<commit_before>$(function() {

    var CHAT = {

        socket        : io.connect('http://localhost:3700'),
        notify        : {},
        notification  : null,
        Notifications : window.Notifications || window.webkitNotifications || window.mozNotifications,
        $name         : $('#name'),
        $message      : $('#message'),
        $send         : $('#send'),
        $notify       : $('#notify'),
        $container    : $('.chat-container'),
        $users        : $('.users'),
        currentUser   : {
            id      : null,
            name    : null,
            session : null
        },

        init : function () {

            var _this = CHAT;

            // Get permission for notifications
            if (_this.Notifications) {
                _this.methods.checkNotificationPermissions();
            }
            else {
                _this.$notify.remove();
            }

            // Initialize events
            _this.events();

        },

        events : function () {

            var _this = CHAT;

            _this.socket.on('user', _this.methods.updateUserList);

            _this.socket.on('typing', _this.methods.updateTypingStatus);

            _this.socket.on('message', _this.methods.appendMessages);

            _this.$send.on('click', _this.methods.sendMessage);

            _this.$message.keyup(function(event){
                if(event.keyCode == 13){
                    _this.$send.trigger('click');
                }
            });

            _this.$message.keyup(function(event) {
                if (event.keyCode !== 13) {
                    _this.methods.sendTyping();
                }
            });

        },

        methods : {

            checkNotificationPermissions : function () {
                if (CHAT.Notifications.checkPermission() === 0) {
                    CHAT.$notify.remove();
                }
                $('#notify, #send').on('click', function () {
                    if (CHAT.Notifications.checkPermission() === 0) { // 0 is PERMISSION_ALLOWED
                        CHAT.$notify.remove();
                    } else {
                        CHAT.Notifications.requestPermission();
                    }
                });
            },

            updateUserList : function (users) {
                var user      = null,
                    userClass = '',
                    sessionId = CHAT.socket.socket.sessionid,
                    _this;

                CHAT.$users.empty();

                for (user in users) {
                    _this = users[user];

                    if (_this.id === sessionId) {
                        userClass = 'current-user';
                        CHAT.$name.val(_this.name).prop('disabled', true);
                        CHAT.currentUser = {
                            id      : _this.id,
                            name    : _this.name,
                            session : sessionId
                        }
                    } else {
                        userClass = '';
                    }

                    CHAT.$users.append('
' + _this.name + '
' + _this.ip + '
');
                }
            },

            appendMessages : function (data) {
                if (data.hasOwnProperty('message')) {
                    var message = CHAT.methods.renderMessage(data.message);

                    CHAT.$container.append('
' + data.username + '' + message + '<time>' + data.timestamp + '</time>
');

                    CHAT.notify.title = data.username + ' says...';
                    CHAT.notify.body = message;

                    CHAT.$container.scrollTop(CHAT.$container[0].scrollHeight);

                    if (CHAT.Notifications && CHAT.notification && !document.hasFocus()) {
                        CHAT.notification = CHAT.Notifications.createNotification('https://scontent-a-lga.xx.fbcdn.net/hphotos-ash2/562136_10150670320458279_1124901033_n.jpg', CHAT.notify.title, CHAT.notify.body);
                        CHAT.notification.onclick = function(x) { window.focus(); this.cancel(); };
                        CHAT.notification.show();

                        notifyCancel = setTimeout(function() {
                            CHAT.notification.cancel();
                        }, 3000);
                    }

                }

                if ($.isArray(data)) {
                    var message;

                    $(data).each(function () {
                        message = CHAT.methods.renderMessage(this.message);
                        CHAT.$container.append('
' + this.username + '' + message + '<time>' + this.timestamp + '</time>
');
                    });
                }
            },

            sendMessage : function () {
                if(!CHAT.$name.val() || !CHAT.$message.val()) {
                    alert('Make sure you entered your name and a message');
                } else {
                    var text     = CHAT.$message.val().replace(/</g, '<'),
                        user     = CHAT.$name.val();

                    CHAT.socket.emit('send', {
                        message   : text,
                        username  : user
                    });

                    CHAT.$message.val('');
                }
            },

            renderMessage : function (message) {
                var text       = message.split(' '),
                    imgRegex   = new RegExp(/\b[A-Za-z0-9:_\/\.\-\+]+(\.gif|\.jpg|\.png)$\b/g),
                    urlRegex   = new RegExp(/\b(^http|www)+[A-Za-z0-9\/\.:]+(?!\.gif|\.jpg|\.png)$\b/g),
                    emoteRegex = new RegExp(/(<)?>?[:=8b](?!$)-?(<)?[3\(\)\[\]>o]?/i),
                    newArr     = [],
                    tmpStr     = '';

                $(text).each(function() {
                    tmp = this;
                    tmp = tmp.replace(imgRegex, '');
                    tmp = tmp.replace(urlRegex, '$&');
                    tmp = tmp.replace(emoteRegex, '$&');
                    newArr.push(tmp);
                });

                return newArr.join(' ');
            },

            sendTyping : function () {
                if (!CHAT.typingTimer) {
                    CHAT.socket.emit('typing', {
                        typing : true,
                        user   : CHAT.currentUser
                    });
                }

                clearTimeout(CHAT.typingTimer);
                CHAT.typingTimer = setTimeout(function () {
                    CHAT.socket.emit('typing', {
                        typing : false,
                        user   : CHAT.currentUser
                    });
                    CHAT.typingTimer = null;
                }, 500);
            },

            updateTypingStatus : function (data) {
                var $user = CHAT.$users.find('div[data-id=' + data.user.id + ']'),
                    $icon = $user.find('i.typing');

                if (data.typing) {
                    $icon.show();
                } else {
                    $icon.hide();
                }
            }

        }
    };

    CHAT.init();

});<commit_msg>Adjusted emoticon regex<commit_after>$(function() {

    var CHAT = {

        socket        : io.connect('http://localhost:3700'),
        notify        : {},
        notification  : null,
        Notifications : window.Notifications || window.webkitNotifications || window.mozNotifications,
        $name         : $('#name'),
        $message      : $('#message'),
        $send         : $('#send'),
        $notify       : $('#notify'),
        $container    : $('.chat-container'),
        $users        : $('.users'),
        currentUser   : {
            id      : null,
            name    : null,
            session : null
        },

        init : function () {

            var _this = CHAT;

            // Get permission for notifications
            if (_this.Notifications) {
                _this.methods.checkNotificationPermissions();
            }
            else {
                _this.$notify.remove();
            }

            // Initialize events
            _this.events();

        },

        events : function () {

            var _this = CHAT;

            _this.socket.on('user', _this.methods.updateUserList);

            _this.socket.on('typing', _this.methods.updateTypingStatus);

            _this.socket.on('message', _this.methods.appendMessages);

            _this.$send.on('click', _this.methods.sendMessage);

            _this.$message.keyup(function(event){
                if(event.keyCode == 13){
                    _this.$send.trigger('click');
                }
            });

            _this.$message.keyup(function(event) {
                if (event.keyCode !== 13) {
                    _this.methods.sendTyping();
                }
            });

        },

        methods : {

            checkNotificationPermissions : function () {
                if (CHAT.Notifications.checkPermission() === 0) {
                    CHAT.$notify.remove();
                }
                $('#notify, #send').on('click', function () {
                    if (CHAT.Notifications.checkPermission() === 0) { // 0 is PERMISSION_ALLOWED
                        CHAT.$notify.remove();
                    } else {
                        CHAT.Notifications.requestPermission();
                    }
                });
            },

            updateUserList : function (users) {
                var user      = null,
                    userClass = '',
                    sessionId = CHAT.socket.socket.sessionid,
                    _this;

                CHAT.$users.empty();

                for (user in users) {
                    _this = users[user];

                    if (_this.id === sessionId) {
                        userClass = 'current-user';
                        CHAT.$name.val(_this.name).prop('disabled', true);
                        CHAT.currentUser = {
                            id      : _this.id,
                            name    : _this.name,
                            session : sessionId
                        }
                    } else {
                        userClass = '';
                    }

                    CHAT.$users.append('
' + _this.name + '
' + _this.ip + '
');
                }
            },

            appendMessages : function (data) {
                if (data.hasOwnProperty('message')) {
                    var message = CHAT.methods.renderMessage(data.message);

                    CHAT.$container.append('
' + data.username + '' + message + '<time>' + data.timestamp + '</time>
');

                    CHAT.notify.title = data.username + ' says...';
                    CHAT.notify.body = message;

                    CHAT.$container.scrollTop(CHAT.$container[0].scrollHeight);

                    if (CHAT.Notifications && CHAT.notification && !document.hasFocus()) {
                        CHAT.notification = CHAT.Notifications.createNotification('https://scontent-a-lga.xx.fbcdn.net/hphotos-ash2/562136_10150670320458279_1124901033_n.jpg', CHAT.notify.title, CHAT.notify.body);
                        CHAT.notification.onclick = function(x) { window.focus(); this.cancel(); };
                        CHAT.notification.show();

                        notifyCancel = setTimeout(function() {
                            CHAT.notification.cancel();
                        }, 3000);
                    }

                }

                if ($.isArray(data)) {
                    var message;

                    $(data).each(function () {
                        message = CHAT.methods.renderMessage(this.message);
                        CHAT.$container.append('
' + this.username + '' + message + '<time>' + this.timestamp + '</time>
');
                    });
                }
            },

            sendMessage : function () {
                if(!CHAT.$name.val() || !CHAT.$message.val()) {
                    alert('Make sure you entered your name and a message');
                } else {
                    var text     = CHAT.$message.val().replace(/</g, '<'),
                        user     = CHAT.$name.val();

                    CHAT.socket.emit('send', {
                        message   : text,
                        username  : user
                    });

                    CHAT.$message.val('');
                }
            },

            renderMessage : function (message) {
                var text       = message.split(' '),
                    imgRegex   = new RegExp(/\b[A-Za-z0-9:_\/\.\-\+]+(\.gif|\.jpg|\.png)$\b/g),
                    urlRegex   = new RegExp(/\b(^http|www)+[A-Za-z0-9\/\.:]+(?!\.gif|\.jpg|\.png)$\b/g),
                    emoteRegex = new RegExp(/(<)?>?[:=8b](?!$|[A-Z])-?(<)?[3\(\)\[\]>]?/i),
                    newArr     = [],
                    tmpStr     = '';

                $(text).each(function() {
                    tmp = this;
                    tmp = tmp.replace(imgRegex, '');
                    tmp = tmp.replace(urlRegex, '$&');
                    tmp = tmp.replace(emoteRegex, '$&');
                    newArr.push(tmp);
                });

                return newArr.join(' ');
            },

            sendTyping : function () {
                if (!CHAT.typingTimer) {
                    CHAT.socket.emit('typing', {
                        typing : true,
                        user   : CHAT.currentUser
                    });
                }

                clearTimeout(CHAT.typingTimer);
                CHAT.typingTimer = setTimeout(function () {
                    CHAT.socket.emit('typing', {
                        typing : false,
                        user   : CHAT.currentUser
                    });
                    CHAT.typingTimer = null;
                }, 500);
            },

            updateTypingStatus : function (data) {
                var $user = CHAT.$users.find('div[data-id=' + data.user.id + ']'),
                    $icon = $user.find('i.typing');

                if (data.typing) {
                    $icon.show();
                } else {
                    $icon.hide();
                }
            }

        }
    };

    CHAT.init();

});<|endoftext|>


<commit_before>var VINYLS = null;
var latestVinyl = null;
var vinylcount = 0;

var Main = (function()
{

  // this is where stuff happens
	function _doAfterLogin(name, fbid){
		_addUserToDb(name, fbid);
    _updateForms(fbid);
		_getExistingData(fbid);
	}

	// Add username with his fb id to db
	function _addUserToDb(name, fbid){
  	//console.log('calling ajax with '+name+' and '+fbid);
  	$.ajax({
    		type: 'POST',
    		url: './php/createuser.php',
    		data: {
      		username: name,
      		facebookid: fbid
   		},
    		success: function (response) {
      		console.log("record has been saved in database: "+response);
    		},
    		error: function () {
      		console.warn('there is some error in the createuser ajax request');
    		}
  	});
	}

  // Update Add and Edit forms with hidden input containing FB ID
  function _updateForms(fbid){
    if(!$('#hiddenfbidinput').length){ // if not already present
      $('#addvinylform').prepend('<input type="hidden" id="hiddenfbidinput" name="fbid" value="'+fbid+'">');
    }
  }

  // After logged in, get users vinyl Data and display it on success
	function _getExistingData(fbid){
    //console.log("calling _getExistingData");
		$.ajax({
    		type: 'POST',
    		url: './php/getuservinyls.php',
    		data: {
      		facebookid: fbid
   		},
    		success: function (response) {
          //console.log(response);
          if(response.length){
            VINYLS = $.parseJSON(response);
            _displayVinylData(VINYLS); // display the resceived data
          }
    		},
    		error: function () {
      		console.warn('there is some error in the getuservinyls ajax request');
    		}
  	});
	}

  // Build actual Vinyl List and display it
  function _displayVinylData(vinyls){

    var index = 0;

    $.each(vinyls, function(){
      content = '
';
      content += '

	'
      content += ''+VINYLS[index].VinylID+'	';
      content += ''+VINYLS[index].Artist+'	';
      content += ''+VINYLS[index].Album+'	';
      content += ''+VINYLS[index].Label+'	';
      content += ''+VINYLS[index].Format+' '+VINYLS[index].Type+'	';
      content += ''+VINYLS[index].Year+'	';
      content += ''+VINYLS[index].Price+' €	';
      content += ''+VINYLS[index].Catalog+'	';
      content += ''+VINYLS[index].Genre+'	';
      content += '	';
      content += '
';

      $('#tablecontent').append(content);
      index += 1;
    });

    // redraw the whole table
    $('.footable').trigger('footable_initialize');

    // update vinyl count
    vinylcount = vinyls.length;
    $('#vinylcount').text(vinylcount);
  }

  // Get Vinyl Artworks from Google
  function _getVinylArtwork(){

  }

  // check if element is in viewport or not (maybe used later)
  function _isScrolledIntoView(elem){
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
      && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
  }

	return{
		doAfterLogin: _doAfterLogin,
		addUserToDb: _addUserToDb,
    updateForms: _updateForms,
		getExistingData: _getExistingData,
    displayVinylData: _displayVinylData,
    getVinylArtwork: _getVinylArtwork,
    isScrolledIntoView: _isScrolledIntoView
	}

})();

/* === Global Actions =========== */

$(document).ready(function(){
  console.log('document ready!');

  // Options for the "Add Vinyl" Ajax call
  var options = {
    target:        '#response',   // target element(s) to be updated with server response
    success:       successCallback,  // post-submit callback
    clearForm:     true        // clear all form fields after successful submit

    // other available options:
    //url:       url         // override for form's 'action' attribute
    //type:      type        // 'get' or 'post', override for form's 'method' attribute
    //dataType:  null        // 'xml', 'script', or 'json' (expected server response type)
    //resetForm: true        // reset the form after successful submit

    // $.ajax options can be used here too, for example:
    //timeout:   3000
  };

  // Submit Add Vinyl Form and send Ajax request with form data
  $('#addvinylform').ajaxForm(options, function() {
    alert("Thank you!");
  });

  function successCallback(response){
    var footable = $('.footable').data('footable');

    // Display added vinyl
    if(response.length){
      latestVinyl = $.parseJSON(response);
      var row = '
';
      row += '

	';
      row += ''+latestVinyl[0].VinylID+'	';
      row += ''+latestVinyl[0].Artist+'	';
      row += ''+latestVinyl[0].Album+'	';
      row += ''+latestVinyl[0].Label+'	';
      row += ''+latestVinyl[0].Format+' '+latestVinyl[0].Type+'	';
      row += ''+latestVinyl[0].Year+'	';
      row += ''+latestVinyl[0].Price+' €	';
      row += ''+latestVinyl[0].Catalog+'	';
      row += ''+latestVinyl[0].Genre+'	';
      row += '	';
      row+= '
';
    }

    // Redraw the table
    footable.appendRow(row);
    footable.redraw();

    // Update the vinyl count
    vinylcount = vinylcount+1;
    $('#vinylcount').text(vinylcount);
  }

  // === ADD VINYL OVERLAY =========================================================

  // open overlay with add vinyl form
  $('#loggedInWrapper').on('click', '#addvinyl', function(){
    $('#overlay').fadeIn(200, function(){
      $(this).append('');
    });
  });

  // close overlay
  $('#overlay').on('click', '.close', function(){
    //$('#addVinylForm').remove();
    $('#overlay').fadeOut(200);
  })

  // === DELETE VINYL =====================================================

  $('#loggedInWrapper').on('click', '.delete', function(){
    // get Vinly ID from DOM
    var id = $(this).parent().siblings('.vinyl-id').text();
    var row = $(this).parents('tr:first');

    // confirm delete
    var r=confirm("Do you really want to delete this vinyl?");
    if (r==true)
    {
      $.ajax({
        type: 'POST',
        url: './php/deletevinyl.php',
        data: {
          facebookid: FBDATA.id,
          vinylid: id
        },
        success: function (response) {
          // remove vinyl from table
          var footable = $('.footable').data('footable');
          footable.removeRow(row);

          // update vinyl count
          vinylcount = vinylcount - 1;
          $('#vinylcount').text(vinylcount);
        },
        error: function () {
          console.warn('could not delete vinyl, ajax request failed');
        }
      });
    }
  });

});

<commit_msg>now loading album cover artworks<commit_after>var VINYLS = null;
var latestVinyl = null;
var vinylcount = 0;

var Main = (function()
{

  // this is where stuff happens
	function _doAfterLogin(name, fbid){
		_addUserToDb(name, fbid);
    _updateForms(fbid);
		_getExistingData(fbid);
	}

	// Add username with his fb id to db
	function _addUserToDb(name, fbid){
  	//console.log('calling ajax with '+name+' and '+fbid);
  	$.ajax({
    		type: 'POST',
    		url: './php/createuser.php',
    		data: {
      		username: name,
      		facebookid: fbid
   		},
    		success: function (response) {
      		console.log("record has been saved in database: "+response);
    		},
    		error: function () {
      		console.warn('there is some error in the createuser ajax request');
    		}
  	});
	}

  // Update Add and Edit forms with hidden input containing FB ID
  function _updateForms(fbid){
    if(!$('#hiddenfbidinput').length){ // if not already present
      $('#addvinylform').prepend('<input type="hidden" id="hiddenfbidinput" name="fbid" value="'+fbid+'">');
    }
  }

  // After logged in, get users vinyl Data and display it on success
	function _getExistingData(fbid){
    //console.log("calling _getExistingData");
		$.ajax({
    		type: 'POST',
    		url: './php/getuservinyls.php',
    		data: {
      		facebookid: fbid
   		},
    		success: function (response) {
          //console.log(response);
          if(response.length){
            VINYLS = $.parseJSON(response);
            _displayVinylData(VINYLS); // display the resceived data
          }
    		},
    		error: function () {
      		console.warn('there is some error in the getuservinyls ajax request');
    		}
  	});
	}

  // Build actual Vinyl List and display it
  function _displayVinylData(vinyls){

    var index = 0;

    $.each(vinyls, function(){
      content = '
';
      content += '

	'
      content += ''+vinyls[index].VinylID+'	';
      content += ''+vinyls[index].Artist+'	';
      content += ''+vinyls[index].Album+'	';
      content += ''+vinyls[index].Label+'	';
      content += ''+vinyls[index].Format+' '+vinyls[index].Type+'	';
      content += ''+vinyls[index].Year+'	';
      content += ''+vinyls[index].Price+' €	';
      content += ''+vinyls[index].Catalog+'	';
      content += ''+vinyls[index].Genre+'	';
      content += '	';
      content += '
';

      $('#tablecontent').append(content);
      index += 1;
    });

    // redraw the whole table
    $('.footable').trigger('footable_initialize');

    // update vinyl count
    vinylcount = vinyls.length;
    $('#vinylcount').text(vinylcount);

    // get Vinyl Artworks
    _getVinylArtwork(vinyls);
  }

  // Get all Vinyl Artworks from Google
  function _getVinylArtwork(vinyls){

    var count = 0;
    var index = 0;

    $.each(vinyls, function(){
      console.log("calling getJSON with index="+index);
      $.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q='+vinyls[index].Artist+' '+vinyls[index].Album+'&v=1.0&callback=?',
      function(data) {
        console.log(data.responseData.results[0].unescapedUrl);
        console.log(vinyls, count);
        $('#tablecontent').find('.vinyl-artwork').eq(count).html('');
        count += 1;
      });

      index += 1;
    });
  }

  // check if element is in viewport or not (maybe used later)
  function _isScrolledIntoView(elem){
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
      && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
  }

	return{
		doAfterLogin: _doAfterLogin,
		addUserToDb: _addUserToDb,
    updateForms: _updateForms,
		getExistingData: _getExistingData,
    displayVinylData: _displayVinylData,
    getVinylArtwork: _getVinylArtwork,
    isScrolledIntoView: _isScrolledIntoView
	}

})();

/* === Global Actions =========== */

$(document).ready(function(){
  console.log('document ready!');

  // Options for the "Add Vinyl" Ajax call
  var options = {
    target:        '#response',   // target element(s) to be updated with server response
    success:       successCallback,  // post-submit callback
    clearForm:     true        // clear all form fields after successful submit

    // other available options:
    //url:       url         // override for form's 'action' attribute
    //type:      type        // 'get' or 'post', override for form's 'method' attribute
    //dataType:  null        // 'xml', 'script', or 'json' (expected server response type)
    //resetForm: true        // reset the form after successful submit

    // $.ajax options can be used here too, for example:
    //timeout:   3000
  };

  // Submit Add Vinyl Form and send Ajax request with form data
  $('#addvinylform').ajaxForm(options, function() {
    alert("Thank you!");
  });

  function successCallback(response){
    var footable = $('.footable').data('footable');

    // Display added vinyl
    if(response.length){
      latestVinyl = $.parseJSON(response);
      var row = '
';
      row += '

	';
      row += ''+latestVinyl[0].VinylID+'	';
      row += ''+latestVinyl[0].Artist+'	';
      row += ''+latestVinyl[0].Album+'	';
      row += ''+latestVinyl[0].Label+'	';
      row += ''+latestVinyl[0].Format+' '+latestVinyl[0].Type+'	';
      row += ''+latestVinyl[0].Year+'	';
      row += ''+latestVinyl[0].Price+' €	';
      row += ''+latestVinyl[0].Catalog+'	';
      row += ''+latestVinyl[0].Genre+'	';
      row += '	';
      row+= '
';
    }

    // Redraw the table
    footable.appendRow(row);
    footable.redraw();

    // Update the vinyl count
    vinylcount = vinylcount+1;
    $('#vinylcount').text(vinylcount);
  }

  // === ADD VINYL OVERLAY =========================================================

  // open overlay with add vinyl form
  $('#loggedInWrapper').on('click', '#addvinyl', function(){
    $('#overlay').fadeIn(200, function(){
      $(this).append('');
    });
  });

  // close overlay
  $('#overlay').on('click', '.close', function(){
    //$('#addVinylForm').remove();
    $('#overlay').fadeOut(200);
  })

  // === DELETE VINYL =====================================================

  $('#loggedInWrapper').on('click', '.delete', function(){
    // get Vinly ID from DOM
    var id = $(this).parent().siblings('.vinyl-id').text();
    var row = $(this).parents('tr:first');

    // confirm delete
    var r=confirm("Do you really want to delete this vinyl?");
    if (r==true)
    {
      $.ajax({
        type: 'POST',
        url: './php/deletevinyl.php',
        data: {
          facebookid: FBDATA.id,
          vinylid: id
        },
        success: function (response) {
          // remove vinyl from table
          var footable = $('.footable').data('footable');
          footable.removeRow(row);

          // update vinyl count
          vinylcount = vinylcount - 1;
          $('#vinylcount').text(vinylcount);
        },
        error: function () {
          console.warn('could not delete vinyl, ajax request failed');
        }
      });
    }
  });

});

<|endoftext|>


<commit_before>/* Minecraft Server Status Checker V2.4

Copyright (c) 2014 Jeremy Lam (JLChnToZ)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
$(function() {
  var allmodes = [
    ["legacy_ping", "ping"],
    ["full_query", "basic_query"]
  ],
    done = 0,
    lang = new Lang('en'),
    searchquery = location.search;

  var supports_storage = (function() {
    try {
      return 'localStorage' in window && window['localStorage'] !== null;
    } catch (e) {
      return false;
    }
  })();

  function set_theme(theme) {
    $('link#themecss').attr('href', theme);
  }

  function onSubmit(form, newstate) {
    if (history.pushState && newstate) {
      var host = $("#id_host").val(),
        port = $("#id_port").val();
      var _state = {
        host: host,
        port: port
      };
      if(!_.isEqual(history.state, _state))
        history.pushState(_state, 'request: ' + host + ':' + port, '?' + host + ':' + port);
    }
    $("#querybutton").button('loading');
    var called = false;
    $(".info, #noresponse").fadeOut("slow", function() {
      if (!called) called = true;
      else return;
      $(".val, #players, #pluginscontent").empty();
      $("#servericon, .nfo, #infoplayers, #pluginscontent").hide();
      $("#noplugins, #noplayers").show();
      done = 0;
      tryRequest(form.serialize(), 0, 0);
      setTimeout(function() {
        tryRequest(form.serialize(), 1, 0);
      }, 2500);
    });
  }

  function $create(elm) {
    return $(document.createElement(elm));
  }

  function tryRequest(form, mode, trial) {
    $.getJSON("json.php", form + "&mode=" + allmodes[mode][trial], function(x, h, r) {
      if (x.err || x == false) return;
      $(".info").each(function(i) {
        $(this).delay(i * 250).fadeIn("slow");
      });
      $("#infotitle").text((x.ip ? x.ip : $("#id_host").val()) + ":" + $("#id_port").val());
      showcontent("#motd", x.motd, 0);
      showcontent("#sversion", x.server_version, -1);
      showcontent("#latency", x.latency, -1);
      showcontent("#map", x.map, -1);
      showcontent("#gametype", x.gametype, -1);
      if (x.plugins && x.plugins.length > 0) {
        $("#noplugins").hide();
        $("#pluginscontent").show();
        var arr = x.plugins.split(";");
        for (var i = 0; i < arr.length; i++)
          $("#pluginscontent").append($create('li').addClass("col-xs-12 col-sm-6 col-lg-4").text(arr[i])
            .hide().delay(i * 100).fadeIn("slow"));
      }
      if (x.icon && x.icon.length > 0) $("#servericon").attr("src", x.icon).fadeIn("slow");
      if (x.player_count || x.player_max || x.player_count === 0 || x.player_max === 0) {
        $("#infoplayers").show();
        $("#pmax").toggle(x.player_count >= x.player_max);
        $("#pcount").toggle(x.player_count < x.player_max).text(x.player_count ? x.player_count : '?');
        $("#pcountmax").text(x.player_max ? x.player_max : '?');
      }
      if (x.players && x.players.length > 0) {
        $("#noplayers").hide();
        $("#players").fadeOut("fast").empty().fadeIn("fast", function() {
          var isPlayerData = true, i;
          for (i = 0; i < x.players.length; i++) // Check if those are really player data
            if(!/^\w{1,16}$/.test(x.players[i])) {
              isPlayerData = false;
              break;
            }
          if(isPlayerData) {
            for (i = 0; i < x.players.length; i++)
              $("#players").append(
                $create('div').addClass("player").append(
                  $create('div').addClass("mc-skin").data("minecraft-username", x.players[i])
                ).append(
                  $create('span').addClass("label label-default").text(x.players[i]).minecraftFormat()
                ).hide().delay(i * 100).fadeIn("slow")
              );
            $(".mc-skin").minecraftSkin({
              scale: 2,
              hat: true
            });
          } else // Non-player data is shown
            for (i = 0; i < x.players.length; i++)
              $("#players").append(
                $create('span').addClass("moreinfo").text(x.players[i]).minecraftFormat()
                .hide().delay(i * 100).fadeIn("slow")
              );
        });
      }
      haveResponse = true;
    }).complete(function(x, s) {
      if (trial + 1 < allmodes[mode].length) setTimeout(function() {
        tryRequest(form, mode, trial + 1);
      }, 5000);
      else callDone();
    });
  }

  function callDone() {
    done++;
    if (done >= allmodes.length) {
      $("#querybutton").button('reset');
      if(!haveResponse)
        $("#noresponse").fadeIn("slow");
    }
  }

  function showcontent(id, content, formatColor) {
    var $target = $(id);
    var $child = $target.children(".val");
    if (content && content.toString().length > 0) {
      $target.show();
      $child.text(content);
      if (formatColor >= 0) $child.minecraftFormat(formatColor);
    }
    return $child;
  }

  function autoload(query) {
    if (typeof(query) == "string" && query.length > 0) {
      var q = query.split(":");
      query = {
        host: q[0],
        port: q[1] ? q[1] : 25565
      };
    } else if (!query) return;
    $("#id_host").val(query['host']);
    $("#id_port").val(query['port']);
    onSubmit($("#requestform"), false);
    return query;
  }

  $("#requestform").submit(function(e) {
    e.preventDefault();
    onSubmit($(this), true);
  });

  $(".changelang").each(function() {
    var $this = $(this), langcode = $this.attr("href").substring(1);
    if(lang.defaultLang != langcode)
      lang.dynamic(langcode, $this.data("lang-path"));
  });

  $('body')
  .on('click', '.change-style-menu-item a', function(e) {
    e.preventDefault();
    set_theme($(this).data("css"));
    if(supports_storage)
      window.localStorage.theme = $(this).data("css");
  })
  .on('click', '.changelang', function(e){
    e.preventDefault();
    lang.change($(this).attr("href").substring(1));
  })
  .tooltip({
    selector: ".change-style-menu-item",
    placement: "left"
  });

  $.get("http://api.bootswatch.com/3/", function (data) {
    var themes = data.themes;
    $.each(themes, function() {
      $("#theme-select").append(
        $("

")
        .addClass("change-style-menu-item")
        .attr({
          title: this.description
        })
        .append(
          $("")
          .data("css", this.cssMin)
          .append(this.name)
          .attr({
            href: "###"
          })
        )
      );
    });
  }, "json");

  if(supports_storage) {
    var t = window.localStorage.theme;
    if(t) set_theme(t);
  }

  window.onpopstate = function(e) {
    autoload(e.state);
  };

  if (searchquery && searchquery.length > 1) {
    var q = autoload(searchquery.substring(1));
    if(history.replaceState)
      history.replaceState(q, 'request: ' + q.host + ':' + q.port, '?' + q.host + ':' + q.port);
  }
});
<commit_msg>Missing some variables...<commit_after>/* Minecraft Server Status Checker V2.4

Copyright (c) 2014 Jeremy Lam (JLChnToZ)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
$(function() {
  var allmodes = [
    ["legacy_ping", "ping"],
    ["full_query", "basic_query"]
  ],
    done = 0,
    haveResponse = false,
    lang = new Lang('en'),
    searchquery = location.search;

  var supports_storage = (function() {
    try {
      return 'localStorage' in window && window['localStorage'] !== null;
    } catch (e) {
      return false;
    }
  })();

  function set_theme(theme) {
    $('link#themecss').attr('href', theme);
  }

  function onSubmit(form, newstate) {
    if (history.pushState && newstate) {
      var host = $("#id_host").val(),
        port = $("#id_port").val();
      var _state = {
        host: host,
        port: port
      };
      if(!_.isEqual(history.state, _state))
        history.pushState(_state, 'request: ' + host + ':' + port, '?' + host + ':' + port);
    }
    $("#querybutton").button('loading');
    var called = false;
    haveResponse = false;
    $(".info, #noresponse").fadeOut("slow", function() {
      if (!called) called = true;
      else return;
      $(".val, #players, #pluginscontent").empty();
      $("#servericon, .nfo, #infoplayers, #pluginscontent").hide();
      $("#noplugins, #noplayers").show();
      done = 0;
      tryRequest(form.serialize(), 0, 0);
      setTimeout(function() {
        tryRequest(form.serialize(), 1, 0);
      }, 2500);
    });
  }

  function $create(elm) {
    return $(document.createElement(elm));
  }

  function tryRequest(form, mode, trial) {
    $.getJSON("json.php", form + "&mode=" + allmodes[mode][trial], function(x, h, r) {
      if (x.err || x == false) return;
      $(".info").each(function(i) {
        $(this).delay(i * 250).fadeIn("slow");
      });
      $("#infotitle").text((x.ip ? x.ip : $("#id_host").val()) + ":" + $("#id_port").val());
      showcontent("#motd", x.motd, 0);
      showcontent("#sversion", x.server_version, -1);
      showcontent("#latency", x.latency, -1);
      showcontent("#map", x.map, -1);
      showcontent("#gametype", x.gametype, -1);
      if (x.plugins && x.plugins.length > 0) {
        $("#noplugins").hide();
        $("#pluginscontent").show();
        var arr = x.plugins.split(";");
        for (var i = 0; i < arr.length; i++)
          $("#pluginscontent").append($create('li').addClass("col-xs-12 col-sm-6 col-lg-4").text(arr[i])
            .hide().delay(i * 100).fadeIn("slow"));
      }
      if (x.icon && x.icon.length > 0) $("#servericon").attr("src", x.icon).fadeIn("slow");
      if (x.player_count || x.player_max || x.player_count === 0 || x.player_max === 0) {
        $("#infoplayers").show();
        $("#pmax").toggle(x.player_count >= x.player_max);
        $("#pcount").toggle(x.player_count < x.player_max).text(x.player_count ? x.player_count : '?');
        $("#pcountmax").text(x.player_max ? x.player_max : '?');
      }
      if (x.players && x.players.length > 0) {
        $("#noplayers").hide();
        $("#players").fadeOut("fast").empty().fadeIn("fast", function() {
          var isPlayerData = true, i;
          for (i = 0; i < x.players.length; i++) // Check if those are really player data
            if(!/^\w{1,16}$/.test(x.players[i])) {
              isPlayerData = false;
              break;
            }
          if(isPlayerData) {
            for (i = 0; i < x.players.length; i++)
              $("#players").append(
                $create('div').addClass("player").append(
                  $create('div').addClass("mc-skin").data("minecraft-username", x.players[i])
                ).append(
                  $create('span').addClass("label label-default").text(x.players[i]).minecraftFormat()
                ).hide().delay(i * 100).fadeIn("slow")
              );
            $(".mc-skin").minecraftSkin({
              scale: 2,
              hat: true
            });
          } else // Non-player data is shown
            for (i = 0; i < x.players.length; i++)
              $("#players").append(
                $create('span').addClass("moreinfo").text(x.players[i]).minecraftFormat()
                .hide().delay(i * 100).fadeIn("slow")
              );
        });
      }
      haveResponse = true;
    }).complete(function(x, s) {
      if (trial + 1 < allmodes[mode].length) setTimeout(function() {
        tryRequest(form, mode, trial + 1);
      }, 5000);
      else callDone();
    });
  }

  function callDone() {
    done++;
    if (done >= allmodes.length) {
      $("#querybutton").button('reset');
      if(!haveResponse)
        $("#noresponse").fadeIn("slow");
    }
  }

  function showcontent(id, content, formatColor) {
    var $target = $(id);
    var $child = $target.children(".val");
    if (content && content.toString().length > 0) {
      $target.show();
      $child.text(content);
      if (formatColor >= 0) $child.minecraftFormat(formatColor);
    }
    return $child;
  }

  function autoload(query) {
    if (typeof(query) == "string" && query.length > 0) {
      var q = query.split(":");
      query = {
        host: q[0],
        port: q[1] ? q[1] : 25565
      };
    } else if (!query) return;
    $("#id_host").val(query['host']);
    $("#id_port").val(query['port']);
    onSubmit($("#requestform"), false);
    return query;
  }

  $("#requestform").submit(function(e) {
    e.preventDefault();
    onSubmit($(this), true);
  });

  $(".changelang").each(function() {
    var $this = $(this), langcode = $this.attr("href").substring(1);
    if(lang.defaultLang != langcode)
      lang.dynamic(langcode, $this.data("lang-path"));
  });

  $('body')
  .on('click', '.change-style-menu-item a', function(e) {
    e.preventDefault();
    set_theme($(this).data("css"));
    if(supports_storage)
      window.localStorage.theme = $(this).data("css");
  })
  .on('click', '.changelang', function(e){
    e.preventDefault();
    lang.change($(this).attr("href").substring(1));
  })
  .tooltip({
    selector: ".change-style-menu-item",
    placement: "left"
  });

  $.get("http://api.bootswatch.com/3/", function (data) {
    var themes = data.themes;
    $.each(themes, function() {
      $("#theme-select").append(
        $("

")
        .addClass("change-style-menu-item")
        .attr({
          title: this.description
        })
        .append(
          $("")
          .data("css", this.cssMin)
          .append(this.name)
          .attr({
            href: "###"
          })
        )
      );
    });
  }, "json");

  if(supports_storage) {
    var t = window.localStorage.theme;
    if(t) set_theme(t);
  }

  window.onpopstate = function(e) {
    autoload(e.state);
  };

  if (searchquery && searchquery.length > 1) {
    var q = autoload(searchquery.substring(1));
    if(history.replaceState)
      history.replaceState(q, 'request: ' + q.host + ':' + q.port, '?' + q.host + ':' + q.port);
  }
});
<|endoftext|>


<commit_before>$(document).ready(function() {
  $("#more-1").click(function() {
    $(".more-1").toggleClass("hidden");
    // if ($('.more-1').hasClass('hidden')) {
    //   $('.more-1').fadeIn().removeClass("hidden")
    // } else {
    //   $('.more-1').fadeOut().delay()addClass("hidden")
    // }
    if ($(".more-1").hasClass("hidden")) {
      $("#more-1").text("MORE");
    } else {
      $("#more-1").text("LESS");
    }
  });
  $("#more-2").click(function() {
    $(".more-2").toggleClass("hidden");
    if ($(".more-2").hasClass("hidden")) {
      $("#more-2").text("MORE");
    } else {
      $("#more-2").text("LESS");
    }
  });
  $("#more-3").click(function() {
    $(".more-3").toggleClass("hidden");
    if ($(".more-3").hasClass("hidden")) {
      $("#more-3").text("MORE");
    } else {
      $("#more-3").text("LESS");
    }
  });
});

var wavesurfer = WaveSurfer.create({
  container: "#waveform",
  waveColor: "#dd621c",
  progressColor: "#4CDD28",
  height: 88
});

var IS_PLAYING = false;
var CURRENT_EPISODE;
var CONTROLS_VISIBLE = false;
var WAVEFORM_VISIBLE = true;

function playOrPause(episodeName) {
  if (CURRENT_EPISODE !== episodeName) {
    wavesurfer.stop();
    CURRENT_EPISODE = episodeName;
    console.log('====================================');
    console.log('PLAYING');
    console.log('====================================');
    wavesurfer.load("../media/" + episodeName + ".mp3");
    wavesurfer.on("ready", function() {
      wavesurfer.play();
      IS_PLAYING = true;
      if (!CONTROLS_VISIBLE) {
        $(".controls").fadeToggle();
        CONTROLS_VISIBLE = true;
      }
      if (!WAVEFORM_VISIBLE) {
        $("#waveform").fadeTo("500", 1);
        WAVEFORM_VISIBLE = true;
      }
    });
  } else {
    if (IS_PLAYING) {
      wavesurfer.pause();
      IS_PLAYING = false;
    } else {
      wavesurfer.play();
      IS_PLAYING = true;
    }
  }
}

function play() {
  wavesurfer.play();
  IS_PLAYING = true;
}

function pause() {
  wavesurfer.pause();
  IS_PLAYING = false;
}

function stop() {
  $(".controls").fadeToggle();
  $("#waveform").fadeTo("500", 0);
  CONTROLS_VISIBLE = false;
  WAVEFORM_VISIBLE = false;
  IS_PLAYING = false;
  wavesurfer.stop();
}
<commit_msg>reset<commit_after>$(document).ready(function() {
  $("#more-1").click(function() {
    $(".more-1").toggleClass("hidden");
    // if ($('.more-1').hasClass('hidden')) {
    //   $('.more-1').fadeIn().removeClass("hidden")
    // } else {
    //   $('.more-1').fadeOut().delay()addClass("hidden")
    // }
    if ($(".more-1").hasClass("hidden")) {
      $("#more-1").text("MORE");
    } else {
      $("#more-1").text("LESS");
    }
  });
  $("#more-2").click(function() {
    $(".more-2").toggleClass("hidden");
    if ($(".more-2").hasClass("hidden")) {
      $("#more-2").text("MORE");
    } else {
      $("#more-2").text("LESS");
    }
  });
  $("#more-3").click(function() {
    $(".more-3").toggleClass("hidden");
    if ($(".more-3").hasClass("hidden")) {
      $("#more-3").text("MORE");
    } else {
      $("#more-3").text("LESS");
    }
  });
});

var wavesurfer = WaveSurfer.create({
  container: "#waveform",
  waveColor: "#dd621c",
  progressColor: "#4CDD28",
  height: 88
});

var IS_PLAYING = false;
var CURRENT_EPISODE;
var CONTROLS_VISIBLE = false;
var WAVEFORM_VISIBLE = true;

function playOrPause(episodeName) {
  if (CURRENT_EPISODE !== episodeName) {
    wavesurfer.stop();
    CURRENT_EPISODE = episodeName;
    console.log('====================================');
    console.log('PLAYING');
    console.log('====================================');
    wavesurfer.load("../media/" + episodeName + ".mp3");
    wavesurfer.on("ready", function() {
      wavesurfer.play();
      IS_PLAYING = true;
      if (!CONTROLS_VISIBLE) {
        $(".controls").fadeToggle();
        CONTROLS_VISIBLE = true;
      }
      if (!WAVEFORM_VISIBLE) {
        $("#waveform").fadeTo("500", 1);
        WAVEFORM_VISIBLE = true;
      }
    });
  } else {
    if (IS_PLAYING) {
      wavesurfer.pause();
      IS_PLAYING = false;
    } else {
      wavesurfer.play();
      IS_PLAYING = true;
    }
  }
}

function play() {
  wavesurfer.play();
  IS_PLAYING = true;
}

function pause() {
  wavesurfer.pause();
  IS_PLAYING = false;
}

function stop() {
  $(".controls").fadeToggle();
  $("#waveform").fadeTo("500", 0);
  CONTROLS_VISIBLE = false;
  WAVEFORM_VISIBLE = false;
  IS_PLAYING = false;
  CURRENT_EPISODE= '';
  wavesurfer.stop();
}
<|endoftext|>


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

//
// Commons
//

var startDate,
	endDate,
	initialPosition,
	spatialPoints = [],
	entities = {};

function entity() {

	// Setters
	this.id = function(_) {
      if (!arguments.length) return id;
      id = _;
      return this;
    };

    this.points = function(_) {
      if (!arguments.length) return points;
      points = _;
      return this;
    };

}

//
// Helpers
//

function formatDate(date) {
	return d3.time.format("%Y-%m-%d %H:%M:%S").parse(date);
}

function print_filter(filter){
	var f=eval(filter);
	if (typeof(f.length) != "undefined") {}else{}
	if (typeof(f.top) != "undefined") {f=f.top(Infinity);}else{}
	if (typeof(f.dimension) != "undefined") {f=f.dimension(function(d) { return "";}).top(Infinity);}else{}
	console.log(filter+"("+f.length+") = "+JSON.stringify(f).replace("[","[\n\t").replace(/}\,/g,"},\n\t").replace("]","\n]"));
}

//
// Setup
//

minDate = formatDate("2008-10-28 00:00:00");
maxDate = formatDate("2008-10-28 23:59:59");
startDate = formatDate("2008-10-28 07:00:00");
endDate = formatDate("2008-10-28 13:00:46");
initialPosition = [39.94403, 116.407526]; // beijing

//
// Slider
//

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];

$("#slider").dateRangeSlider({
	bounds: {min: minDate, max: maxDate},
	defaultValues: {min: startDate, max: endDate},
	wheelMode: "scroll",
	wheelSpeed: 10,
	step: {
	    minutes: 5
	},
	formatter: function(val) {
		var format = d3.time.format("%Y-%m-%d %H:%M");
		return format(val);
	},
	scales: [{
	  first: function(value) { return value; },
	  end: function(value) {return value; },
	  next: function(value) {
	    var next = new Date(value);
	    return new Date(next.setMinutes(value.getMinutes() + 60));
	  },
	  label: function(value){
	  	console.log(value);
	  	var next = new Date(value);
	    return next.getHours()+1;
	  },
	  format: function(tickContainer, tickStart, tickEnd){
	    tickContainer.addClass("myCustomClass");
	  }
	}]
});

/*,
scales: [{
  first: function(value){ return value; },
  end: function(value) {return value; },
  next: function(value){
    var next = new Date(value);
    return new Date(next.setMonth(value.getMonth() + 1));
  },
  label: function(value){
    return months[value.getMonth()];
  },
  format: function(tickContainer, tickStart, tickEnd){
    tickContainer.addClass("myCustomClass");
  }
}]*/

d3.csv("csv/182-29out-5min.csv", function(collection) {

	$('.inner').delay(3000).fadeTo('slow', 0.4);

	// when hover over text
	$('.inner').hover(
		function(){
			$('.inner').stop().fadeTo('slow', 1);
		},
		function(){
			$('.inner').stop().delay(500).fadeTo('slow', 0.4);
		}
	);

	spatialPoints = [];

	function convertTimestampToUTCDate(timestampInSeconds) {
		var targetTime = new Date(timestampInSeconds*1000);
		return new Date(targetTime.getUTCFullYear(), targetTime.getUTCMonth(), targetTime.getUTCDate(),  targetTime.getUTCHours(), targetTime.getUTCMinutes(), targetTime.getUTCSeconds());
	}

	// Add a LatLng object to each item in the dataset
	collection.forEach(function(d) {
		spatialPoints.push({
			coordinates: new L.LatLng(d.lat, d.lng),
			date: convertTimestampToUTCDate(d.timestamp),
			user: parseInt(d.user)
		});
	});

	$("#slider").bind("valuesChanging", function(e, data){
		updatePointsWithRange([data.values.min, data.values.max]);
	});

	//
	// CROSSFILTER
	//

	var spatial = crossfilter(spatialPoints),
		all = spatial.groupAll(),
		dateDimension = spatial.dimension(function (d) { return d.date; }),
		usersDimension = spatial.dimension(function(d) { return d.user; }),
		usersGroup = usersDimension.group(),
		users = [];

	getDistinctUsers();

	function filterSpatialPointsWithRange(range) {
		entities = {};
		dateDimension.filterRange(range);
		dateDimension.top(Infinity).forEach(function (d) {
			// First time
			if (!entities[d.user]) {
				entities[d.user] = [];
			}
			// Add point to entity
			entities[d.user].push(d.coordinates);
		});
	}

	function getDistinctUsers() {
		usersGroup.top(Infinity).forEach(function (d) {
			users.push({user: d.key});
		});
		$("#active").html(users.length);
	}

	// Count total number of points
	var n = all.reduceCount().value();
	console.log("There are " + n + " points in total.");

	//
	// MAP
	//

	var map = L.map('map').setView(initialPosition, 11),
		maplink = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
						attribution: '© OpenStreetMap',
						maxZoom: 18,
					}).addTo(map);

	// Initialize the SVG layer */
	map._initPathRoot();

	// Pick up the SVG from the map object */
	var svg = d3.select("#map").select("svg"),
		mapTrails = svg.append("g"),
		mapPoints = svg.append("g");

	// Use Leaflet to implement a D3 geometric transformation.
	function projectPoint(x, y) {
		var point = map.latLngToLayerPoint(new L.LatLng(x, y));
		this.stream.point(point.x, point.y);
	}

	var transform = d3.geo.transform({point: projectPoint}),
		path = d3.geo.path().projection(transform);

	//
	// Points
	//

	filterSpatialPointsWithRange([startDate, endDate]);

	var pointers = mapPoints
		.selectAll("circle")
		.data(users)
		.enter()
		.append("circle")
		.attr("r", 5)
		.attr("fill", "#CC0099")
		.attr("fill-opacity", 1)
		.attr("stroke", "black")
		.attr("stroke-width", 2)
		.attr("stroke-opacity", 1)
		.attr("opacity", 1)
		;

	var trails = mapTrails
		.selectAll("path")
		.data(users)
		.enter()
		.append("path")
		.attr("fill", "none")
        .attr("stroke", "#842DCE")
        .attr("stroke-width", 3)
        ;

	function render() {
		pointers.attr("transform", function (d) {
			var coordinates = entities[d.user];
			if (coordinates && coordinates.length>0) {
				var header = coordinates[0];
				return "translate("+
					map.latLngToLayerPoint(header).x +","+
					map.latLngToLayerPoint(header).y +")";
			} else {
				return "translate(-5,-5)";
			}
		});
		trails.attr("d", function (d) {
			var coordinates = entities[d.user];
			if (coordinates && coordinates.length>0) {
				return path({type: "LineString", coordinates: convertToArrayXY(coordinates)});
			} else {
				return "M0,0";
			}
		});
	}

	function updateOnResize() {
		render();
	}

	function updatePointsWithRange(range) {
		filterSpatialPointsWithRange(range);
		render();
	}

	function convertToArrayXY(coordinates) {
		var array = [];
		coordinates.forEach(function(d) {
			array.push([d.lat, d.lng]);
		});
		return array;
	}

	map.on("viewreset", updateOnResize);
	updateOnResize();

	$(".loading").hide();
	$(".description").show();

});

});
<commit_msg>Comments review.<commit_after>$(document).ready(function(){

//
// Commons
//

var startDate,
	endDate,
	initialPosition,
	spatialPoints = [],
	entities = {};

function entity() {

	// Setters
	this.id = function(_) {
      if (!arguments.length) return id;
      id = _;
      return this;
    };

    this.points = function(_) {
      if (!arguments.length) return points;
      points = _;
      return this;
    };

}

//
// Helpers
//

function formatDate(date) {
	return d3.time.format("%Y-%m-%d %H:%M:%S").parse(date);
}

function print_filter(filter){
	var f=eval(filter);
	if (typeof(f.length) != "undefined") {}else{}
	if (typeof(f.top) != "undefined") {f=f.top(Infinity);}else{}
	if (typeof(f.dimension) != "undefined") {f=f.dimension(function(d) { return "";}).top(Infinity);}else{}
	console.log(filter+"("+f.length+") = "+JSON.stringify(f).replace("[","[\n\t").replace(/}\,/g,"},\n\t").replace("]","\n]"));
}

//
// Setup
//

minDate = formatDate("2008-10-28 00:00:00");
maxDate = formatDate("2008-10-28 23:59:59");
startDate = formatDate("2008-10-28 07:00:00");
endDate = formatDate("2008-10-28 13:00:46");
initialPosition = [39.94403, 116.407526]; // beijing

//
// Slider
//

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];

$("#slider").dateRangeSlider({
	bounds: {min: minDate, max: maxDate},
	defaultValues: {min: startDate, max: endDate},
	wheelMode: "scroll",
	wheelSpeed: 10,
	step: {
	    minutes: 5
	},
	formatter: function(val) {
		var format = d3.time.format("%Y-%m-%d %H:%M");
		return format(val);
	},
	scales: [{
	  first: function(value) { return value; },
	  end: function(value) {return value; },
	  next: function(value) {
	    var next = new Date(value);
	    return new Date(next.setMinutes(value.getMinutes() + 60));
	  },
	  label: function(value){
	  	console.log(value);
	  	var next = new Date(value);
	    return next.getHours()+1;
	  },
	  format: function(tickContainer, tickStart, tickEnd){
	    tickContainer.addClass("myCustomClass");
	  }
	}]
});

d3.csv("csv/182-29out-5min.csv", function(collection) {

	$('.inner').delay(3000).fadeTo('slow', 0.4);

	// when hover over text
	$('.inner').hover(
		function(){
			$('.inner').stop().fadeTo('slow', 1);
		},
		function(){
			$('.inner').stop().delay(500).fadeTo('slow', 0.4);
		}
	);

	spatialPoints = [];

	function convertTimestampToUTCDate(timestampInSeconds) {
		var targetTime = new Date(timestampInSeconds*1000);
		return new Date(targetTime.getUTCFullYear(), targetTime.getUTCMonth(), targetTime.getUTCDate(),  targetTime.getUTCHours(), targetTime.getUTCMinutes(), targetTime.getUTCSeconds());
	}

	// Add a LatLng object to each item in the dataset
	collection.forEach(function(d) {
		spatialPoints.push({
			coordinates: new L.LatLng(d.lat, d.lng),
			date: convertTimestampToUTCDate(d.timestamp),
			user: parseInt(d.user)
		});
	});

	$("#slider").bind("valuesChanging", function(e, data){
		updatePointsWithRange([data.values.min, data.values.max]);
	});

	//
	// CROSSFILTER
	//

	var spatial = crossfilter(spatialPoints),
		all = spatial.groupAll(),
		dateDimension = spatial.dimension(function (d) { return d.date; }),
		usersDimension = spatial.dimension(function(d) { return d.user; }),
		usersGroup = usersDimension.group(),
		users = [];

	getDistinctUsers();

	function filterSpatialPointsWithRange(range) {
		entities = {};
		dateDimension.filterRange(range);
		dateDimension.top(Infinity).forEach(function (d) {
			// First time
			if (!entities[d.user]) {
				entities[d.user] = [];
			}
			// Add point to entity
			entities[d.user].push(d.coordinates);
		});
	}

	function getDistinctUsers() {
		usersGroup.top(Infinity).forEach(function (d) {
			users.push({user: d.key});
		});
		$("#active").html(users.length);
	}

	// Count total number of points
	var n = all.reduceCount().value();
	console.log("There are " + n + " points in total.");

	//
	// MAP
	//

	var map = L.map('map').setView(initialPosition, 11),
		maplink = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
						attribution: '© OpenStreetMap',
						maxZoom: 18,
					}).addTo(map);

	// Initialize the SVG layer */
	map._initPathRoot();

	// Pick up the SVG from the map object */
	var svg = d3.select("#map").select("svg"),
		mapTrails = svg.append("g"),
		mapPoints = svg.append("g");

	// Use Leaflet to implement a D3 geometric transformation.
	function projectPoint(x, y) {
		var point = map.latLngToLayerPoint(new L.LatLng(x, y));
		this.stream.point(point.x, point.y);
	}

	var transform = d3.geo.transform({point: projectPoint}),
		path = d3.geo.path().projection(transform);

	//
	// Points
	//

	filterSpatialPointsWithRange([startDate, endDate]);

	var pointers = mapPoints
		.selectAll("circle")
		.data(users)
		.enter()
		.append("circle")
		.attr("r", 5)
		.attr("fill", "#CC0099")
		.attr("fill-opacity", 1)
		.attr("stroke", "black")
		.attr("stroke-width", 2)
		.attr("stroke-opacity", 1)
		.attr("opacity", 1)
		;

	var trails = mapTrails
		.selectAll("path")
		.data(users)
		.enter()
		.append("path")
		.attr("fill", "none")
        .attr("stroke", "#842DCE")
        .attr("stroke-width", 3)
        ;

	function render() {
		pointers.attr("transform", function (d) {
			var coordinates = entities[d.user];
			if (coordinates && coordinates.length>0) {
				var header = coordinates[0];
				return "translate("+
					map.latLngToLayerPoint(header).x +","+
					map.latLngToLayerPoint(header).y +")";
			} else {
				return "translate(-5,-5)";
			}
		});
		trails.attr("d", function (d) {
			var coordinates = entities[d.user];
			if (coordinates && coordinates.length>0) {
				return path({type: "LineString", coordinates: convertToArrayXY(coordinates)});
			} else {
				return "M0,0";
			}
		});
	}

	function updateOnResize() {
		render();
	}

	function updatePointsWithRange(range) {
		filterSpatialPointsWithRange(range);
		render();
	}

	function convertToArrayXY(coordinates) {
		var array = [];
		coordinates.forEach(function(d) {
			array.push([d.lat, d.lng]);
		});
		return array;
	}

	map.on("viewreset", updateOnResize);
	updateOnResize();

	$(".loading").hide();
	$(".description").show();

});

});
<|endoftext|>


<commit_before>(function($,window,document,undefined){
    'use strict';
var l = 'licud';
var y = 'yeshatid';
var m = 'meretz';
var a = 'avoda';
partieArray = [a,m,l,y];
var partie;
var not = $('img').not(this).removeClass;
num = licudNum = avodaNum = meretzNum = yeshNum = partieActiveNum = '95';
random = Math.ceil(Math.random() * 20);
var i = random;

function popChanger(param1) {
	if ($('span#'+param1).width() == 100) {
		$('.popup').css('display','inline-block');
		$('.pop_holder, span#'+param1+'_pop').css('display','block');
		$('span#'+param1).append('');
	}
}

function partieChanger() {
$('.show').not(this).removeClass('avoda yeshatid meretz licud')
.addClass(partie)
.attr('src', 'img/'+partie+'/'+(i++)+'.jpg');
}

function preloader() {
    if (document.images) {
        var numArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
        for (var i = 1; i < numArray.length; i++) {
            numArray[i] = new Image();
            numArray[i].src = "img/" + l + "/" + i + ".jpg";
            numArray[i].src = "img/" + a + "/" + i + ".jpg";
            numArray[i].src = "img/" + m + "/" + i + ".jpg";
            numArray[i].src = "img/" + y + "/" + i + ".jpg";
        }
    }
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		};
	}
}
addLoadEvent(preloader);

$('#close').click(function() {
    $('.popup, .pop_holder, span#licud_pop, span#meretz_pop, span#yesh_pop, span#avoda_pop').css('display', 'none');
    $('.results').css('display', 'block');
});

$('.show').click(function(e) {
    e.preventDefault();

    var partieNum = Math.ceil(Math.random() * 4);

    if (partieNum == 1) {
        partie = partieArray[0];
    } else if (partieNum == 2) {
        partie = partieArray[1];
    } else if (partieNum == 3) {
        partie = partieArray[2];
    } else {
        partie = partieArray[3];
    }

    if ($(this).hasClass('licud')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == l) {
            partie = y;
        }
        $('#licud').width(licudNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('meretz')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == m) {
            partie = a;
        }
        $('#meretz').width(meretzNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('avoda')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == a) {
            partie = l;
        }
        $('#avoda').width(avodaNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('yeshatid')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == y) {
            partie = m;
        }
        $('#yesh').width(yeshNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }

    for (var n = 0; n < partieArray.length; n++) {
        popChanger(partieArray[n]);
    }

});

})(jQuery, this, this.document);
<commit_msg>refactoring validthis<commit_after>(function($,window,document,undefined){
    'use strict';
var l = 'licud';
var y = 'yeshatid';
var m = 'meretz';
var a = 'avoda';
partieArray = [a,m,l,y];
var partie;
var not = $('img').not(this).removeClass;
num = licudNum = avodaNum = meretzNum = yeshNum = partieActiveNum = '95';
random = Math.ceil(Math.random() * 20);
var i = random;

function popChanger(param1) {
	if ($('span#'+param1).width() == 100) {
		$('.popup').css('display','inline-block');
		$('.pop_holder, span#'+param1+'_pop').css('display','block');
		$('span#'+param1).append('');
	}
}

function partieChanger() {
/*jshint validthis:true */
$('.show').not(this).removeClass('avoda yeshatid meretz licud')
.addClass(partie)
.attr('src', 'img/'+partie+'/'+(i++)+'.jpg');
}

function preloader() {
    if (document.images) {
        var numArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
        for (var i = 1; i < numArray.length; i++) {
            numArray[i] = new Image();
            numArray[i].src = "img/" + l + "/" + i + ".jpg";
            numArray[i].src = "img/" + a + "/" + i + ".jpg";
            numArray[i].src = "img/" + m + "/" + i + ".jpg";
            numArray[i].src = "img/" + y + "/" + i + ".jpg";
        }
    }
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		};
	}
}
addLoadEvent(preloader);

$('#close').click(function() {
    $('.popup, .pop_holder, span#licud_pop, span#meretz_pop, span#yesh_pop, span#avoda_pop').css('display', 'none');
    $('.results').css('display', 'block');
});

$('.show').click(function(e) {
    e.preventDefault();

    var partieNum = Math.ceil(Math.random() * 4);

    if (partieNum == 1) {
        partie = partieArray[0];
    } else if (partieNum == 2) {
        partie = partieArray[1];
    } else if (partieNum == 3) {
        partie = partieArray[2];
    } else {
        partie = partieArray[3];
    }

    if ($(this).hasClass('licud')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == l) {
            partie = y;
        }
        $('#licud').width(licudNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('meretz')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == m) {
            partie = a;
        }
        $('#meretz').width(meretzNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('avoda')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == a) {
            partie = l;
        }
        $('#avoda').width(avodaNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }
    if ($(this).hasClass('yeshatid')) {
        if (i >= 21) {
            i = random;
        }
        if (partie == y) {
            partie = m;
        }
        $('#yesh').width(yeshNum++);
        $('.show').not(this).removeClass('avoda yeshatid meretz licud').addClass(partie).attr('src', 'img/' + partie + '/' + (i++) + '.jpg');
    }

    for (var n = 0; n < partieArray.length; n++) {
        popChanger(partieArray[n]);
    }

});

})(jQuery, this, this.document);
<|endoftext|>


<commit_before>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://player.me/api/v1/users/?username=true' + $('#inputText').val(), "", function(data){
         var avatar = "https://player.me/api/v1/users/" + data['username']['avatar'] + "/?username=true";
         var username = data['id']['username'];
         var followers = data['followers_count'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['created_at'];
         var html = '';
         html += '
' + username + '
';
         html += '
Followers: ' + followers;
         html += '
Following: ' + totalViews;
         html += "
";
         if(online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played: ' + lastPlayed;
         html += '
Joined on: ' + joined.replace('T', ' at ');
         $('.profile').html(html);
      });
}
<commit_msg>Update main.js<commit_after>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://player.me/api/v1/users/id' + $('#inputText').val(), "", function(data){
         var avatar = "https://player.me/api/v1/users/" + data['username']['avatars'] + "avatars";
         var username = data['id']['username'];
         var followers = data['followers_count'];
         if(data['type'] != null){
            var lastPlayed = data['type']['name'];
         }else{
            var lastPlayed = "None";
         }
         var joined = data['created_at'];
         var html = '';
         html += '
' + username + '
';
         html += '
Followers: ' + followers;
         html += '
Following: ' + totalViews;
         html += "
";
         if(online){
             html += '
Online';
         }else{
             html += '
Offline';
         }
         html+= '
Last Played: ' + lastPlayed;
         html += '
Joined on: ' + joined.replace('T', ' at ');
         $('.profile').html(html);
      });
}
<|endoftext|>


<commit_before>'use strict';

// Third Party Dependencies
const electron = require('electron');
const app = electron.app;
const crashReporter = electron.crashReporter;
const nodeURL = require('url');
const shellPath = require('shell-path');
const squirrelStartup = require('electron-squirrel-startup');
const AutoLaunch = require('auto-launch');
const urlParser = require('url');

// Local Dependencies
const {getConfigField, updateUserConfigWin, updateUserConfigMac, readConfigFileSync} = require('./config.js');
const {setCheckboxValues} = require('./menus/menuTemplate.js');
const { isMac, isDevEnv } = require('./utils/misc.js');
const protocolHandler = require('./protocolHandler');
const getCmdLineArg = require('./utils/getCmdLineArg.js');
const log = require('./log.js');
const logLevels = require('./enums/logLevels.js');
const { deleteIndexFolder } = require('./search/search.js');

require('electron-dl')();

//setting the env path child_process issue https://github.com/electron/electron/issues/7688
shellPath()
    .then((path) => {
        process.env.PATH = path
    })
    .catch(() => {
        process.env.PATH = [
            './node_modules/.bin',
            '/usr/local/bin',
            process.env.PATH
        ].join(':');
    });

// used to check if a url was opened when the app was already open
let isAppAlreadyOpen = false;

// exit early for squirrel installer
if (squirrelStartup) {
    return;
}

require('./mainApiMgr.js');

// monitor memory of main process
require('./memoryMonitor.js');

const windowMgr = require('./windowMgr.js');

getConfigField('url')
.then(initializeCrashReporter)
.catch(app.quit);

function initializeCrashReporter(podUrl) {

    getConfigField('crashReporter')
    .then((crashReporterConfig) => {
        crashReporter.start({companyName: crashReporterConfig.companyName, submitURL: crashReporterConfig.submitURL, uploadToServer: crashReporterConfig.uploadToServer, extra: {'process': 'main', podUrl: podUrl}});
        log.send(logLevels.INFO, 'initialized crash reporter on the main process!');
    })
    .catch((err) => {
        log.send(logLevels.ERROR, 'Unable to initialize crash reporter in the main process. Error is -> ' + err);
    });

}

// only allow a single instance of app.
const shouldQuit = app.makeSingleInstance((argv) => {
    // Someone tried to run a second instance, we should focus our window.
    let mainWin = windowMgr.getMainWindow();
    if (mainWin) {
        isAppAlreadyOpen = true;
        if (mainWin.isMinimized()) {
            mainWin.restore();
        }
        mainWin.focus();
    }
    processProtocolAction(argv);
});

let allowMultiInstance = getCmdLineArg(process.argv, '--multiInstance', true) || isDevEnv;

// quit if another instance is already running, ignore for dev env or if app was started with multiInstance flag
if (!allowMultiInstance && shouldQuit) {
    app.quit();
}

let symphonyAutoLauncher;

if (isMac) {
    symphonyAutoLauncher = new AutoLaunch({
        name: 'Symphony',
        mac: {
            useLaunchAgent: true,
        },
        path: process.execPath,
    });
} else {
    symphonyAutoLauncher = new AutoLaunch({
        name: 'Symphony',
        path: process.execPath,
    });
}

/**
 * Sets chrome authentication flags in electron
 */
function setChromeFlags() {

    log.send(logLevels.INFO, 'checking if we need to set custom chrome flags!');

    // Read the config parameters synchronously
    let config = readConfigFileSync();

    // If we cannot find any config, just skip setting any flags
    if (config && config !== null && config.customFlags) {

        log.send(logLevels.INFO, 'Chrome flags config found!');

        // If we cannot find the authServerWhitelist config, move on
        if (config.customFlags.authServerWhitelist && config.customFlags.authServerWhitelist !== "") {
            log.send(logLevels.INFO, 'Setting auth server whitelist flag');
            app.commandLine.appendSwitch('auth-server-whitelist', config.customFlags.authServerWhitelist);
        }

        // If we cannot find the authNegotiateDelegateWhitelist config, move on
        if (config.customFlags.authNegotiateDelegateWhitelist && config.customFlags.authNegotiateDelegateWhitelist !== "") {
            log.send(logLevels.INFO, 'Setting auth negotiate delegate whitelist flag');
            app.commandLine.appendSwitch('auth-negotiate-delegate-whitelist', config.customFlags.authNegotiateDelegateWhitelist);
        }

    }
}

// Set the chrome flags
setChromeFlags();

/**
 * This method will be called when Electron has finished
 * initialization and is ready to create browser windows.
 * Some APIs can only be used after this event occurs.
 */
app.on('ready', readConfigThenOpenMainWindow);

/**
 * Is triggered when all the windows are closed
 * In which case we quit the app
 */
app.on('window-all-closed', function() {
    app.quit();
});

/**
 * Is triggered when the app is up & running
 */
app.on('activate', function() {
    if (windowMgr.isMainWindow(null)) {
        setupThenOpenMainWindow();
    } else {
        windowMgr.showMainWindow();
    }
});

app.on('will-quit', function (e) {
    e.preventDefault();
    deleteIndexFolder();
    app.exit();
});

// adds 'symphony' as a protocol
// in the system. plist file in macOS
// and registry keys in windows
app.setAsDefaultProtocolClient('symphony');

/**
 * This event is emitted only on macOS
 * at this moment, support for windows
 * is in pipeline (https://github.com/electron/electron/pull/8052)
 */
app.on('open-url', function(event, url) {
    handleProtocolAction(url);
});

/**
 * Reads the config fields that are required for the menu items
 * then opens the main window
 *
 * This is a workaround for the issue where the menu template was returned
 * even before the config data was populated
 * https://perzoinc.atlassian.net/browse/ELECTRON-154
 */
function readConfigThenOpenMainWindow() {
    setCheckboxValues()
        .then(setupThenOpenMainWindow)
        .catch(setupThenOpenMainWindow)
}

/**
 * Sets up the app (to handle various things like config changes, protocol handling etc.)
 * and opens the main window
 */
function setupThenOpenMainWindow() {

    processProtocolAction(process.argv);

    isAppAlreadyOpen = true;

    // allows installer to launch app and set appropriate global / user config params.
    let hasInstallFlag = getCmdLineArg(process.argv, '--install', true);
    let perUserInstall = getCmdLineArg(process.argv, '--peruser', true);
    let customDataArg = getCmdLineArg(process.argv, '--userDataPath=', false);

    if (customDataArg && customDataArg.split('=').length > 1) {
        let customDataFolder = customDataArg.split('=')[1];
        app.setPath('userData', customDataFolder);
    }
    if (!isMac && hasInstallFlag) {
        getConfigField('launchOnStartup')
            .then(setStartup)
            .then(() => updateUserConfigWin(perUserInstall))
            .then(app.quit)
            .catch(app.quit);
        return;
    }

    // allows mac installer to overwrite user config
    if (isMac && hasInstallFlag) {
        // This value is being sent from post install script
        // as the app is launched as a root user we don't get
        // access to the config file
        let launchOnStartup = process.argv[3];
        // We wire this in via the post install script
        // to get the config file path where the app is installed
        setStartup(launchOnStartup)
            .then(updateUserConfigMac)
            .then(app.quit)
            .catch(app.quit);
        return;
    }

    getUrlAndCreateMainWindow();

    // Event that fixes the remote desktop issue in Windows
    // by repositioning the browser window
    electron.screen.on('display-removed', windowMgr.verifyDisplays);
}

/**
 * Sets Symphony on startup
 * @param lStartup
 * @returns {Promise}
 */
function setStartup(lStartup) {
    return new Promise((resolve) => {
        let launchOnStartup = (lStartup === 'true');
        if (launchOnStartup) {
            symphonyAutoLauncher.enable();
            return resolve();
        }
        symphonyAutoLauncher.disable();
        return resolve();
    });
}

/**
 * Checks for the url argument, processes it
 * and creates the main window
 */
function getUrlAndCreateMainWindow() {
    // for dev env allow passing url argument
    if (isDevEnv) {
        let url = getCmdLineArg(process.argv, '--url=', false);
        if (url) {
            windowMgr.createMainWindow(url.substr(6));
            return;
        }
    }

    getConfigField('url')
        .then(createWin).catch(function(err) {
            let title = 'Error loading configuration';
            electron.dialog.showErrorBox(title, title + ': ' + err);
        });
}

/**
 * Creates a window
 * @param urlFromConfig
 */
function createWin(urlFromConfig) {
    // add https protocol if none found.
    let parsedUrl = nodeURL.parse(urlFromConfig);

    if (!parsedUrl.protocol) {
        parsedUrl.protocol = 'https:';
        parsedUrl.slashes = true
    }
    let url = nodeURL.format(parsedUrl);

    windowMgr.createMainWindow(url);
}

/**
 * processes protocol action for windows clients
 * @param argv {Array} an array of command line arguments
 */
function processProtocolAction(argv) {

    // In case of windows, we need to handle protocol handler
    // manually because electron doesn't emit
    // 'open-url' event on windows
    if (!(process.platform === 'win32')) {
        return;
    }

    let protocolUri = getCmdLineArg(argv, 'symphony://', false);

    if (protocolUri) {

        const parsedURL = urlParser.parse(protocolUri);

        if (!parsedURL.protocol || !parsedURL.slashes) {
            return;
        }

        handleProtocolAction(protocolUri);

    }
}

/**
 * Handles a protocol action based on the current state of the app
 * @param uri
 */
function handleProtocolAction(uri) {
    if (!isAppAlreadyOpen) {
        // app is opened by the protocol url, cache the protocol url to be used later
        protocolHandler.setProtocolUrl(uri);
    } else {
        // app is already open, so, just trigger the protocol action method
        protocolHandler.processProtocolAction(uri);
    }
}<commit_msg>electron-261: add gpu switches<commit_after>'use strict';

// Third Party Dependencies
const electron = require('electron');
const app = electron.app;
const crashReporter = electron.crashReporter;
const nodeURL = require('url');
const shellPath = require('shell-path');
const squirrelStartup = require('electron-squirrel-startup');
const AutoLaunch = require('auto-launch');
const urlParser = require('url');

// Local Dependencies
const {getConfigField, updateUserConfigWin, updateUserConfigMac, readConfigFileSync} = require('./config.js');
const {setCheckboxValues} = require('./menus/menuTemplate.js');
const { isMac, isDevEnv, isWindowsOS } = require('./utils/misc.js');
const protocolHandler = require('./protocolHandler');
const getCmdLineArg = require('./utils/getCmdLineArg.js');
const log = require('./log.js');
const logLevels = require('./enums/logLevels.js');
const { deleteIndexFolder } = require('./search/search.js');

require('electron-dl')();

// ELECTRON-261: On Windows, due to gpu issues, we need to disable gpu
// to ensure screen sharing works effectively with multiple monitors
// https://github.com/electron/electron/issues/4380
if (isWindowsOS) {
    app.commandLine.appendSwitch("disable-gpu", true);
    app.commandLine.appendSwitch("disable-gpu-compositing", true);
    app.commandLine.appendSwitch("disable-d3d11", true);
}

//setting the env path child_process issue https://github.com/electron/electron/issues/7688
shellPath()
    .then((path) => {
        process.env.PATH = path
    })
    .catch(() => {
        process.env.PATH = [
            './node_modules/.bin',
            '/usr/local/bin',
            process.env.PATH
        ].join(':');
    });

// used to check if a url was opened when the app was already open
let isAppAlreadyOpen = false;

// exit early for squirrel installer
if (squirrelStartup) {
    return;
}

require('./mainApiMgr.js');

// monitor memory of main process
require('./memoryMonitor.js');

const windowMgr = require('./windowMgr.js');

getConfigField('url')
.then(initializeCrashReporter)
.catch(app.quit);

function initializeCrashReporter(podUrl) {

    getConfigField('crashReporter')
    .then((crashReporterConfig) => {
        crashReporter.start({companyName: crashReporterConfig.companyName, submitURL: crashReporterConfig.submitURL, uploadToServer: crashReporterConfig.uploadToServer, extra: {'process': 'main', podUrl: podUrl}});
        log.send(logLevels.INFO, 'initialized crash reporter on the main process!');
    })
    .catch((err) => {
        log.send(logLevels.ERROR, 'Unable to initialize crash reporter in the main process. Error is -> ' + err);
    });

}

// only allow a single instance of app.
const shouldQuit = app.makeSingleInstance((argv) => {
    // Someone tried to run a second instance, we should focus our window.
    let mainWin = windowMgr.getMainWindow();
    if (mainWin) {
        isAppAlreadyOpen = true;
        if (mainWin.isMinimized()) {
            mainWin.restore();
        }
        mainWin.focus();
    }
    processProtocolAction(argv);
});

let allowMultiInstance = getCmdLineArg(process.argv, '--multiInstance', true) || isDevEnv;

// quit if another instance is already running, ignore for dev env or if app was started with multiInstance flag
if (!allowMultiInstance && shouldQuit) {
    app.quit();
}

let symphonyAutoLauncher;

if (isMac) {
    symphonyAutoLauncher = new AutoLaunch({
        name: 'Symphony',
        mac: {
            useLaunchAgent: true,
        },
        path: process.execPath,
    });
} else {
    symphonyAutoLauncher = new AutoLaunch({
        name: 'Symphony',
        path: process.execPath,
    });
}

/**
 * Sets chrome authentication flags in electron
 */
function setChromeFlags() {

    log.send(logLevels.INFO, 'checking if we need to set custom chrome flags!');

    // Read the config parameters synchronously
    let config = readConfigFileSync();

    // If we cannot find any config, just skip setting any flags
    if (config && config !== null && config.customFlags) {

        log.send(logLevels.INFO, 'Chrome flags config found!');

        // If we cannot find the authServerWhitelist config, move on
        if (config.customFlags.authServerWhitelist && config.customFlags.authServerWhitelist !== "") {
            log.send(logLevels.INFO, 'Setting auth server whitelist flag');
            app.commandLine.appendSwitch('auth-server-whitelist', config.customFlags.authServerWhitelist);
        }

        // If we cannot find the authNegotiateDelegateWhitelist config, move on
        if (config.customFlags.authNegotiateDelegateWhitelist && config.customFlags.authNegotiateDelegateWhitelist !== "") {
            log.send(logLevels.INFO, 'Setting auth negotiate delegate whitelist flag');
            app.commandLine.appendSwitch('auth-negotiate-delegate-whitelist', config.customFlags.authNegotiateDelegateWhitelist);
        }

    }
}

// Set the chrome flags
setChromeFlags();

/**
 * This method will be called when Electron has finished
 * initialization and is ready to create browser windows.
 * Some APIs can only be used after this event occurs.
 */
app.on('ready', readConfigThenOpenMainWindow);

/**
 * Is triggered when all the windows are closed
 * In which case we quit the app
 */
app.on('window-all-closed', function() {
    app.quit();
});

/**
 * Is triggered when the app is up & running
 */
app.on('activate', function() {
    if (windowMgr.isMainWindow(null)) {
        setupThenOpenMainWindow();
    } else {
        windowMgr.showMainWindow();
    }
});

app.on('will-quit', function (e) {
    e.preventDefault();
    deleteIndexFolder();
    app.exit();
});

// adds 'symphony' as a protocol
// in the system. plist file in macOS
// and registry keys in windows
app.setAsDefaultProtocolClient('symphony');

/**
 * This event is emitted only on macOS
 * at this moment, support for windows
 * is in pipeline (https://github.com/electron/electron/pull/8052)
 */
app.on('open-url', function(event, url) {
    handleProtocolAction(url);
});

/**
 * Reads the config fields that are required for the menu items
 * then opens the main window
 *
 * This is a workaround for the issue where the menu template was returned
 * even before the config data was populated
 * https://perzoinc.atlassian.net/browse/ELECTRON-154
 */
function readConfigThenOpenMainWindow() {
    setCheckboxValues()
        .then(setupThenOpenMainWindow)
        .catch(setupThenOpenMainWindow)
}

/**
 * Sets up the app (to handle various things like config changes, protocol handling etc.)
 * and opens the main window
 */
function setupThenOpenMainWindow() {

    processProtocolAction(process.argv);

    isAppAlreadyOpen = true;

    // allows installer to launch app and set appropriate global / user config params.
    let hasInstallFlag = getCmdLineArg(process.argv, '--install', true);
    let perUserInstall = getCmdLineArg(process.argv, '--peruser', true);
    let customDataArg = getCmdLineArg(process.argv, '--userDataPath=', false);

    if (customDataArg && customDataArg.split('=').length > 1) {
        let customDataFolder = customDataArg.split('=')[1];
        app.setPath('userData', customDataFolder);
    }
    if (!isMac && hasInstallFlag) {
        getConfigField('launchOnStartup')
            .then(setStartup)
            .then(() => updateUserConfigWin(perUserInstall))
            .then(app.quit)
            .catch(app.quit);
        return;
    }

    // allows mac installer to overwrite user config
    if (isMac && hasInstallFlag) {
        // This value is being sent from post install script
        // as the app is launched as a root user we don't get
        // access to the config file
        let launchOnStartup = process.argv[3];
        // We wire this in via the post install script
        // to get the config file path where the app is installed
        setStartup(launchOnStartup)
            .then(updateUserConfigMac)
            .then(app.quit)
            .catch(app.quit);
        return;
    }

    getUrlAndCreateMainWindow();

    // Event that fixes the remote desktop issue in Windows
    // by repositioning the browser window
    electron.screen.on('display-removed', windowMgr.verifyDisplays);
}

/**
 * Sets Symphony on startup
 * @param lStartup
 * @returns {Promise}
 */
function setStartup(lStartup) {
    return new Promise((resolve) => {
        let launchOnStartup = (lStartup === 'true');
        if (launchOnStartup) {
            symphonyAutoLauncher.enable();
            return resolve();
        }
        symphonyAutoLauncher.disable();
        return resolve();
    });
}

/**
 * Checks for the url argument, processes it
 * and creates the main window
 */
function getUrlAndCreateMainWindow() {
    // for dev env allow passing url argument
    if (isDevEnv) {
        let url = getCmdLineArg(process.argv, '--url=', false);
        if (url) {
            windowMgr.createMainWindow(url.substr(6));
            return;
        }
    }

    getConfigField('url')
        .then(createWin).catch(function(err) {
            let title = 'Error loading configuration';
            electron.dialog.showErrorBox(title, title + ': ' + err);
        });
}

/**
 * Creates a window
 * @param urlFromConfig
 */
function createWin(urlFromConfig) {
    // add https protocol if none found.
    let parsedUrl = nodeURL.parse(urlFromConfig);

    if (!parsedUrl.protocol) {
        parsedUrl.protocol = 'https:';
        parsedUrl.slashes = true
    }
    let url = nodeURL.format(parsedUrl);

    windowMgr.createMainWindow(url);
}

/**
 * processes protocol action for windows clients
 * @param argv {Array} an array of command line arguments
 */
function processProtocolAction(argv) {

    // In case of windows, we need to handle protocol handler
    // manually because electron doesn't emit
    // 'open-url' event on windows
    if (!(process.platform === 'win32')) {
        return;
    }

    let protocolUri = getCmdLineArg(argv, 'symphony://', false);

    if (protocolUri) {

        const parsedURL = urlParser.parse(protocolUri);

        if (!parsedURL.protocol || !parsedURL.slashes) {
            return;
        }

        handleProtocolAction(protocolUri);

    }
}

/**
 * Handles a protocol action based on the current state of the app
 * @param uri
 */
function handleProtocolAction(uri) {
    if (!isAppAlreadyOpen) {
        // app is opened by the protocol url, cache the protocol url to be used later
        protocolHandler.setProtocolUrl(uri);
    } else {
        // app is already open, so, just trigger the protocol action method
        protocolHandler.processProtocolAction(uri);
    }
}<|endoftext|>


<commit_before>var obj = this;
var id = getRandomInt(1, 65355);
var sceneObjId = id + "SceneObj";
obj[sceneObjId] = new THREE.Scene();
obj[sceneObjId].socket = io.connect('http://localhost:8080');

function getRandomInt(min, max) {
	min = Math.ceil(min);
	max = Math.floor(max);
	return Math.floor(Math.random() * (max - min)) + min;
}

obj[sceneObjId].socket.on('connect', function() {
	var socketID = obj[sceneObjId].socket.id;
	var camObjId = socketID + "CamObj";
	var cubeObjId = socketID + "CubeObj";

	obj[camObjId] = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);

	obj[sceneObjId].socket.emit("newObj", {
		"id": socketID
	});

	var renderer = new THREE.WebGLRenderer();
	renderer.setSize(window.innerWidth, window.innerHeight);
	document.body.appendChild(renderer.domElement);

	var scale = 200;
	var sections = 20;
	var fogGrid = new THREE.Fog(0x00ff00, 1, 5);
	var baseGrid = new THREE.GridHelper(scale, sections);
	obj[sceneObjId].add(baseGrid);

	var cWidth = 1;
	var cHeight = 1;
	var cDepth = 1;
	var cColor = "rgb(174, 129, 255)";
	var camZ = 4;

	var cubeColorRGB = new THREE.Color(cColor);
	var cubeGeom = new THREE.BoxGeometry(cWidth, cHeight, cDepth);
	var cubeColor = new THREE.MeshBasicMaterial({ color: cubeColorRGB, opacity: 0.7, transparent: true });
	var group = new THREE.Group();
	obj[sceneObjId].add(group);
	obj[cubeObjId] = new THREE.Mesh(cubeGeom, cubeColor);
	obj[cubeObjId].name = socketID;
	group.add(obj[cubeObjId]);
	obj[sceneObjId].add(obj[cubeObjId]);

	obj[cubeObjId].position.set(0, 10, camZ);
	obj[camObjId].position.set(0, 10, camZ);
	obj[camObjId].up = new THREE.Vector3(0, 12, camZ);

	var render = function () {
		requestAnimationFrame(render);
		renderer.render(obj[sceneObjId], obj[camObjId]);
	};

	render();

	var keys = {};

	$(document).keydown(function (e) {
		keys[e.key] = true;
		var xx = 0;
		var zz = 0;
		var speed = 4;
		for (var i in keys) {
			if (!keys.hasOwnProperty(i)) continue;
				if (i == 'w') {
					zz = -speed;
				}

				if (i == 's') {
					zz = speed;
				}

				if (i == 'a') {
					xx = -speed;
				}

				if (i == 'd') {
					xx = speed;
				}
		}

		obj[sceneObjId].socket.emit('updatePos', {
			'x': xx,
			'z': zz,
			'id': socketID
		});

		obj[sceneObjId].socket.emit('getUserList');
	});

	$(document).keyup(function (e) {
		delete keys[e.key];
	});

	obj[sceneObjId].socket.on('deleteGridObj', function(userID) {
		var clientID = userID + "CubeObj";
		obj[sceneObjId].remove(obj[clientID]);
	});

	obj[sceneObjId].socket.on('returnUserList', function(userID, userData) {

		var userCube = userData;
		var uIDCube = userID + "CubeObj";
		var clientCube = obj[uIDCube];

		if ((typeof clientCube) != "undefined") {

			if (userID != socketID) {

				clientCube.position.z = userCube.z;
				clientCube.position.x = userCube.x;

			}

		} else {

			var uIDCube1 = userID + "CubeObj";

			var cWidth1 = userData.w;
			var cHeight1 = userData.h;
			var cDepth1 = userData.d;
			var cColor1 = userData.color;

			var cubeColorRGB1 = new THREE.Color(cColor1);
			var cubeGeom1 = new THREE.BoxGeometry(cWidth1, cHeight1, cDepth1);
			var cubeColor1 = new THREE.MeshBasicMaterial({ color: cubeColorRGB1, opacity: 0.7, transparent: true });
			obj[uIDCube1] = new THREE.Mesh(cubeGeom1, cubeColor1);

			group.add(obj[uIDCube1]);
			obj[uIDCube1].name = userID;
			obj[sceneObjId].add(obj[uIDCube1]);

			obj[uIDCube1].position.set(userData.x, 7, userData.z);
		}

	});

	obj[sceneObjId].socket.on('move', function(data) {
			var newCamZ = data.CamObj.z;
			var newCubeZ = data.CubeObj.z;

			var newCamX = data.CamObj.x;
			var newCubeX = data.CubeObj.x;

			obj[cubeObjId].position.set(newCamX, 10, newCubeZ);
			obj[camObjId].position.set(newCamX, 10, newCubeZ);
			obj[camObjId].up = new THREE.Vector3(0, 12, newCamZ);
	});

});
<commit_msg>Code cleanup<commit_after>var obj = this;
var id = getRandomInt(1, 65355);
var sceneObjId = id + "SceneObj";
obj[sceneObjId] = new THREE.Scene();
obj[sceneObjId].socket = io.connect('http://localhost:8080');

function getRandomInt(min, max) {
	min = Math.ceil(min);
	max = Math.floor(max);
	return Math.floor(Math.random() * (max - min)) + min;
}

obj[sceneObjId].socket.on('connect', function() {
	var socketID = obj[sceneObjId].socket.id;
	var camObjId = socketID + "CamObj";
	var cubeObjId = socketID + "CubeObj";

	obj[camObjId] = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);

	obj[sceneObjId].socket.emit("newObj", {
		"id": socketID
	});

	var renderer = new THREE.WebGLRenderer();
	renderer.setSize(window.innerWidth, window.innerHeight);
	document.body.appendChild(renderer.domElement);

	var scale = 200;
	var sections = 20;
	var fogGrid = new THREE.Fog(0x00ff00, 1, 5);
	var baseGrid = new THREE.GridHelper(scale, sections);
	obj[sceneObjId].add(baseGrid);

	var cWidth = 1;
	var cHeight = 1;
	var cDepth = 1;
	var cColor = "rgb(174, 129, 255)";
	var camZ = 4;

	var cubeColorRGB = new THREE.Color(cColor);
	var cubeGeom = new THREE.BoxGeometry(cWidth, cHeight, cDepth);
	var cubeColor = new THREE.MeshBasicMaterial({ color: cubeColorRGB, opacity: 0.7, transparent: true });
	var group = new THREE.Group();
	obj[sceneObjId].add(group);
	obj[cubeObjId] = new THREE.Mesh(cubeGeom, cubeColor);
	obj[cubeObjId].name = socketID;
	group.add(obj[cubeObjId]);
	obj[sceneObjId].add(obj[cubeObjId]);

	obj[cubeObjId].position.set(0, 10, camZ);
	obj[camObjId].position.set(0, 10, camZ);
	obj[camObjId].up = new THREE.Vector3(0, 12, camZ);

	var render = function () {
		requestAnimationFrame(render);
		renderer.render(obj[sceneObjId], obj[camObjId]);
	};

	render();

	var keys = {};

	$(document).keydown(function (e) {
		keys[e.key] = true;
		var xx = 0;
		var zz = 0;
		var speed = 4;
		for (var i in keys) {
			if (!keys.hasOwnProperty(i)) continue;

				if (i == 'w') {
					zz -= speed;
				}

				if (i == 's') {
					zz += speed;
				}

				if (i == 'a') {
					xx -= speed;
				}

				if (i == 'd') {
					xx += speed;
				}
		}

		obj[sceneObjId].socket.emit('updatePos', {
			'x': xx,
			'z': zz,
			'id': socketID
		});

		obj[sceneObjId].socket.emit('getUserList');
	});

	$(document).keyup(function (e) {
		delete keys[e.key];
	});

	obj[sceneObjId].socket.on('deleteGridObj', function(userID) {
		var clientID = userID + "CubeObj";
		obj[sceneObjId].remove(obj[clientID]);
	});

	obj[sceneObjId].socket.on('returnUserList', function(userID, userData) {

		var userCube = userData;
		var uIDCube = userID + "CubeObj";
		var clientCube = obj[uIDCube];

		if ((typeof clientCube) != "undefined") {

			if (userID != socketID) {

				clientCube.position.z = userCube.z;
				clientCube.position.x = userCube.x;

			}

		} else {

			var uIDCube1 = userID + "CubeObj";

			var cWidth1 = userData.w;
			var cHeight1 = userData.h;
			var cDepth1 = userData.d;
			var cColor1 = userData.color;

			var cubeColorRGB1 = new THREE.Color(cColor1);
			var cubeGeom1 = new THREE.BoxGeometry(cWidth1, cHeight1, cDepth1);
			var cubeColor1 = new THREE.MeshBasicMaterial({ color: cubeColorRGB1, opacity: 0.7, transparent: true });
			obj[uIDCube1] = new THREE.Mesh(cubeGeom1, cubeColor1);

			group.add(obj[uIDCube1]);
			obj[uIDCube1].name = userID;
			obj[sceneObjId].add(obj[uIDCube1]);

			obj[uIDCube1].position.set(userData.x, 7, userData.z);
		}

	});

	obj[sceneObjId].socket.on('move', function(data) {
			var newCamZ = data.CamObj.z;
			var newCubeZ = data.CubeObj.z;

			var newCamX = data.CamObj.x;
			var newCubeX = data.CubeObj.x;

			obj[cubeObjId].position.set(newCamX, 10, newCubeZ);
			obj[camObjId].position.set(newCamX, 10, newCubeZ);
			obj[camObjId].up = new THREE.Vector3(0, 12, newCamZ);
	});

});
<|endoftext|>