<commit_before>var socket = io.connect();
var $dele = $('#dele');
var $button1 = $('#button1');var counter=0;var moves=0;var gamecount=1;var playersname;
var visited1=0;
var visited2=0;
var visited3=0;
var visited4=0;
var visited5=0;
var visited6=0;
var visited7=0;
var visited8=0;
var visited9=0;
var ismoved=0;
var $button2 = $('#button2');
var $available=$('#available');
var $reset=$('#reset');
var $joinarea=$('#joinarea');
var $gamearea=$('#gamearea');
var $users=$('#users');
var $spot1=$('#spot1');
var $spot2=$('#spot2');
var $spot3=$('#spot3');
var $spot4=$('#spot4');
var $spot5=$('#spot5');
var $spot6=$('#spot6');
var $spot7=$('#spot7');
var $spot8=$('#spot8');
var $spot9=$('#spot9');
socket.on('available',function(data){
var html2='';
for(var i=0;i<data.length;i++)
{
html2+='
Game id:  '+data[i].id+'
';
}
$available.html(html2);
});
$button1.click(function(e){
e.preventDefault();
mbox.prompt("Enter Your name",function(result){
    socket.emit('create',result);
});
socket.on('created',function(data){
  $joinarea.hide();
  $gamearea.show();
  var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
  for(i=0;i<list.length;i++)
  {
    html2+='
'+list[i]+'
';
  }
  html1+=html2;
  $users.html(html1);
});
});
$button2.click(function(e){
e.preventDefault();
mbox.prompt("enter the id of game you want to enter:",function(result){
    socket.emit('join',result);
    socket.on('player2name',function(data){
      mbox.prompt("enter your name:",function(result){
        if(result)
        {socket.emit('gamestart',result);}
      });
    });
});
});
$delete.click(function(e){
    e.preventDefault();
    socket.emit('disconnect',1);
    $gamearea.hide();
    $joinarea.show();

});

socket.on('joined',function(data){
$joinarea.hide();
$gamearea.show();
var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
for(i=0;i<list.length;i++)
{
  html2+='
'+list[i]+'
';
}
html1+=html2;
$users.html(html1);
  socket.emit('namelist',gamecount);
});
socket.on('display',function(data){
var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
for(i=0;i<list.length;i++)
{
  html2+='
'+list[i]+'
';
}
html1+=html2;
$users.html(html1);
});
socket.on('firstmove',function(data){
mbox.alert(data[1]+" will make the first move",function(err,result){
  if (err) throw err;
});
});
$spot1.click(function(){
    if(visited1==0)
    {
  if(counter==0)
  {document.getElementById("spot1").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot1").innerHTML = "X";counter=counter-1;
  }
   visited1=1;
  socket.emit('check',{area:"spot1",counter:counter,moves:moves,visited:visited1});

    }

});
socket.on('checked',function(data){
   data.visited=1;
if(data.counter==0)
{document.getElementById(data.area).innerHTML="X";}
else {
  document.getElementById(data.area).innerHTML="O";
}
    document.getElementById(data.area).click(false);
counter=data.counter;moves=data.moves+1;
if(($spot1.text()=="X"&&$spot2.text()=="X"&&$spot3.text()=="X")||($spot4.text()=="X"&&$spot5.text()=="X"&&$spot6.text()=="X")||($spot7.text()=="X"&&$spot8.text()=="X"&&$spot9.text()=="X")||($spot1.text()=="X"&&$spot4.text()=="X"&&$spot7.text()=="X")
||($spot2.text()=="X"&&$spot5.text()=="X"&&$spot8.text()=="X")||($spot3.text()=="X"&&$spot6.text()=="X"&&$spot9.text()=="X")||($spot1.text()=="X"&&$spot5.text()=="X"&&$spot9.text()=="X")||($spot3.text()=="X"&&$spot5.text()=="X"&&$spot7.text()=="X"))
{
    moves=0;counter=0;
  mbox.alert(playersname[(gamecount+1)%2]+" won the game!!..Press Reset to start new game",function(err,result){
    if (err) throw err;
  });
}
else if(($spot1.text()=="O"&&$spot2.text()=="O"&&$spot3.text()=="O")||($spot4.text()=="O"&&$spot5.text()=="O"&&$spot6.text()=="O")||($spot7.text()=="O"&&$spot8.text()=="O"&&$spot9.text()=="O")||($spot1.text()=="O"&&$spot4.text()=="O"&&$spot7.text()=="O")
||($spot2.text()=="O"&&$spot5.text()=="O"&&$spot8.text()=="O")||($spot3.text()=="O"&&$spot6.text()=="O"&&$spot9.text()=="O")||($spot1.text()=="O"&&$spot5.text()=="O"&&$spot9.text()=="O")||($spot3.text()=="O"&&$spot5.text()=="O"&&$spot7.text()=="O"))
{
    moves=0;counter=0;
    mbox.alert(playersname[gamecount]+" won the game!!..Press Reset to start new game",function(err,result){
      if (err) throw err;
    });
}
else if(moves==9)
{
  socket.emit('draw',gamecount);
  mbox.alert("the game resulted in draw",function(err,result){
    if (err) throw err;
    mbox.alert("Press Reset to start new game",function(err,result){
      if (err) throw err;
    });
  });
    socket.emit('namelist',gamecount);
}
});
socket.on('newgame1',function(data){
moves=0;counter=0;
});
$reset.click(function(e){
e.preventDefault();
$spot1.empty();$spot2.empty();$spot3.empty();$spot4.empty();$spot5.empty();$spot6.empty();$spot7.empty();$spot8.empty();$spot9.empty();
gamecount=gamecount+1;gamecount=gamecount%2;
    visited1=0;visited2=0;visited3=0;visited4=0;visited5=0;visited6=0;visited7=0;visited8=0;visited9=0;
mbox.alert(playersname[gamecount]+" will make first move",function(err,result){
  if (err) throw err;
});
});
socket.on('gotnamelist',function(data){
  playersname=data.list;
});
$spot2.click(function(){
     if(visited2==0)
    {
  if(counter==0)
  {document.getElementById("spot2").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot2").innerHTML = "X";counter=counter-1;
  }
      visited2=1;
  socket.emit('check',{area:"spot2",counter:counter,moves:moves,visited:visited2});

    }
  });
$spot3.click(function(){
     if(visited3==0)
    {
  if(counter==0)
  {document.getElementById("spot3").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot3").innerHTML = "X";counter=counter-1;
  }
     visited3=1;
  socket.emit('check',{area:"spot3",counter:counter,moves:moves,visited:visited3});

    }

});
$spot4.click(function(){
     if(visited4==0)
    {
  if(counter==0)
  {document.getElementById("spot4").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot4").innerHTML = "X";counter=counter-1;
  }
     visited4=1;
  socket.emit('check',{area:"spot4",counter:counter,moves:moves,visited:visited4});

    }
});
$spot5.click(function(){
     if(visited5==0)
    {
  if(counter==0)
  {document.getElementById("spot5").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot5").innerHTML = "X";counter=counter-1;
  }
      visited5=1;
  socket.emit('check',{area:"spot5",counter:counter,moves:moves,visited:visited5});

    }
});
$spot6.click(function(){
     if(visited6==0)
    {
  if(counter==0)
  {document.getElementById("spot6").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot6").innerHTML = "X";counter=counter-1;
  }
      visited6=1;
  socket.emit('check',{area:"spot6",counter:counter,moves:moves,visited:visited6});

    }
});
$spot7.click(function(){
     if(visited7==0)
    {
  if(counter==0)
  {document.getElementById("spot7").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot7").innerHTML = "X";counter=counter-1;
  }
       visited7=1;
  socket.emit('check',{area:"spot7",counter:counter,moves:moves,visited:visited7});

    }
                });
$spot8.click(function(){
     if(visited8==0)
    {
  if(counter==0)
  {document.getElementById("spot8").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot8").innerHTML = "X";counter=counter-1;
  }
     visited8=1;
  socket.emit('check',{area:"spot8",counter:counter,moves:moves,visited:visited8});

    }
                });
$spot9.click(function(){
     if(visited9==0)
    {
  if(counter==0)
  {document.getElementById("spot9").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot9").innerHTML = "X";counter=counter-1;
  }
    visited9=1;
  socket.emit('check',{area:"spot9",counter:counter,moves:moves,visited:visited9});

    }

});
socket.on('reset',function(data){counter=0;moves=0;gamecount=1;
$spot1.empty();$spot2.empty();$spot3.empty();$spot4.empty();$spot5.empty();$spot6.empty();$spot7.empty();$spot8.empty();$spot9.empty();
});
<commit_msg>Update script.js<commit_after>var socket = io.connect();
var $dele = $('#dele');
var $button1 = $('#button1');var counter=0;var moves=0;var gamecount=1;var playersname;
var visited1=0;
var visited2=0;
var visited3=0;
var visited4=0;
var visited5=0;
var visited6=0;
var visited7=0;
var visited8=0;
var visited9=0;
var ismoved=0;
var $button2 = $('#button2');
var $available=$('#available');
var $reset=$('#reset');
var $joinarea=$('#joinarea');
var $gamearea=$('#gamearea');
var $users=$('#users');
var $spot1=$('#spot1');
var $spot2=$('#spot2');
var $spot3=$('#spot3');
var $spot4=$('#spot4');
var $spot5=$('#spot5');
var $spot6=$('#spot6');
var $spot7=$('#spot7');
var $spot8=$('#spot8');
var $spot9=$('#spot9');
socket.on('available',function(data){
var html2='';
for(var i=0;i<data.length;i++)
{
html2+='
Game id:  '+data[i].id+'
';
}
$available.html(html2);
});
$button1.click(function(e){
e.preventDefault();
mbox.prompt("Enter Your name",function(result){
    socket.emit('create',result);
});
socket.on('created',function(data){
  $joinarea.hide();
  $gamearea.show();
  var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
  for(i=0;i<list.length;i++)
  {
    html2+='
'+list[i]+'
';
  }
  html1+=html2;
  $users.html(html1);
});
});
$button2.click(function(e){
e.preventDefault();
mbox.prompt("enter the id of game you want to enter:",function(result){
    socket.emit('join',result);
    socket.on('player2name',function(data){
      mbox.prompt("enter your name:",function(result){
        if(result)
        {socket.emit('gamestart',result);}
      });
    });
});
});
$dele.click(function(e){
    e.preventDefault();
    socket.emit('disconnect',1);
    $gamearea.hide();
    $joinarea.show();

});

socket.on('joined',function(data){
$joinarea.hide();
$gamearea.show();
var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
for(i=0;i<list.length;i++)
{
  html2+='
'+list[i]+'
';
}
html1+=html2;
$users.html(html1);
  socket.emit('namelist',gamecount);
});
socket.on('display',function(data){
var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
for(i=0;i<list.length;i++)
{
  html2+='
'+list[i]+'
';
}
html1+=html2;
$users.html(html1);
});
socket.on('firstmove',function(data){
mbox.alert(data[1]+" will make the first move",function(err,result){
  if (err) throw err;
});
});
$spot1.click(function(){
    if(visited1==0)
    {
  if(counter==0)
  {document.getElementById("spot1").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot1").innerHTML = "X";counter=counter-1;
  }
   visited1=1;
  socket.emit('check',{area:"spot1",counter:counter,moves:moves,visited:visited1});

    }

});
socket.on('checked',function(data){
   data.visited=1;
if(data.counter==0)
{document.getElementById(data.area).innerHTML="X";}
else {
  document.getElementById(data.area).innerHTML="O";
}
    document.getElementById(data.area).click(false);
counter=data.counter;moves=data.moves+1;
if(($spot1.text()=="X"&&$spot2.text()=="X"&&$spot3.text()=="X")||($spot4.text()=="X"&&$spot5.text()=="X"&&$spot6.text()=="X")||($spot7.text()=="X"&&$spot8.text()=="X"&&$spot9.text()=="X")||($spot1.text()=="X"&&$spot4.text()=="X"&&$spot7.text()=="X")
||($spot2.text()=="X"&&$spot5.text()=="X"&&$spot8.text()=="X")||($spot3.text()=="X"&&$spot6.text()=="X"&&$spot9.text()=="X")||($spot1.text()=="X"&&$spot5.text()=="X"&&$spot9.text()=="X")||($spot3.text()=="X"&&$spot5.text()=="X"&&$spot7.text()=="X"))
{
    moves=0;counter=0;
  mbox.alert(playersname[(gamecount+1)%2]+" won the game!!..Press Reset to start new game",function(err,result){
    if (err) throw err;
  });
}
else if(($spot1.text()=="O"&&$spot2.text()=="O"&&$spot3.text()=="O")||($spot4.text()=="O"&&$spot5.text()=="O"&&$spot6.text()=="O")||($spot7.text()=="O"&&$spot8.text()=="O"&&$spot9.text()=="O")||($spot1.text()=="O"&&$spot4.text()=="O"&&$spot7.text()=="O")
||($spot2.text()=="O"&&$spot5.text()=="O"&&$spot8.text()=="O")||($spot3.text()=="O"&&$spot6.text()=="O"&&$spot9.text()=="O")||($spot1.text()=="O"&&$spot5.text()=="O"&&$spot9.text()=="O")||($spot3.text()=="O"&&$spot5.text()=="O"&&$spot7.text()=="O"))
{
    moves=0;counter=0;
    mbox.alert(playersname[gamecount]+" won the game!!..Press Reset to start new game",function(err,result){
      if (err) throw err;
    });
}
else if(moves==9)
{
  socket.emit('draw',gamecount);
  mbox.alert("the game resulted in draw",function(err,result){
    if (err) throw err;
    mbox.alert("Press Reset to start new game",function(err,result){
      if (err) throw err;
    });
  });
    socket.emit('namelist',gamecount);
}
});
socket.on('newgame1',function(data){
moves=0;counter=0;
});
$reset.click(function(e){
e.preventDefault();
$spot1.empty();$spot2.empty();$spot3.empty();$spot4.empty();$spot5.empty();$spot6.empty();$spot7.empty();$spot8.empty();$spot9.empty();
gamecount=gamecount+1;gamecount=gamecount%2;
    visited1=0;visited2=0;visited3=0;visited4=0;visited5=0;visited6=0;visited7=0;visited8=0;visited9=0;
mbox.alert(playersname[gamecount]+" will make first move",function(err,result){
  if (err) throw err;
});
});
socket.on('gotnamelist',function(data){
  playersname=data.list;
});
$spot2.click(function(){
     if(visited2==0)
    {
  if(counter==0)
  {document.getElementById("spot2").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot2").innerHTML = "X";counter=counter-1;
  }
      visited2=1;
  socket.emit('check',{area:"spot2",counter:counter,moves:moves,visited:visited2});

    }
  });
$spot3.click(function(){
     if(visited3==0)
    {
  if(counter==0)
  {document.getElementById("spot3").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot3").innerHTML = "X";counter=counter-1;
  }
     visited3=1;
  socket.emit('check',{area:"spot3",counter:counter,moves:moves,visited:visited3});

    }

});
$spot4.click(function(){
     if(visited4==0)
    {
  if(counter==0)
  {document.getElementById("spot4").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot4").innerHTML = "X";counter=counter-1;
  }
     visited4=1;
  socket.emit('check',{area:"spot4",counter:counter,moves:moves,visited:visited4});

    }
});
$spot5.click(function(){
     if(visited5==0)
    {
  if(counter==0)
  {document.getElementById("spot5").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot5").innerHTML = "X";counter=counter-1;
  }
      visited5=1;
  socket.emit('check',{area:"spot5",counter:counter,moves:moves,visited:visited5});

    }
});
$spot6.click(function(){
     if(visited6==0)
    {
  if(counter==0)
  {document.getElementById("spot6").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot6").innerHTML = "X";counter=counter-1;
  }
      visited6=1;
  socket.emit('check',{area:"spot6",counter:counter,moves:moves,visited:visited6});

    }
});
$spot7.click(function(){
     if(visited7==0)
    {
  if(counter==0)
  {document.getElementById("spot7").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot7").innerHTML = "X";counter=counter-1;
  }
       visited7=1;
  socket.emit('check',{area:"spot7",counter:counter,moves:moves,visited:visited7});

    }
                });
$spot8.click(function(){
     if(visited8==0)
    {
  if(counter==0)
  {document.getElementById("spot8").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot8").innerHTML = "X";counter=counter-1;
  }
     visited8=1;
  socket.emit('check',{area:"spot8",counter:counter,moves:moves,visited:visited8});

    }
                });
$spot9.click(function(){
     if(visited9==0)
    {
  if(counter==0)
  {document.getElementById("spot9").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot9").innerHTML = "X";counter=counter-1;
  }
    visited9=1;
  socket.emit('check',{area:"spot9",counter:counter,moves:moves,visited:visited9});

    }

});
socket.on('reset',function(data){counter=0;moves=0;gamecount=1;
$spot1.empty();$spot2.empty();$spot3.empty();$spot4.empty();$spot5.empty();$spot6.empty();$spot7.empty();$spot8.empty();$spot9.empty();
});
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    sass = require('gulp-sass'),
    mainBowerFiles = require('main-bower-files'),
    watch = require('gulp-watch'),
    clean = require('gulp-clean');

gulp.task('default', function() {
    gulp.start('sass').start('bower-files');
});
/**
 * Clean all the automatic installed files
 */
gulp.task('clean', function() {
    gulp.src(['./site/+(lib|css)/*.+(js|css)']).pipe(clean());
});

gulp.task('sass', function() {
    gulp.src('./sass/*.scss').pipe(sass({
        errLogToConsole: true
    })).pipe(gulp.dest('./site/css/'));
});

gulp.task('watch', function() {
    watch(['./sass/*.scss'], function() {
        gulp.start('sass');
    });
});
/**
 * Add the Angular and related packages
 **/
gulp.task('bower-files', function() {
    gulp.src(mainBowerFiles({
        overrides: {
            'angular': {
                main: 'angular.min.js'
            },
            'angular-component-route': {
                main: 'angular_1_router.js'
            },
            'angular-animate': {
                main: 'angular-animate.min.js'
            },
            'angular-aria': {
                main: 'angular-aria.min.js'
            },
            'angular-sanitize': {
                main: 'angular-sanitize.min.js'
            },
            'angular-messages': {
                main: 'angular-messages.min.js'
            },
            'angular-material': {
                main: [
                    'angular-material.min.js',
                    'angular-material.min.css'
                ]
            }
        }
    })).pipe(gulp.dest('./site/libs'));
});
<commit_msg>Added commentary to the action sass in gulpfile.js<commit_after>'use strict';

var gulp = require('gulp'),
    sass = require('gulp-sass'),
    mainBowerFiles = require('main-bower-files'),
    watch = require('gulp-watch'),
    clean = require('gulp-clean');

gulp.task('default', function() {
    gulp.start('sass').start('bower-files');
});
/**
 * Clean all the automatic installed files
 */
gulp.task('clean', function() {
    gulp.src(['./site/+(lib|css)/*.+(js|css)']).pipe(clean());
});
/**
 * It's only to demonstration. There is the sass on-fly compiling on the project now.
 */
gulp.task('sass', function() {
    gulp.src('./sass/*.scss').pipe(sass({
        errLogToConsole: true
    })).pipe(gulp.dest('./site/css/'));
});

gulp.task('watch', function() {
    watch(['./sass/*.scss'], function() {
        gulp.start('sass');
    });
});
/**
 * Add the Angular and related packages
 **/
gulp.task('bower-files', function() {
    gulp.src(mainBowerFiles({
        overrides: {
            'angular': {
                main: 'angular.min.js'
            },
            'angular-component-route': {
                main: 'angular_1_router.js'
            },
            'angular-animate': {
                main: 'angular-animate.min.js'
            },
            'angular-aria': {
                main: 'angular-aria.min.js'
            },
            'angular-sanitize': {
                main: 'angular-sanitize.min.js'
            },
            'angular-messages': {
                main: 'angular-messages.min.js'
            },
            'angular-material': {
                main: [
                    'angular-material.min.js',
                    'angular-material.min.css'
                ]
            }
        }
    })).pipe(gulp.dest('./site/libs'));
});
<|endoftext|>


<commit_before>const { loadAsync } = require('@expo/metro-config');
const Server = require('metro/src/Server');

async function fetchAssetManifestAsync(platform, projectRoot) {
  const config = await loadAsync(projectRoot);
  const server = new Server(config);

  const requestOpts = {
    entryFile: process.env.ENTRY_FILE || 'index.js',
    dev: false,
    minify: false,
    platform,
  };

  let assetManifest;
  let error;
  try {
    assetManifest = await server.getAssets({
      ...Server.DEFAULT_BUNDLE_OPTIONS,
      ...requestOpts,
    });
  } catch (e) {
    error = e;
  } finally {
    server.end();
  }

  if (error) {
    throw error;
  }

  return assetManifest;
}

module.exports = fetchAssetManifestAsync;
<commit_msg>[expo-updates] Change directory to project root before loading asset manifest<commit_after>const { loadAsync } = require('@expo/metro-config');
const Server = require('metro/src/Server');

async function fetchAssetManifestAsync(platform, projectRoot) {
  // Project-level babel config does not load unless we change to the
  // projectRoot before instantiating the server
  process.chdir(projectRoot)

  const config = await loadAsync(projectRoot);
  const server = new Server(config);

  const requestOpts = {
    entryFile: process.env.ENTRY_FILE || 'index.js',
    dev: false,
    minify: false,
    platform,
  };

  let assetManifest;
  let error;
  try {
    assetManifest = await server.getAssets({
      ...Server.DEFAULT_BUNDLE_OPTIONS,
      ...requestOpts,
    });
  } catch (e) {
    error = e;
  } finally {
    server.end();
  }

  if (error) {
    throw error;
  }

  return assetManifest;
}

module.exports = fetchAssetManifestAsync;
<|endoftext|>


<commit_before>define(function(require, exports, module) {

   var $            = require('jquery'),
       alerts       = require('alerts'),
       uploadifive  = require('uploadifive');

  //*******************  Add New Album  *******************//
  $('#add_new_album').click(function(){
    jPrompt('新相册名称:', '', '添加新相册', function(r) {
      if(r) {
        $.ajax({
          type   : 'POST',
          url    : '/admin/gallery/list',
          data   : {'title': r},
          success: function(e) {
            console.log(e);
          }
        });
      }
    });
  });

  //*************  PHOTO ADD ALERT  ***************//
  var album_id = $('#add_new_photo').data('albumid');
  $('#add_new_photo').uploadifive({
    method       : 'post',
    dnd          : false,
    fileType     : 'image',
    formData     : {'album_id' : album_id},
    uploadScript : '/admin/album/detail/' + album_id
  });

});
<commit_msg>new gallery auto reload<commit_after>define(function(require, exports, module) {

   var $            = require('jquery'),
       alerts       = require('alerts'),
       uploadifive  = require('uploadifive');

  //*******************  Add New Album  *******************//
  $('#add_new_album').click(function(){
    jPrompt('新相册名称:', '', '添加新相册', function(r) {
      if(r) {
        $.ajax({
          type   : 'POST',
          url    : '/admin/gallery/list',
          data   : {'title': r},
          success: function(e) {
            window.location.reload();
          }
        });
      }
    });
  });

  //*************  PHOTO ADD ALERT  ***************//
  var album_id = $('#add_new_photo').data('albumid');
  $('#add_new_photo').uploadifive({
    method       : 'post',
    dnd          : false,
    fileType     : 'image',
    formData     : {'album_id' : album_id},
    uploadScript : '/admin/album/detail/' + album_id
  });

});
<|endoftext|>


<commit_before>function resize_main_div() {
    // Resize main_div to exactly take up remaining vertical space.
    var div = $('#main_div');
    div.height(Math.max(200, div.height() + $(window).height() - $('body').height()));
}
$(function () {
    resize_main_div();
    $(window).resize(resize_main_div);
    $('#zephyr-type-tabs a').on('shown', function (e) { resize_main_div(); });
});

$(function() {
    $('#zephyr-type-tabs a[href="#class-message"]').on('shown', function (e) {
        $('#class-message input:not(:hidden):first').focus().select();
    });
    $('#zephyr-type-tabs a[href="#personal-message"]').on('shown', function (e) {
        $('#personal-message input:not(:hidden):first').focus().select();
    });
});

$.ajaxSetup({
     beforeSend: function(xhr, settings) {
         function getCookie(name) {
             var cookieValue = null;
             if (document.cookie && document.cookie != '') {
                 var cookies = document.cookie.split(';');
                 for (var i = 0; i < cookies.length; i++) {
                     var cookie = jQuery.trim(cookies[i]);
                     // Does this cookie string begin with the name we want?
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     }
});

$(function() {
    var status_classes = 'alert-error alert-success alert-info';
    var send_status = $('#send-status');
    var buttons = $('#class-message, #personal-message').find('input[type="submit"]');

    var options = {
        beforeSubmit: function (form, _options) {
            send_status.removeClass(status_classes)
                       .addClass('alert-info')
                       .text('Sending')
                       .stop(true).fadeTo(0,1);
            buttons.attr('disabled', 'disabled');
            buttons.blur()
        },
        success: function (resp, statusText, xhr, form) {
            form.find('textarea').val('');
            send_status.removeClass(status_classes)
                       .addClass('alert-success')
                       .text('Sent message')
                       .stop(true).fadeTo(0,1).delay(1000).fadeOut(1000);
            buttons.removeAttr('disabled');
        },
        error: function() {
            send_status.removeClass(status_classes)
                       .addClass('alert-error')
                       .text('Error sending message ')
                       .append($('')
                           .addClass('send-status-close').html('×')
                           .click(function () { send_status.stop(true).fadeOut(500); }))
                       .stop(true).fadeTo(0,1);

            buttons.removeAttr('disabled');
        }
    };

    send_status.hide();
    $("#class-message form").ajaxForm(options);
    $("#personal-message form").ajaxForm(options);
});

selected_tag = '
▶
'

var allow_hotkeys = true;

function select_zephyr(next_zephyr) {
    p = $("#selected");
    td = $(p).closest("td");
    if (next_zephyr.length != 0) { // We are not at the bottom or top of the zephyrs.
        td.empty(); // Clear the previous arrow.
        next_zephyr.children("td:first").html(selected_tag);
        $.post("update", {pointer: next_zephyr.attr("id")});

        if (($(next_zephyr).offset().top < $("#main_div").offset().top) ||
            ($(next_zephyr).offset().top + $(next_zephyr).height() > $("#main_div").offset().top + $("#main_div").height())) {
            scroll_to_selected();
        }
    }
}

// NB: This just binds to current elements, and won't bind to elements
// created after ready() is called.

$(document).ready(function() {
    $('input, textarea, button').focus(function() {
          allow_hotkeys = false;
    });

    $('input, textarea, button').blur(function() {
          allow_hotkeys = true;
    });
    $("body").delegate("p", "click", function(){
        select_zephyr($(this).parent().parent());
    });

    $.get('get_state', function(data) {
	    select_zephyr($("#" + data.pointer));
	}, dataType="json");
});

var goto_pressed = false;

$(document).keydown(function(event) {
    if (allow_hotkeys) {

        if (event.keyCode == 38 || event.keyCode == 40) { // down or up arrow

            p = $("#selected");
            tr = $(p).closest("tr");
            if (event.keyCode == 40) { // down arrow
                // There are probably more verbose but more efficient ways to do this.
                next_zephyr = tr.nextAll(":not(:hidden):first");
            } else { // up arrow
                next_zephyr = tr.prevAll(":not(:hidden):first");
            }
            select_zephyr(next_zephyr);
            event.preventDefault();
        } else if (event.keyCode == 82) { // 'r' keypress, for responding to a zephyr
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var instance = parent.find("span.zephyr_instance").text();
            if (zephyr_class != '') {
                $('#zephyr-type-tabs a[href="#class-message"]').tab('show');
                $("#class").val(zephyr_class);
                $("#instance").val(instance);
                $("#new_zephyr").focus();
                $("#new_zephyr").select();
            } else { // No instance, must be a personal

                var recipient = parent.find("span.zephyr_sender").text();
                if (recipient == username) { // that is, we sent the original message
                    recipient = parent.find("span.zephyr_personal_recipient").text();
                }
                prepare_personal(recipient);
                $("#new_personal_zephyr").focus();
                $("#new_personal_zephyr").select();
            }
            event.preventDefault();
        } else if (event.keyCode == 71) { // 'g' keypress, set trigger for "go to"
            goto_pressed = true;
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 67) { // 'c' keypress, for narrow-by-recipient
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            narrow(zephyr_class, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 73) { // 'i' keypress, for narrow-by-instance
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var zephyr_instance = parent.find("span.zephyr_instance").text();
            narrow_instance(zephyr_class, zephyr_instance, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 80) { // 'p' keypress, for narrow-to-personals
            narrow_personals($("#selected").parents("tr").attr("id"));
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 65) { // 'a' keypress, for unnarrow
            unhide();
            event.preventDefault();
        }

        if (event.keyCode != 71) { // not 'g'
            goto_pressed = false;
        }

    } else if (event.keyCode == 27) { // Esc pressed
        $('input, textarea, button').blur();
        event.preventDefault();
    }
});

function scroll_to_selected() {
    $('#main_div').scrollTop(0);
    $('#main_div').scrollTop($("#selected").offset().top - $('#main_div').height()/1.5);

}

function home_view(element) {
    return true;
}

var current_view_predicate = home_view;

function current_view(element) {
    if (current_view_predicate(element)) {
        element.show()
    } else {
        element.hide()
    }
}

function do_narrow(target_zephyr, description, filter_function) {
    // We want the zephyr on which the narrow happened to stay in the same place if possible.
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;
    current_view_predicate = filter_function;
    $("tr").each(function() {
        current_view($(this))
    });

    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});

    scroll_to_selected();

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html(description);
}

function narrow_personals(target_zephyr) {
    var message = "Showing personals";
    do_narrow(target_zephyr, message,
              function(element) {
                  return (element.find("span.zephyr_personal_recipient").length > 0);
              }
             );
}

function narrow_class(class_name, target_zephyr) {
    var message = "Showing " + class_name + "";
    do_narrow(target_zephyr, message,
              function(element) {
                  return (element.find("span.zephyr_class").length > 0 &&
                          element.find("span.zephyr_class").text() == class_name);
              }
             );
}

function narrow_instance(class_name, instance, target_zephyr) {
    var message = "Showing " + class_name
        + " " + instance + "";
    do_narrow(target_zephyr, message,
              function(element) {
                  return (element.find("span.zephyr_class").length > 0 &&
                          element.find("span.zephyr_class").text() == class_name &&
                          element.find("span.zephyr_instance").text() == instance);
              }
             );
}

function prepare_personal(username) {
    $('#zephyr-type-tabs a[href="#personal-message"]').tab('show');
    $("#recipient").val(username);
    $("#new_personal_zephyr").focus();
}

function unhide() {
    current_view_predicate = home_view;
    $("tr").show();

    scroll_to_selected();

    $("#unhide").attr("disabled", "disabled");
    $("#narrow_indicator").html("");
}

function newline2br(content) {
    return content.replace(/\n/g, '
');
}

function add_message(index, zephyr) {
    var zephyr_para = $('
');
    var new_label = function (text, classes, on_click) {
        zephyr_para.append($('')
            .text(text)
            .addClass('label zephyr_label_clickable ' + classes)
            .click(on_click));
        zephyr_para.append(' ');
    };

    if (zephyr.type == 'class') {
        new_label(zephyr.display_recipient, 'zephyr_class',
            function (e) { narrow_class(zephyr.display_recipient, zephyr.id); });
        new_label(zephyr.instance, 'zephyr_instance',
            function (e) { narrow_instance(zephyr.display_recipient,
                                           zephyr.instance, zephyr.id); });
    } else {
        new_label(zephyr.display_recipient, 'zephyr_personal_recipient',
            function (e) { narrow_personals(zephyr.id); });
        zephyr_para.append('← ');
    }

    new_label(zephyr.sender, 'zephyr_sender',
             function (e) { prepare_personal(zephyr.sender); });

    zephyr_para.append('
' + newline2br(zephyr.content));

    $('#table tr:last').after($('
')
        .attr('id', zephyr.id)
        .append('

	')
        .append($('').append(zephyr_para)));
}

$(function() {
  $(initial_zephyr_json).each(add_message);
});

var longpoll_failures = 0;

function get_updates_longpoll(data) {
    if (data && data.zephyrs) {
        $.each(data.zephyrs, add_message);
    }
    var last_received = $("tr:last").attr("id");
    $.ajax({
        type:     'POST',
        url:      'get_updates_longpoll',
        data:     { last_received: last_received },
        dataType: 'json',
        success: function (data) {
            longpoll_failures = 0;
            get_updates_longpoll(data);
        },
        error: function () {
            longpoll_failures += 1;
            if (longpoll_failures >= 6) {
                $('#connection-error').show();
                resize_main_div();
            } else {
                setTimeout(get_updates_longpoll, 5*1000);
            }
        }
    });
}

$(function () {
    get_updates_longpoll();
});

<commit_msg>Filter newly arriving messages by the current view.<commit_after>function resize_main_div() {
    // Resize main_div to exactly take up remaining vertical space.
    var div = $('#main_div');
    div.height(Math.max(200, div.height() + $(window).height() - $('body').height()));
}
$(function () {
    resize_main_div();
    $(window).resize(resize_main_div);
    $('#zephyr-type-tabs a').on('shown', function (e) { resize_main_div(); });
});

$(function() {
    $('#zephyr-type-tabs a[href="#class-message"]').on('shown', function (e) {
        $('#class-message input:not(:hidden):first').focus().select();
    });
    $('#zephyr-type-tabs a[href="#personal-message"]').on('shown', function (e) {
        $('#personal-message input:not(:hidden):first').focus().select();
    });
});

$.ajaxSetup({
     beforeSend: function(xhr, settings) {
         function getCookie(name) {
             var cookieValue = null;
             if (document.cookie && document.cookie != '') {
                 var cookies = document.cookie.split(';');
                 for (var i = 0; i < cookies.length; i++) {
                     var cookie = jQuery.trim(cookies[i]);
                     // Does this cookie string begin with the name we want?
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     }
});

$(function() {
    var status_classes = 'alert-error alert-success alert-info';
    var send_status = $('#send-status');
    var buttons = $('#class-message, #personal-message').find('input[type="submit"]');

    var options = {
        beforeSubmit: function (form, _options) {
            send_status.removeClass(status_classes)
                       .addClass('alert-info')
                       .text('Sending')
                       .stop(true).fadeTo(0,1);
            buttons.attr('disabled', 'disabled');
            buttons.blur()
        },
        success: function (resp, statusText, xhr, form) {
            form.find('textarea').val('');
            send_status.removeClass(status_classes)
                       .addClass('alert-success')
                       .text('Sent message')
                       .stop(true).fadeTo(0,1).delay(1000).fadeOut(1000);
            buttons.removeAttr('disabled');
        },
        error: function() {
            send_status.removeClass(status_classes)
                       .addClass('alert-error')
                       .text('Error sending message ')
                       .append($('')
                           .addClass('send-status-close').html('×')
                           .click(function () { send_status.stop(true).fadeOut(500); }))
                       .stop(true).fadeTo(0,1);

            buttons.removeAttr('disabled');
        }
    };

    send_status.hide();
    $("#class-message form").ajaxForm(options);
    $("#personal-message form").ajaxForm(options);
});

selected_tag = '
▶
'

var allow_hotkeys = true;

function select_zephyr(next_zephyr) {
    p = $("#selected");
    td = $(p).closest("td");
    if (next_zephyr.length != 0) { // We are not at the bottom or top of the zephyrs.
        td.empty(); // Clear the previous arrow.
        next_zephyr.children("td:first").html(selected_tag);
        $.post("update", {pointer: next_zephyr.attr("id")});

        if (($(next_zephyr).offset().top < $("#main_div").offset().top) ||
            ($(next_zephyr).offset().top + $(next_zephyr).height() > $("#main_div").offset().top + $("#main_div").height())) {
            scroll_to_selected();
        }
    }
}

// NB: This just binds to current elements, and won't bind to elements
// created after ready() is called.

$(document).ready(function() {
    $('input, textarea, button').focus(function() {
          allow_hotkeys = false;
    });

    $('input, textarea, button').blur(function() {
          allow_hotkeys = true;
    });
    $("body").delegate("p", "click", function(){
        select_zephyr($(this).parent().parent());
    });

    $.get('get_state', function(data) {
	    select_zephyr($("#" + data.pointer));
	}, dataType="json");
});

var goto_pressed = false;

$(document).keydown(function(event) {
    if (allow_hotkeys) {

        if (event.keyCode == 38 || event.keyCode == 40) { // down or up arrow

            p = $("#selected");
            tr = $(p).closest("tr");
            if (event.keyCode == 40) { // down arrow
                // There are probably more verbose but more efficient ways to do this.
                next_zephyr = tr.nextAll(":not(:hidden):first");
            } else { // up arrow
                next_zephyr = tr.prevAll(":not(:hidden):first");
            }
            select_zephyr(next_zephyr);
            event.preventDefault();
        } else if (event.keyCode == 82) { // 'r' keypress, for responding to a zephyr
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var instance = parent.find("span.zephyr_instance").text();
            if (zephyr_class != '') {
                $('#zephyr-type-tabs a[href="#class-message"]').tab('show');
                $("#class").val(zephyr_class);
                $("#instance").val(instance);
                $("#new_zephyr").focus();
                $("#new_zephyr").select();
            } else { // No instance, must be a personal

                var recipient = parent.find("span.zephyr_sender").text();
                if (recipient == username) { // that is, we sent the original message
                    recipient = parent.find("span.zephyr_personal_recipient").text();
                }
                prepare_personal(recipient);
                $("#new_personal_zephyr").focus();
                $("#new_personal_zephyr").select();
            }
            event.preventDefault();
        } else if (event.keyCode == 71) { // 'g' keypress, set trigger for "go to"
            goto_pressed = true;
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 67) { // 'c' keypress, for narrow-by-recipient
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            narrow(zephyr_class, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 73) { // 'i' keypress, for narrow-by-instance
            var parent = $("#selected").parents("tr");
            var zephyr_class = parent.find("span.zephyr_class").text();
            var zephyr_instance = parent.find("span.zephyr_instance").text();
            narrow_instance(zephyr_class, zephyr_instance, parent.attr("id"));
            event.preventDefault()
        } else if (goto_pressed && event.keyCode == 80) { // 'p' keypress, for narrow-to-personals
            narrow_personals($("#selected").parents("tr").attr("id"));
            event.preventDefault();
        } else if (goto_pressed && event.keyCode == 65) { // 'a' keypress, for unnarrow
            unhide();
            event.preventDefault();
        }

        if (event.keyCode != 71) { // not 'g'
            goto_pressed = false;
        }

    } else if (event.keyCode == 27) { // Esc pressed
        $('input, textarea, button').blur();
        event.preventDefault();
    }
});

function scroll_to_selected() {
    $('#main_div').scrollTop(0);
    $('#main_div').scrollTop($("#selected").offset().top - $('#main_div').height()/1.5);

}

function home_view(element) {
    return true;
}

var current_view_predicate = home_view;

function current_view(element) {
    if (current_view_predicate(element)) {
        element.show()
    } else {
        element.hide()
    }
}

function do_narrow(target_zephyr, description, filter_function) {
    // We want the zephyr on which the narrow happened to stay in the same place if possible.
    var old_top = $("#main_div").offset().top - $("#" + target_zephyr).offset().top;
    current_view_predicate = filter_function;
    $("tr").each(function() {
        current_view($(this))
    });

    $("#selected").closest("td").empty();
    $("#" + target_zephyr).children("td:first").html(selected_tag);
    $.post("update", {pointer: target_zephyr});

    scroll_to_selected();

    $("#unhide").removeAttr("disabled");
    $("#narrow_indicator").html(description);
}

function narrow_personals(target_zephyr) {
    var message = "Showing personals";
    do_narrow(target_zephyr, message,
              function(element) {
                  return (element.find("span.zephyr_personal_recipient").length > 0);
              }
             );
}

function narrow_class(class_name, target_zephyr) {
    var message = "Showing " + class_name + "";
    do_narrow(target_zephyr, message,
              function(element) {
                  return (element.find("span.zephyr_class").length > 0 &&
                          element.find("span.zephyr_class").text() == class_name);
              }
             );
}

function narrow_instance(class_name, instance, target_zephyr) {
    var message = "Showing " + class_name
        + " " + instance + "";
    do_narrow(target_zephyr, message,
              function(element) {
                  return (element.find("span.zephyr_class").length > 0 &&
                          element.find("span.zephyr_class").text() == class_name &&
                          element.find("span.zephyr_instance").text() == instance);
              }
             );
}

function prepare_personal(username) {
    $('#zephyr-type-tabs a[href="#personal-message"]').tab('show');
    $("#recipient").val(username);
    $("#new_personal_zephyr").focus();
}

function unhide() {
    current_view_predicate = home_view;
    $("tr").show();

    scroll_to_selected();

    $("#unhide").attr("disabled", "disabled");
    $("#narrow_indicator").html("");
}

function newline2br(content) {
    return content.replace(/\n/g, '
');
}

function add_message(index, zephyr) {
    var zephyr_para = $('
');
    var new_label = function (text, classes, on_click) {
        zephyr_para.append($('')
            .text(text)
            .addClass('label zephyr_label_clickable ' + classes)
            .click(on_click));
        zephyr_para.append(' ');
    };

    if (zephyr.type == 'class') {
        new_label(zephyr.display_recipient, 'zephyr_class',
            function (e) { narrow_class(zephyr.display_recipient, zephyr.id); });
        new_label(zephyr.instance, 'zephyr_instance',
            function (e) { narrow_instance(zephyr.display_recipient,
                                           zephyr.instance, zephyr.id); });
    } else {
        new_label(zephyr.display_recipient, 'zephyr_personal_recipient',
            function (e) { narrow_personals(zephyr.id); });
        zephyr_para.append('← ');
    }

    new_label(zephyr.sender, 'zephyr_sender',
             function (e) { prepare_personal(zephyr.sender); });

    zephyr_para.append('
' + newline2br(zephyr.content));

    $('#table tr:last').after($('
')
        .attr('id', zephyr.id)
        .append('

	')
        .append($('').append(zephyr_para)));
    current_view($('tr[id="' + zephyr.id + '"]'));
}

$(function() {
  $(initial_zephyr_json).each(add_message);
});

var longpoll_failures = 0;

function get_updates_longpoll(data) {
    if (data && data.zephyrs) {
        $.each(data.zephyrs, add_message);
    }
    var last_received = $("tr:last").attr("id");
    $.ajax({
        type:     'POST',
        url:      'get_updates_longpoll',
        data:     { last_received: last_received },
        dataType: 'json',
        success: function (data) {
            longpoll_failures = 0;
            get_updates_longpoll(data);
        },
        error: function () {
            longpoll_failures += 1;
            if (longpoll_failures >= 6) {
                $('#connection-error').show();
                resize_main_div();
            } else {
                setTimeout(get_updates_longpoll, 5*1000);
            }
        }
    });
}

$(function () {
    get_updates_longpoll();
});

<|endoftext|>


<commit_before>
/**
 * Test dependencies
 *
 * @api private
 */

var sio = require('socket.io')
  , redis = require('redis')
  , should = require('should')
  , RedisStore = sio.RedisStore;

/**
 * Test.
 */

module.exports = {

  'test publishing doesnt get caught by the own store subscriber': function (done) {
    var a = new RedisStore
      , b = new RedisStore;

    a.subscribe('woot', function (arg) {
      arg.should.equal('bb');
      a.destroy();
      b.destroy();
      done();
    }, function () {
      a.publish('woot', 'aa');
      b.publish('woot', 'bb');
    });
  },

  'test publishing to multiple subscribers': function (done) {
    var a = new RedisStore
      , b = new RedisStore
      , c = new RedisStore
      , subscriptions = 3
      , messages = 2;

    a.subscribe('tobi', function () {
      throw new Error('Shouldnt publish to itself');
    }, publish);

    function subscription (arg1, arg2, arg3) {
      arg1.should.equal(1);
      arg2.should.equal(2);
      arg3.should.equal(3);
      --messages || finish();
    }

    b.subscribe('tobi', subscription, publish);
    c.subscribe('tobi', subscription, publish);

    function publish () {
      --subscriptions || a.publish('tobi', 1, 2, 3);
    }

    function finish () {
      a.destroy();
      b.destroy();
      c.destroy();
      done();
    }
  },

  'test storing data for a client': function (done) {
    var store = new RedisStore
      , rand = 'test-' + Date.now()
      , client = store.client(rand);

    client.id.should.equal(rand);

    client.set('a', 'b', function (err) {
      should.strictEqual(err, null);

      client.get('a', function (err, val) {
        should.strictEqual(err, null);
        val.should.equal('b');

        client.has('a', function (err, has) {
          should.strictEqual(err, null);
          has.should.be.true;

          client.has('b', function (err, has) {
            should.strictEqual(err, null);
            has.should.be.false;

            client.del('a', function (err) {
              should.strictEqual(err, null);

              client.has('a', function (err, has) {
                should.strictEqual(err, null);
                has.should.be.false;

                client.set('b', 'c', function (err) {
                  should.strictEqual(err, null);

                  client.set('c', 'd', function (err) {
                    should.strictEqual(err, null);

                    client.get('b', function (err, val) {
                      should.strictEqual(err, null);
                      val.should.equal('c');

                      client.get('c', function (err, val) {
                        should.strictEqual(err, null);
                        val.should.equal('d');

                        store.destroy();
                        done();
                      });
                    });
                  });
                });
              });
            });
          });
        });
      });
    });
  },

  'test cleaning up clients data': function (done) {
    var rand1 = Math.abs(Math.random() * Date.now() | 0)
      , rand2 = Math.abs(Math.random() * Date.now() | 0);

    var store = new RedisStore()
      , client1 = store.client(rand1)
      , client2 = store.client(rand2);

    client1.set('a', 'b', function (err) {
      should.strictEqual(err, null);

      client2.set('c', 'd', function (err) {
        should.strictEqual(err, null);

        client1.has('a', function (err, val) {
          should.strictEqual(err, null);
          val.should.be.true;

          client2.has('c', function (err, val) {
            should.strictEqual(err, null);
            val.should.be.true;

            store.destroy();

            var newstore = new RedisStore()
              , newclient1 = newstore.client(rand1)
              , newclient2 = newstore.client(rand2);

            newclient1.has('a', function (err, val) {
              should.strictEqual(err, null);
              val.should.be.false;

              newclient2.has('c', function (err, val) {
                should.strictEqual(err, null);
                val.should.be.false;

                newstore.destroy();
                done();
              });
            });
          });
        });
      });
    });
  },

  'test cleaning up a particular client': function (done) {
    var rand1 = Math.abs(Math.random() * Date.now() | 0)
      , rand2 = Math.abs(Math.random() * Date.now() | 0);

    var store = new RedisStore()
      , client1 = store.client(rand1)
      , client2 = store.client(rand2);

    client1.set('a', 'b', function (err) {
      should.strictEqual(err, null);

      client2.set('c', 'd', function (err) {
        should.strictEqual(err, null);

        client1.has('a', function (err, val) {
          should.strictEqual(err, null);
          val.should.be.true;

          client2.has('c', function (err, val) {
            should.strictEqual(err, null);
            val.should.be.true;

            store.clients.should.have.property(rand1);
            store.clients.should.have.property(rand2);
            store.destroyClient(rand1);

            store.clients.should.not.have.property(rand1);
            store.clients.should.have.property(rand2);

            client1.has('a', function (err, val) {
              should.strictEqual(err, null);
              val.should.equal(false);

              store.destroy();
              done();
            });
          });
        });
      });
    });
  }

};
<commit_msg>Added RedisStore expiration tests.<commit_after>
/**
 * Test dependencies
 *
 * @api private
 */

var sio = require('socket.io')
  , redis = require('redis')
  , should = require('should')
  , RedisStore = sio.RedisStore;

/**
 * Test.
 */

module.exports = {

  'test publishing doesnt get caught by the own store subscriber': function (done) {
    var a = new RedisStore
      , b = new RedisStore;

    a.subscribe('woot', function (arg) {
      arg.should.equal('bb');
      a.destroy();
      b.destroy();
      done();
    }, function () {
      a.publish('woot', 'aa');
      b.publish('woot', 'bb');
    });
  },

  'test publishing to multiple subscribers': function (done) {
    var a = new RedisStore
      , b = new RedisStore
      , c = new RedisStore
      , subscriptions = 3
      , messages = 2;

    a.subscribe('tobi', function () {
      throw new Error('Shouldnt publish to itself');
    }, publish);

    function subscription (arg1, arg2, arg3) {
      arg1.should.equal(1);
      arg2.should.equal(2);
      arg3.should.equal(3);
      --messages || finish();
    }

    b.subscribe('tobi', subscription, publish);
    c.subscribe('tobi', subscription, publish);

    function publish () {
      --subscriptions || a.publish('tobi', 1, 2, 3);
    }

    function finish () {
      a.destroy();
      b.destroy();
      c.destroy();
      done();
    }
  },

  'test storing data for a client': function (done) {
    var store = new RedisStore
      , rand = 'test-' + Date.now()
      , client = store.client(rand);

    client.id.should.equal(rand);

    client.set('a', 'b', function (err) {
      should.strictEqual(err, null);

      client.get('a', function (err, val) {
        should.strictEqual(err, null);
        val.should.equal('b');

        client.has('a', function (err, has) {
          should.strictEqual(err, null);
          has.should.be.true;

          client.has('b', function (err, has) {
            should.strictEqual(err, null);
            has.should.be.false;

            client.del('a', function (err) {
              should.strictEqual(err, null);

              client.has('a', function (err, has) {
                should.strictEqual(err, null);
                has.should.be.false;

                client.set('b', 'c', function (err) {
                  should.strictEqual(err, null);

                  client.set('c', 'd', function (err) {
                    should.strictEqual(err, null);

                    client.get('b', function (err, val) {
                      should.strictEqual(err, null);
                      val.should.equal('c');

                      client.get('c', function (err, val) {
                        should.strictEqual(err, null);
                        val.should.equal('d');

                        store.destroy();
                        done();
                      });
                    });
                  });
                });
              });
            });
          });
        });
      });
    });
  },

  'test cleaning up clients data': function (done) {
    var rand1 = Math.abs(Math.random() * Date.now() | 0)
      , rand2 = Math.abs(Math.random() * Date.now() | 0);

    var store = new RedisStore()
      , client1 = store.client(rand1)
      , client2 = store.client(rand2);

    client1.set('a', 'b', function (err) {
      should.strictEqual(err, null);

      client2.set('c', 'd', function (err) {
        should.strictEqual(err, null);

        client1.has('a', function (err, val) {
          should.strictEqual(err, null);
          val.should.be.true;

          client2.has('c', function (err, val) {
            should.strictEqual(err, null);
            val.should.be.true;

            store.destroy();

            var newstore = new RedisStore()
              , newclient1 = newstore.client(rand1)
              , newclient2 = newstore.client(rand2);

            newclient1.has('a', function (err, val) {
              should.strictEqual(err, null);
              val.should.be.false;

              newclient2.has('c', function (err, val) {
                should.strictEqual(err, null);
                val.should.be.false;

                newstore.destroy();
                done();
              });
            });
          });
        });
      });
    });
  },

  'test cleaning up a particular client': function (done) {
    var rand1 = Math.abs(Math.random() * Date.now() | 0)
      , rand2 = Math.abs(Math.random() * Date.now() | 0);

    var store = new RedisStore()
      , client1 = store.client(rand1)
      , client2 = store.client(rand2);

    client1.set('a', 'b', function (err) {
      should.strictEqual(err, null);

      client2.set('c', 'd', function (err) {
        should.strictEqual(err, null);

        client1.has('a', function (err, val) {
          should.strictEqual(err, null);
          val.should.be.true;

          client2.has('c', function (err, val) {
            should.strictEqual(err, null);
            val.should.be.true;

            store.clients.should.have.property(rand1);
            store.clients.should.have.property(rand2);
            store.destroyClient(rand1);

            store.clients.should.not.have.property(rand1);
            store.clients.should.have.property(rand2);

            client1.has('a', function (err, val) {
              should.strictEqual(err, null);
              val.should.equal(false);

              store.destroy();
              done();
            });
          });
        });
      });
    });
  },

  'test destroy expiration': function (done) {
    var store = new RedisStore()
      , id = Math.abs(Math.random() * Date.now() | 0)
      , client = store.client(id);

    client.set('a', 'b', function (err) {
      should.strictEqual(err, null);
      store.destroyClient(id, 1);

      setTimeout(function () {
        client.get('a', function (err, val) {
          should.strictEqual(err, null);
          val.should.equal('b');
        });
      }, 500);

      setTimeout(function () {
        client.get('a', function (err, val) {
          should.strictEqual(err, null);
          should.strictEqual(val, null);

          store.destroy();
          done();
        });
      }, 1900);
    });
  }

};
<|endoftext|>


<commit_before>//Function to get more than one tag out of the instagetter
//When calling the function the params should be in a string like - instaGetter('firsttag, secondtag, thirdtag');
//The function will split on the commas and create a feed for each tag

//NOW ONLY OPTIMIZED FOR 1 TAG

function instaGetter(params){
	$("#choosenHash").html('#' + params);
	array_of_tags = params.split(', ');
	var name_of_tag;
	var currentOBJ = '';
	var doFeed = true;

	for (var i = 0; i < array_of_tags.length; i++){
		//The tagname to use
		if(currentOBJ == ''){
			name_of_tag = array_of_tags[i];
			$('#instafeed').append('

');
		}

		var feed = new Instafeed({
			target: name_of_tag,
			get: 'tagged',
			tagName: name_of_tag,
			clientId: 'bf5093520bb54d3cac22e936e98a3804',
			limit: 60,
			template: '

{{model.user.username}}

',
			success: function(data){

				///////
				if (currentOBJ == ''){
					doFeed = true;
					currentOBJ = data;
					console.log('it changed');
				}else{
					if(data.data[0].id == currentOBJ.data[0].id){
						//Do nothing
						console.log('exactly the same');
						doFeed = false;
						return;

					}else{
						doFeed = true;
						currentOBJ = data;
						console.log('it changed');
					}
				}
				/////////
			}
		});

	feed.run();
	setInterval(function(){
		//Run the feed
		if(doFeed){
			feed.mock = true;
			feed.run();
			console.log('should be imgs')
		}else{
			feed.mock = false;
			feed.run();
			console.log('should not put imgs');
		}

	},6000)

	}
}

//This is the caller of the function!! put in the tag u want to use!!
instaGetter('batman');<commit_msg>Update rasmus.js<commit_after>//Function to get more than one tag out of the instagetter
//When calling the function the params should be in a string like - instaGetter('firsttag, secondtag, thirdtag');
//The function will split on the commas and create a feed for each tag

//NOW ONLY OPTIMIZED FOR 1 TAG

function instaGetter(params){
	$("#choosenHash").html('#' + params);
	array_of_tags = params.split(', ');
	var name_of_tag;
	var currentOBJ = '';
	var doFeed = true;

	for (var i = 0; i < array_of_tags.length; i++){
		//The tagname to use
		if(currentOBJ == ''){
			name_of_tag = array_of_tags[i];
			$('#instafeed').append('

');
		}

		var feed = new Instafeed({
			target: name_of_tag,
			get: 'tagged',
			tagName: name_of_tag,
			clientId: 'PUT YOUR API CLIENT ID HERE',
			limit: 60,
			template: '

{{model.user.username}}

',
			success: function(data){

				///////
				if (currentOBJ == ''){
					doFeed = true;
					currentOBJ = data;
					console.log('it changed');
				}else{
					if(data.data[0].id == currentOBJ.data[0].id){
						//Do nothing
						console.log('exactly the same');
						doFeed = false;
						return;

					}else{
						doFeed = true;
						currentOBJ = data;
						console.log('it changed');
					}
				}
				/////////
			}
		});

	feed.run();
	setInterval(function(){
		//Run the feed
		if(doFeed){
			feed.mock = true;
			feed.run();
			console.log('should be imgs')
		}else{
			feed.mock = false;
			feed.run();
			console.log('should not put imgs');
		}

	},6000)

	}
}

//This is the caller of the function!! put in the tag u want to use!!
instaGetter('batman');
<|endoftext|>


<commit_before>// Load modules

var Hoek = require('hoek');
var Joi = require('joi');
var Mongoose = require('mongoose');
var Async = require('async');
var Path = require('path');
var Glob = require('glob');

// Declare internals

var internals = {
	schema: Joi.object({
		pattern: Joi.string().required(),	// Glob pattern
		options: Joi.object({				// Glob options
			cwd: Joi.string().required()
		}).unknown(true).required()
	})
};

exports.register = function (server, options, next) {

	var results = Joi.validate(options, internals.schema);
	Hoek.assert(!results.error, 'Invalid options ' + results.error);
	var settings = results.value;

	Glob(settings.pattern, settings.options, function (err, files) {

		Hoek.assert(!err, err);

		Async.each(files, function (file, callback) {

			var path = Path.resolve(settings.options.cwd, file);
			var module = require(path);
			var model = module

			if (module.hasOwnProperty('load') && typeof(module.load) === 'function') {
				model = module.load(server);
			}

			if (model.schema instanceof Mongoose.Schema) {
				server.expose(model.modelName, model);
				server.log('hapi-mongoose-models', 'Model `' + model.modelName + '` loaded');
			}
			else {
				server.log('hapi-mongoose-models', 'File `' + file + '` not ' +
						   'contains a mongoose mode, will be ignored')
			}

			return Hoek.nextTick(callback)();
		}, next);
	});
};

exports.register.attributes = {
	pkg: require('../package.json')
};
<commit_msg>fix text in log<commit_after>// Load modules

var Hoek = require('hoek');
var Joi = require('joi');
var Mongoose = require('mongoose');
var Async = require('async');
var Path = require('path');
var Glob = require('glob');

// Declare internals

var internals = {
	schema: Joi.object({
		pattern: Joi.string().required(),	// Glob pattern
		options: Joi.object({				// Glob options
			cwd: Joi.string().required()
		}).unknown(true).required()
	})
};

exports.register = function (server, options, next) {

	var results = Joi.validate(options, internals.schema);
	Hoek.assert(!results.error, 'Invalid options ' + results.error);
	var settings = results.value;

	Glob(settings.pattern, settings.options, function (err, files) {

		Hoek.assert(!err, err);

		Async.each(files, function (file, callback) {

			var path = Path.resolve(settings.options.cwd, file);
			var module = require(path);
			var model = module

			if (module.hasOwnProperty('load') && typeof(module.load) === 'function') {
				model = module.load(server);
			}

			if (model.schema instanceof Mongoose.Schema) {
				server.expose(model.modelName, model);
				server.log('hapi-mongoose-models', 'Model `' + model.modelName + '` loaded');
			}
			else {
				server.log('hapi-mongoose-models', 'File `' + file + '` not ' +
						   'contains a mongoose model, will be ignored')
			}

			return Hoek.nextTick(callback)();
		}, next);
	});
};

exports.register.attributes = {
	pkg: require('../package.json')
};
<|endoftext|>


<commit_before>var express = require('express');
var app = module.exports = express();
var server = require('http').createServer(app)
var io = require("socket.io").listen(server);
//var socket = io.listen(server);
var uuid = require('node-uuid');
var Room = require('./room.js');

app.configure(function() {
	app.locals.pretty = true;
	  app.use(express.bodyParser());
	  app.use(express.methodOverride());
	  app.use(express.static(__dirname + '/public'));
	  app.use('/components', express.static(__dirname + '/components'));
	  app.use('/js', express.static(__dirname + '/js'));
	  app.set('views', __dirname + '/views');
	  app.engine('html', require('ejs').renderFile);
});

app.get('/', function(req, res) {
  res.render('index.html');
});

server.listen(3000, "192.168.56.101",  function(){
  console.log("Express server up and running.");
});

io.set("log level", 1);
var people = {};
var rooms = {};
var sockets = [];

Array.prototype.contains = function(k, callback) {
    var self = this;
    return (function check(i) {
        if (i >= self.length) {
            return callback(false);
        }
        if (self[i] === k) {
            return callback(true);
        }
        return process.nextTick(check.bind(null, i+1));
    }(0));
};

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return true;
}

io.sockets.on("connection", function (socket) {

	socket.on("joinserver", function(name) {
		ownerRoomID = inRoomID = null;
		people[socket.id] = {"name" : name, "owns" : ownerRoomID, "inroom": inRoomID};
		socket.emit("update", "You have connected to the server.");
		io.sockets.emit("update", people[socket.id].name + " is online.")
		sizePeople = Object.size(people);
		sizeRooms = Object.size(rooms);
		io.sockets.emit("update-people", {people: people, count: sizePeople});
		socket.emit("roomList", {rooms: rooms, count: sizeRooms});
		sockets.push(socket);
	});

	socket.on("send", function(msg) {
		var re = /^[w]:.*:/;
		var whisper = re.test(msg);
		var whisperStr = msg.split(":");
		var found = false;
		if (whisper) {
			var whisperTo = whisperStr[1];
			var keys = Object.keys(people);
			if (keys.length != 0) {
				for (var i = 0; i<keys.length; i++) {
					if (people[keys[i]].name === whisperTo) {
						var whisperId = keys[i];
						found = true;
						if (socket.id === whisperId) { //can't whisper to ourselves
							socket.emit("update", "You can't whisper to yourself.");
						}
						break;
					}
				}
			}
			if (found && socket.id !== whisperId) {
				var whisperTo = whisperStr[1];
				var whisperMsg = whisperStr[2];
				socket.emit("whisper", {name: "You"}, whisperMsg);
				io.sockets.socket(whisperId).emit("whisper", people[socket.id], whisperMsg);
			} else {
				socket.emit("update", "Can't find " + whisperTo);
			}
		} else {
			if (io.sockets.manager.roomClients[socket.id]['/'+socket.room] !== undefined ) {
				io.sockets.in(socket.room).emit("chat", people[socket.id], msg);
		    	} else {
				socket.emit("update", "Please connect to a room.");
		    	}
		}
	});

	socket.on("disconnect", function() {
		if (typeof people[socket.id] !== "undefined") {
			if (people[socket.id].inroom === null) {
				//io.sockets.emit("update", people[socket.id].name + " has left the server.");
				delete people[socket.id];
				sizePeople = Object.size(people);
				io.sockets.emit("update-people", {people: people, count: sizePeople});
			} else {
				if (people[socket.id].owns !== null) {
					var room= rooms[people[socket.id].owns];
					if (socket.id === room.owner) {
						io.sockets.in(socket.room).emit("update", "The owner (" +people[socket.id].name + ") has left the server. The room is removed and you have been disconnected from it as well.");
						var i = 0;
						while(i < sockets.length) {
							if (sockets[i].id === room.people[i]) {
								people[sockets[i].id].inroom = null;
								sockets[i].leave(room.name);
							}
					    		++i;
						}
						delete rooms[people[socket.id].owns];
					}
				}
				io.sockets.emit("update", people[socket.id].name + " has left the server.");
				delete people[socket.id];
				sizePeople = Object.size(people);
				sizeRooms = Object.size(rooms);
				io.sockets.emit("update-people", {people: people, count: sizePeople});
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			}
		}
		p = sockets.indexOf(socket.id);
		sockets.splice(p, 1);
	});

	//Room functions
	socket.on("createRoom", function(name) {
		if (people[socket.id].owns === null) {
			var id = uuid.v4();
			var room = new Room(name, id, socket.id);
			rooms[id] = room;
			sizeRooms = Object.size(rooms);
			io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			//add room to socket, and auto join the creator of the room
			socket.room = name;
			socket.join(socket.room);
			people[socket.id].owns = id;
			people[socket.id].inroom = id;
			room.addPerson(socket.id);
			socket.emit("update", "Welcome to " + room.name + ".");
			socket.emit("sendRoomID", {id: id});
		} else {
			io.sockets.emit("update", "You have already created a room.");
		}
	});

	socket.on("check", function(name, fn) {
		var keys = Object.keys(rooms);
		var match = false;
		if (keys.length != 0) {
			for (var i = 0; i<keys.length; i++) {
				if (rooms[keys[i]].name === name) {
					match = true;
					break;
				}
			}
		}
		fn({result: match});
	});

	socket.on("removeRoom", function(id) {
		var room = rooms[id];
		if (room) {
			if (socket.id === room.owner) { //only the owner can remove the room
				var personCount = room.people.length;
				if (personCount > 2) {
					console.log('There are still people in the room warning');
				}  else {
					if (socket.id === room.owner) {
						io.sockets.in(socket.room).emit("update", "The owner (" +people[socket.id].name + ") removed the room. and you have also been removed from it.");
						var i = 0;
						while(i < sockets.length) {
							if(sockets[i].id === room.people[i]) {
								people[sockets[i].id].inroom = null;
								sockets[i].leave(room.name);
							}
						    ++i;
						}
			    			delete rooms[id];
			    			people[room.owner].owns = null;
			    			sizeRooms = Object.size(rooms);
						io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
					}
				}
			} else {
				socket.emit("update", "Only the owner can remove a room.");
			}
		}
	});

	socket.on("joinRoom", function(id) {
		if (typeof people[socket.id] !== "undefined") {
			var room = rooms[id];
			if (socket.id === room.owner) {
				socket.emit("update", "You are the owner of this room and you have already been joined.");
			} else {
				room.people.contains(socket.id, function(found) {
				    if (found) {
				        socket.emit("update", "You have already joined this room.");
				    } else {
				    	if (people[socket.id].inroom !== null) {
				    		socket.emit("update", "You are already in a room ("+rooms[people[socket.id].inroom].name+"), please leave it first to join another room.");
				    	} else {
						room.addPerson(socket.id);
						people[socket.id].inroom = id;
						socket.room = room.name;
						socket.join(socket.room);
						user = people[socket.id];
						io.sockets.in(socket.room).emit("update", user.name + " has connected to " + room.name + " room.");
						socket.emit("update", "Welcome to " + room.name + ".");
						socket.emit("sendRoomID", {id: id});
					}
				    }
				});
			}
		} else {
			socket.emit("update", "Please enter a valid name first.");
		}
	});

	socket.on("leaveRoom", function(id) {
		var room = rooms[id];
		if (room) {
			if (socket.id === room.owner) {
				io.sockets.in(socket.room).emit("update", "The owner (" +people[socket.id].name + ") is leaving the room. The room is removed and you have been disconnected from it as well.");
				var i = 0;
				while(i < sockets.length) {
					if(sockets[i].id === room.people[i]) {
						people[sockets[i].id].inroom = null;
						sockets[i].leave(room.name);
					}
				    ++i;
				}
	    			delete rooms[id];
	    			people[room.owner].owns = null;
	    			sizeRooms = Object.size(rooms);
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			} else {
				//make sure that the socket is in fact part of this room
				room.people.contains(socket.id, function(found) {
				    if (found) {
				       var personIndex = room.people.indexOf(socket.id);
					room.people.splice(personIndex, 1);
					people[socket.id].inroom = null;
					io.sockets.emit("update", people[socket.id].name + " has left the room.");
					socket.leave(room.name);
				    }
				 });
			}
		}
	});
});
<commit_msg>server.js update and adding underscore.js<commit_after>var express = require('express');
var app = module.exports = express();
var server = require('http').createServer(app)
var io = require("socket.io").listen(server);
var uuid = require('node-uuid');
var Room = require('./room.js');

app.configure(function() {
	app.locals.pretty = true;
	  app.use(express.bodyParser());
	  app.use(express.methodOverride());
	  app.use(express.static(__dirname + '/public'));
	  app.use('/components', express.static(__dirname + '/components'));
	  app.use('/js', express.static(__dirname + '/js'));
	  app.set('views', __dirname + '/views');
	  app.engine('html', require('ejs').renderFile);
});

app.get('/', function(req, res) {
  res.render('index.html');
});

server.listen(3000, "192.168.56.101",  function(){
  console.log("Express server up and running.");
});

io.set("log level", 1);
var people = {};
var rooms = {};
var sockets = [];

Array.prototype.contains = function(k, callback) {
    var self = this;
    return (function check(i) {
        if (i >= self.length) {
            return callback(false);
        }
        if (self[i] === k) {
            return callback(true);
        }
        return process.nextTick(check.bind(null, i+1));
    }(0));
};

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return true;
}

io.sockets.on("connection", function (socket) {

	socket.on("joinserver", function(name) {
		ownerRoomID = inRoomID = null;
		people[socket.id] = {"name" : name, "owns" : ownerRoomID, "inroom": inRoomID};
		socket.emit("update", "You have connected to the server.");
		io.sockets.emit("update", people[socket.id].name + " is online.")
		sizePeople = Object.size(people);
		sizeRooms = Object.size(rooms);
		io.sockets.emit("update-people", {people: people, count: sizePeople});
		socket.emit("roomList", {rooms: rooms, count: sizeRooms});
		sockets.push(socket);
	});

	socket.on("send", function(msg) {
		var re = /^[w]:.*:/;
		var whisper = re.test(msg);
		var whisperStr = msg.split(":");
		var found = false;
		if (whisper) {
			var whisperTo = whisperStr[1];
			var keys = Object.keys(people);
			if (keys.length != 0) {
				for (var i = 0; i<keys.length; i++) {
					if (people[keys[i]].name === whisperTo) {
						var whisperId = keys[i];
						found = true;
						if (socket.id === whisperId) { //can't whisper to ourselves
							socket.emit("update", "You can't whisper to yourself.");
						}
						break;
					}
				}
			}
			if (found && socket.id !== whisperId) {
				var whisperTo = whisperStr[1];
				var whisperMsg = whisperStr[2];
				socket.emit("whisper", {name: "You"}, whisperMsg);
				io.sockets.socket(whisperId).emit("whisper", people[socket.id], whisperMsg);
			} else {
				socket.emit("update", "Can't find " + whisperTo);
			}
		} else {
			if (io.sockets.manager.roomClients[socket.id]['/'+socket.room] !== undefined ) {
				io.sockets.in(socket.room).emit("chat", people[socket.id], msg);
		    	} else {
				socket.emit("update", "Please connect to a room.");
		    	}
		}
	});

	socket.on("disconnect", function() {
		if (typeof people[socket.id] !== "undefined") {
			if (people[socket.id].inroom === null) {
				//io.sockets.emit("update", people[socket.id].name + " has left the server.");
				delete people[socket.id];
				sizePeople = Object.size(people);
				io.sockets.emit("update-people", {people: people, count: sizePeople});
			} else {
				if (people[socket.id].owns !== null) {
					var room= rooms[people[socket.id].owns];
					if (socket.id === room.owner) {
						io.sockets.in(socket.room).emit("update", "The owner (" +people[socket.id].name + ") has left the server. The room is removed and you have been disconnected from it as well.");
						var i = 0;
						while(i < sockets.length) {
							if (sockets[i].id === room.people[i]) {
								people[sockets[i].id].inroom = null;
								sockets[i].leave(room.name);
							}
					    		++i;
						}
						delete rooms[people[socket.id].owns];
					}
				}
				io.sockets.emit("update", people[socket.id].name + " has left the server.");
				delete people[socket.id];
				sizePeople = Object.size(people);
				sizeRooms = Object.size(rooms);
				io.sockets.emit("update-people", {people: people, count: sizePeople});
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			}
		}
		p = sockets.indexOf(socket.id);
		sockets.splice(p, 1);
	});

	//Room functions
	socket.on("createRoom", function(name) {
		if (people[socket.id].owns === null) {
			var id = uuid.v4();
			var room = new Room(name, id, socket.id);
			rooms[id] = room;
			sizeRooms = Object.size(rooms);
			io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			//add room to socket, and auto join the creator of the room
			socket.room = name;
			socket.join(socket.room);
			people[socket.id].owns = id;
			people[socket.id].inroom = id;
			room.addPerson(socket.id);
			socket.emit("update", "Welcome to " + room.name + ".");
			socket.emit("sendRoomID", {id: id});
		} else {
			io.sockets.emit("update", "You have already created a room.");
		}
	});

	socket.on("check", function(name, fn) {
		var keys = Object.keys(rooms);
		var match = false;
		if (keys.length != 0) {
			for (var i = 0; i<keys.length; i++) {
				if (rooms[keys[i]].name === name) {
					match = true;
					break;
				}
			}
		}
		fn({result: match});
	});

	socket.on("removeRoom", function(id) {
		var room = rooms[id];
		if (room) {
			if (socket.id === room.owner) { //only the owner can remove the room
				var personCount = room.people.length;
				if (personCount > 2) {
					console.log('There are still people in the room warning');
				}  else {
					if (socket.id === room.owner) {
						io.sockets.in(socket.room).emit("update", "The owner (" +people[socket.id].name + ") removed the room. and you have also been removed from it.");
						var i = 0;
						while(i < sockets.length) {
							if(sockets[i].id === room.people[i]) {
								people[sockets[i].id].inroom = null;
								sockets[i].leave(room.name);
							}
						    ++i;
						}
			    			delete rooms[id];
			    			people[room.owner].owns = null;
			    			sizeRooms = Object.size(rooms);
						io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
					}
				}
			} else {
				socket.emit("update", "Only the owner can remove a room.");
			}
		}
	});

	socket.on("joinRoom", function(id) {
		if (typeof people[socket.id] !== "undefined") {
			var room = rooms[id];
			if (socket.id === room.owner) {
				socket.emit("update", "You are the owner of this room and you have already been joined.");
			} else {
				room.people.contains(socket.id, function(found) {
				    if (found) {
				        socket.emit("update", "You have already joined this room.");
				    } else {
				    	if (people[socket.id].inroom !== null) {
				    		socket.emit("update", "You are already in a room ("+rooms[people[socket.id].inroom].name+"), please leave it first to join another room.");
				    	} else {
						room.addPerson(socket.id);
						people[socket.id].inroom = id;
						socket.room = room.name;
						socket.join(socket.room);
						user = people[socket.id];
						io.sockets.in(socket.room).emit("update", user.name + " has connected to " + room.name + " room.");
						socket.emit("update", "Welcome to " + room.name + ".");
						socket.emit("sendRoomID", {id: id});
					}
				    }
				});
			}
		} else {
			socket.emit("update", "Please enter a valid name first.");
		}
	});

	socket.on("leaveRoom", function(id) {
		var room = rooms[id];
		if (room) {
			if (socket.id === room.owner) {
				io.sockets.in(socket.room).emit("update", "The owner (" +people[socket.id].name + ") is leaving the room. The room is removed and you have been disconnected from it as well.");
				var i = 0;
				while(i < sockets.length) {
					if(sockets[i].id === room.people[i]) {
						people[sockets[i].id].inroom = null;
						sockets[i].leave(room.name);
					}
				    ++i;
				}
	    			delete rooms[id];
	    			people[room.owner].owns = null;
	    			sizeRooms = Object.size(rooms);
				io.sockets.emit("roomList", {rooms: rooms, count: sizeRooms});
			} else {
				//make sure that the socket is in fact part of this room
				room.people.contains(socket.id, function(found) {
				    if (found) {
				       var personIndex = room.people.indexOf(socket.id);
					room.people.splice(personIndex, 1);
					people[socket.id].inroom = null;
					io.sockets.emit("update", people[socket.id].name + " has left the room.");
					socket.leave(room.name);
				    }
				 });
			}
		}
	});
});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing err<commit_msg>Updated the readme again<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing erro<|endoftext|>


<commit_before>var NEIGHBOR_DISTANCE = 10;
var TURN_SENSITIVITY = 0.5;
var MAX_Y = 100;

var Boid = function(x, y, initialVelocity, initialHeading) {
  this.x = x;
  this.y = y;
  this.velocity = initialVelocity;
  this.heading = initialHeading;
}

Boid.prototype.step = function(dt) {
  this.x += dt * this.velocity * Math.cos(this.heading);
  this.y += dt * this.velocity * Math.sin(this.heading);
};

Boid.prototype.adjustHeading = function(flock, dt) {
  var neighborCount = 0;
  var neighborX = 0;
  var neighborY = 0;
  for(var i = 0; i < flock.length; i++) {
    var dx = this.x - flock[i].x;
    var dy = this.y - flock[i].y;

    if( (dx * dx + dy * dy) > NEIGHBOR_DISTANCE) {
      continue;
    }

    neighborX += dx;
    neighborY += dy;
  }

  var neighborHeading = Math.atan2(neighborY, neighborX);

  var timeSensitivity = TURN_SENSITIVITY * dt;
  this.heading = (1 - timeSensitivity) * this.heading + timeSensitivity * this.heading;

  if(this.y > MAX_Y) {
    this.heading = -MATH.PI / 2;
  }
};
<commit_msg>Stubbing out a flock class<commit_after>var NEIGHBOR_DISTANCE = 10;
var TURN_SENSITIVITY = 0.5;
var MAX_Y = 100;

var Boid = function(x, y, initialVelocity, initialHeading) {
  this.x = x;
  this.y = y;
  this.velocity = initialVelocity;
  this.heading = initialHeading;
}

Boid.prototype.step = function(dt) {
  this.x += dt * this.velocity * Math.cos(this.heading);
  this.y += dt * this.velocity * Math.sin(this.heading);
};

Boid.prototype.adjustHeading = function(flock, dt) {
  var neighborCount = 0;
  var neighborX = 0;
  var neighborY = 0;
  for(var i = 0; i < flock.length; i++) {
    var dx = this.x - flock[i].x;
    var dy = this.y - flock[i].y;

    if( (dx * dx + dy * dy) > NEIGHBOR_DISTANCE) {
      continue;
    }

    neighborX += dx;
    neighborY += dy;
  }

  var neighborHeading = Math.atan2(neighborY, neighborX);

  var timeSensitivity = TURN_SENSITIVITY * dt;
  this.heading = (1 - timeSensitivity) * this.heading + timeSensitivity * this.heading;

  if(this.y > MAX_Y) {
    this.heading = -MATH.PI / 2;
  }
};

var Flock = function(boidCount, xMin, xMax) {
  this.boids = [];
  for(var i = 0; i < boidCount; i++) {
    var x = Math.random() * (xMax - xMin) + xMax;
    var y = Math.random() * MAX_Y;
    var heading = Math.random() * Math.PI * 2;
    boids.push(new Boid(x, y, 10, heading));
  }
}

Flock.prototype.update = function(dt) {
  for(var i = 0; i < this.boids.length; i++) {
    this.boids[i].adjustHeading(this.boids, dt);
  }

  for(var i = 0; i < this.boids.length; i++) {
    this.boids[i].step(dt);
  }
};
<|endoftext|>


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

	Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");

	window.onLoad = function(){
		//query
		//list
		//destroyAll
	}

	$('#classroom-enter').click(function(){
		event.preventDefault();
		var request = $('#classroom-enter-form').val();
		console.log(request);
		var Classroom;
		var Classsearch = Parse.Object.extend("Classroom");
		var search = new Parse.Query(Classsearch);
		search.equalTo("code",request);
		search.find({
			success: function(results){
				if(results.length != 1) {
					console.log(results.length);
					console.log("YUFAILSOHARD!?");
				} else {
					console.log(results.length);
					console.log(results);
					console.log(results[0].attributes.code);
					console.log(results[0].id);
					console.log("YAAASSS!!!!\n");
					search.get(results[0].id, {
						success: function(results) {
							Classroom = results[0];
						}
					});
					console.log(Classroom);
				}
			},
			error: function(error){
				console.log("YUFAILSOHARD!?");
			}
		});
	});

	$('#post').click(function(){
		//Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");
		event.preventDefault();
		var Post = Parse.Object.extend("Post");
		var post = new Post();
		post.set("question","");
		post.set("upvotes", 0);
		post.set("downvotes", 0);
		post.set("answered", false);

		post.save(null, {
	  		success: function(Post) {
	    		// Execute any logic that should take place after the object is saved.
	    		//alert('New object created with objectId: ' + post.id);

	    		/*************************
				Rosemond's Code Goes Here!
	  			**************************/

	  		},
	  		error: function(Post, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  		}

		});

		var TestObject = Parse.Object.extend("TestObject");
		var testObject = new TestObject();
		testObject.save({foo: "bar"}).then(function(object) {
	  		//alert("yay! it worked");
		});
	});
});

<commit_msg>LOLWUT<commit_after>$(document).ready(function(){

	Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");

	window.onLoad = function(){
		//query
		//list
		//destroyAll
	}

	$('#classroom-enter').click(function(){
		event.preventDefault();
		var request = $('#classroom-enter-form').val();
		console.log(request);
		var Classroom;
		var Classsearch = Parse.Object.extend("Classroom");
		var search = new Parse.Query(Classsearch);
		search.equalTo("code",request);
		search.find({
			success: function(results){
				if(results.length != 1) {
					console.log(results.length);
					console.log("YUFAILSOHARD!?");
				} else {
					console.log(results.length);
					console.log(results);
					console.log(results[0]);
					console.log(results[0].attributes.code);
					console.log(results[0].id);
					console.log("YAAASSS!!!!\n");
					search.get(results[0].id, {
						success: function(results) {
							Classroom = results[0];
						}
					});
					console.log(results[0]);
					console.log(Classroom);
				}
			},
			error: function(error){
				console.log("YUFAILSOHARD!?");
			}
		});
	});

	$('#post').click(function(){
		//Parse.initialize("HnLswO6JpYmn4QrX2ClgADpA3HN2GFiVS1V95RP3", "IhuA6xPlWchDYpifcYQ39V18VAe9Dh44TgWBD2t1");
		event.preventDefault();
		var Post = Parse.Object.extend("Post");
		var post = new Post();
		post.set("question","");
		post.set("upvotes", 0);
		post.set("downvotes", 0);
		post.set("answered", false);

		post.save(null, {
	  		success: function(Post) {
	    		// Execute any logic that should take place after the object is saved.
	    		//alert('New object created with objectId: ' + post.id);

	    		/*************************
				Rosemond's Code Goes Here!
	  			**************************/

	  		},
	  		error: function(Post, error) {
	    		// Execute any logic that should take place if the save fails.
	    		// error is a Parse.Error with an error code and message.
	    		alert('Failed to create new object, with error code: ' + error.message);
	  		}

		});

		var TestObject = Parse.Object.extend("TestObject");
		var testObject = new TestObject();
		testObject.save({foo: "bar"}).then(function(object) {
	  		//alert("yay! it worked");
		});
	});
});

<|endoftext|>