<commit_before>// Design:
//
// * There are several regions in the game;
//   Sheep Stock,
//   Field,
//   Hand,
//   Deck,
//   Discard pile,
//   Exile.
// * A region contains a pile of cards.
// * A pile of cards is expressed as an array.
// * The first card in an array is corresponding to
//   the bottom card in a pile or the first card put into the pile.
// * The last card in an array is corresponding to
//   the top card in a pile or the last card put into the pile.

var shephy = {};

(function (S, $) {
  S.CARD_TYPE_SHEEP = 'Sheep';
  S.CARD_TYPE_EVENT = 'Event';

  function random(n) {
    return Math.floor(Math.random() * n);
  }

  function shuffle(xs) {
    for (var i = 0; i < xs.length; i++) {
      var j = random(xs.length - i);
      var tmp = xs[i];
      xs[i] = xs[j];
      xs[j] = tmp;
    }
  }

  S.delay = function(expressionAsFunction) {
    var result;
    var isEvaluated = false;

    return function () {
      if (!isEvaluated) {
        result = expressionAsFunction();
        isEvaluated = true;
      }
      return result;
    };
  };

  S.force = function (promise) {
    return promise();
  };

  S.clone = function (x) {
    return JSON.parse(JSON.stringify(x));
  };

  function makeSheepStockPile(n) {
    var cards = [];
    for (var i = 0; i < 7; i++) {
      cards.push({
        name: n + '',
        type: S.CARD_TYPE_SHEEP,
        rank: n
      });
    }
    return cards;
  }

  function makeEventCard(name) {
    // TODO: Implement effects when a card is played.
    return {
      name: name,
      type: S.CARD_TYPE_EVENT
    };
  }

  function makeInitalDeck() {
    var names = [
      'All-purpose Sheep',
      'Be Fruitful',
      'Be Fruitful',
      'Be Fruitful',
      'Crowding',
      'Dominion',
      'Dominion',
      'Falling Rock',
      'Fill the Earth',
      'Flourish',
      'Golden Hooves',
      'Inspirationi',
      'Lightning',
      'Meteor',
      'Multiply',
      'Plague',
      'Planning Sheep',
      'Sheep Dog',
      'Shephion',
      'Slump',
      'Storm',
      'Wolves'
    ];
    var cards = names.map(makeEventCard);
    shuffle(cards);
    return cards;
  }

  S.makeInitalWorld = function () {
    var sheepStock = {};
    [1, 3, 10, 30, 100, 300, 1000].forEach(function (n) {
      sheepStock[n] = makeSheepStockPile(n);
    });

    var initialSheepCard = sheepStock[1].pop();

    return {
      sheepStock: sheepStock,
      field: [initialSheepCard],
      enemySheepCount: 1,
      deck: makeInitalDeck(),
      hand: [],
      discardPile: [],
      exile: []
    };
  };

  S.gainX = function (world, rank) {
    if (world.sheepStock[rank].length == 0)
      return;
    if (7 - world.field.length <= 0)
      return;

    world.field.push(world.sheepStock[rank].pop());
  };

  S.releaseX = function (world, fieldIndex) {
    var c = world.field.splice(fieldIndex, 1)[0];
    world.sheepStock[c.rank].push(c);
  };

  S.discardX = function (world, handIndex) {
    var c = world.hand.splice(handIndex, 1)[0];
    world.discardPile.push(c);
  };

  S.exileX = function (world, region, index) {
    var c = region.splice(index, 1)[0];
    world.exile.push(c);
  };

  S.drawX = function (world) {
    if (world.deck.length == 0)
      return;
    if (5 - world.hand.length <= 0)
      return;

    world.hand.push(world.deck.pop());
  };

  S.remakeDeckX = function (world) {
    world.deck.push.apply(world.deck, world.discardPile);
    world.discardPile = [];
    shuffle(world.deck);
  };

  S.shouldDraw = function (world) {
    return world.hand.length < 5 && 0 < world.deck.length;
  };

  S.judgeGame = function (world) {
    if (world.field.some(function (c) {return c.rank == 1000;})) {
      return {
        state: 'win',
        description: 'You win!'
      };
    }
    if (world.enemySheepCount == 1000) {
      return {
        state: 'lose',
        description: 'Enemies reached 1000 sheep - you lose.'
      };
    }
    if (world.field.length == 0) {
      return {
        state: 'lose',
        description: 'You lost all your sheep - you lose.'
      };
    }

    throw 'Invalid operation';
  };

  S.makeGameTree = function (world, opt_state) {
    var x = S.makeWorld(world, opt_state);
    return {
      world: x[0],
      moves: S.listPossibleMoves(x[0], x[1])
    };
  };

  S.makeWorld = function (world, opt_state) {
    if (opt_state === undefined)
      return [world, opt_state];

    var state = opt_state;
    var sn;
    var wn = S.clone(world);

    if (state.step == 'play') {
      S.discardX(wn, state.handIndex);
      var eventName = world.hand[state.handIndex].name;
      switch (eventName) {
        case 'Multiply':
          S.gainX(wn, 3);
          break;
        default:
          throw 'Not implemented card - ' + eventName;
      }
    }

    // TODO: Make a new world based on state.

    return [wn, sn];
  };

  S.listPossibleMoves = function (world, opt_state) {
    if (opt_state === undefined)
      return S.listPossibleMovesForBasicRules(world);
    else
      return S.listPossibleMovesForPlayingCard(world, opt_state);
  }

  S.listPossibleMovesForBasicRules = function (world) {
    // TODO: Add an option to continue the current game to compete high score.
    if (world.field.some(function (c) {return c.rank == 1000;}))
      return [];

    if (1000 <= world.enemySheepCount)
      return [];

    if (world.field.length == 0)
      return [];

    if (world.hand.length == 0 && world.deck.length == 0) {
      return [
        {
          description: 'Remake Deck then fill Hand',
          gameTreePromise: S.delay(function () {
            var wn = S.clone(world);
            S.remakeDeckX(wn);
            while (S.shouldDraw(wn))
              S.drawX(wn);
            wn.enemySheepCount *= 10;
            return S.makeGameTree(wn);
          })
        }
      ];
    }

    if (S.shouldDraw(world)) {
      return [
        {
          description:
            5 - world.hand.length == 1
            ? 'Draw a card'
            : 'Draw cards',
          gameTreePromise: S.delay(function () {
            var wn = S.clone(world);
            while (S.shouldDraw(wn))
              S.drawX(wn);
            return S.makeGameTree(wn);
          })
        }
      ];
    }

    return world.hand.map(function (c, i) {
      return {
        description: 'Play ' + c.name,
        gameTreePromise: S.delay(function () {
          return S.makeGameTree(world, {step: 'play', handIndex: i});
        })
      };
    });
  };

  S.listPossibleMovesForPlayingCard = function (world, state) {
    // TODO: Implement more cards.
    throw 'Invalid operation: state = ' + JSON.stringify(state);
  };

  // UI  {{{1

  function textizeCards(cs) {
    if (cs.length == 0)
      return '-';
    else
      return cs.map(function (c) {return c.name;}).join(', ');
  }

  function nodizeMove(m) {
    var $m = $('<input>');
    $m.attr({
      type: 'button',
      value: m.description
    });
    $m.click(function () {
      drawState(S.force(m.gameTreePromise));
    });
    return $m;
  }

  function drawState(gameTree) {
    var w = gameTree.world;
    [1, 3, 10, 30, 100, 300, 1000].forEach(function (rank) {
      $('#sheepStock' + rank + ' > .count').text(w.sheepStock[rank].length);
    });
    $('#enemySheepCount > .count').text(w.enemySheepCount);
    $('#field > .cards').text(
      w.field
      .map(function (c) {return c.rank;})
      .join(', ')
    );
    $('#hand > .cards').text(textizeCards(w.hand));
    $('#deck > .count').text(w.deck.length);
    $('#discardPile > .cards').text(textizeCards(w.discardPile));
    $('#exile > .cards').text(textizeCards(w.exile));

    $('#message').text('Choose a move:');  // TODO: Update for no move.
    $('#moves').empty().append(gameTree.moves.map(nodizeMove));
  }

  //}}}1
})(shephy, jQuery);

// vim: expandtab softtabstop=2 shiftwidth=2 foldmethod=marker
<commit_msg>Fix to show a proper message at the end of a game<commit_after>// Design:
//
// * There are several regions in the game;
//   Sheep Stock,
//   Field,
//   Hand,
//   Deck,
//   Discard pile,
//   Exile.
// * A region contains a pile of cards.
// * A pile of cards is expressed as an array.
// * The first card in an array is corresponding to
//   the bottom card in a pile or the first card put into the pile.
// * The last card in an array is corresponding to
//   the top card in a pile or the last card put into the pile.

var shephy = {};

(function (S, $) {
  S.CARD_TYPE_SHEEP = 'Sheep';
  S.CARD_TYPE_EVENT = 'Event';

  function random(n) {
    return Math.floor(Math.random() * n);
  }

  function shuffle(xs) {
    for (var i = 0; i < xs.length; i++) {
      var j = random(xs.length - i);
      var tmp = xs[i];
      xs[i] = xs[j];
      xs[j] = tmp;
    }
  }

  S.delay = function(expressionAsFunction) {
    var result;
    var isEvaluated = false;

    return function () {
      if (!isEvaluated) {
        result = expressionAsFunction();
        isEvaluated = true;
      }
      return result;
    };
  };

  S.force = function (promise) {
    return promise();
  };

  S.clone = function (x) {
    return JSON.parse(JSON.stringify(x));
  };

  function makeSheepStockPile(n) {
    var cards = [];
    for (var i = 0; i < 7; i++) {
      cards.push({
        name: n + '',
        type: S.CARD_TYPE_SHEEP,
        rank: n
      });
    }
    return cards;
  }

  function makeEventCard(name) {
    // TODO: Implement effects when a card is played.
    return {
      name: name,
      type: S.CARD_TYPE_EVENT
    };
  }

  function makeInitalDeck() {
    var names = [
      'All-purpose Sheep',
      'Be Fruitful',
      'Be Fruitful',
      'Be Fruitful',
      'Crowding',
      'Dominion',
      'Dominion',
      'Falling Rock',
      'Fill the Earth',
      'Flourish',
      'Golden Hooves',
      'Inspirationi',
      'Lightning',
      'Meteor',
      'Multiply',
      'Plague',
      'Planning Sheep',
      'Sheep Dog',
      'Shephion',
      'Slump',
      'Storm',
      'Wolves'
    ];
    var cards = names.map(makeEventCard);
    shuffle(cards);
    return cards;
  }

  S.makeInitalWorld = function () {
    var sheepStock = {};
    [1, 3, 10, 30, 100, 300, 1000].forEach(function (n) {
      sheepStock[n] = makeSheepStockPile(n);
    });

    var initialSheepCard = sheepStock[1].pop();

    return {
      sheepStock: sheepStock,
      field: [initialSheepCard],
      enemySheepCount: 1,
      deck: makeInitalDeck(),
      hand: [],
      discardPile: [],
      exile: []
    };
  };

  S.gainX = function (world, rank) {
    if (world.sheepStock[rank].length == 0)
      return;
    if (7 - world.field.length <= 0)
      return;

    world.field.push(world.sheepStock[rank].pop());
  };

  S.releaseX = function (world, fieldIndex) {
    var c = world.field.splice(fieldIndex, 1)[0];
    world.sheepStock[c.rank].push(c);
  };

  S.discardX = function (world, handIndex) {
    var c = world.hand.splice(handIndex, 1)[0];
    world.discardPile.push(c);
  };

  S.exileX = function (world, region, index) {
    var c = region.splice(index, 1)[0];
    world.exile.push(c);
  };

  S.drawX = function (world) {
    if (world.deck.length == 0)
      return;
    if (5 - world.hand.length <= 0)
      return;

    world.hand.push(world.deck.pop());
  };

  S.remakeDeckX = function (world) {
    world.deck.push.apply(world.deck, world.discardPile);
    world.discardPile = [];
    shuffle(world.deck);
  };

  S.shouldDraw = function (world) {
    return world.hand.length < 5 && 0 < world.deck.length;
  };

  S.judgeGame = function (world) {
    if (world.field.some(function (c) {return c.rank == 1000;})) {
      return {
        state: 'win',
        description: 'You win!'
      };
    }
    if (world.enemySheepCount == 1000) {
      return {
        state: 'lose',
        description: 'Enemies reached 1000 sheep - you lose.'
      };
    }
    if (world.field.length == 0) {
      return {
        state: 'lose',
        description: 'You lost all your sheep - you lose.'
      };
    }

    throw 'Invalid operation';
  };

  S.makeGameTree = function (world, opt_state) {
    var x = S.makeWorld(world, opt_state);
    return {
      world: x[0],
      moves: S.listPossibleMoves(x[0], x[1])
    };
  };

  S.makeWorld = function (world, opt_state) {
    if (opt_state === undefined)
      return [world, opt_state];

    var state = opt_state;
    var sn;
    var wn = S.clone(world);

    if (state.step == 'play') {
      S.discardX(wn, state.handIndex);
      var eventName = world.hand[state.handIndex].name;
      switch (eventName) {
        case 'Multiply':
          S.gainX(wn, 3);
          break;
        default:
          throw 'Not implemented card - ' + eventName;
      }
    }

    // TODO: Make a new world based on state.

    return [wn, sn];
  };

  S.listPossibleMoves = function (world, opt_state) {
    if (opt_state === undefined)
      return S.listPossibleMovesForBasicRules(world);
    else
      return S.listPossibleMovesForPlayingCard(world, opt_state);
  }

  S.listPossibleMovesForBasicRules = function (world) {
    // TODO: Add an option to continue the current game to compete high score.
    if (world.field.some(function (c) {return c.rank == 1000;}))
      return [];

    if (1000 <= world.enemySheepCount)
      return [];

    if (world.field.length == 0)
      return [];

    if (world.hand.length == 0 && world.deck.length == 0) {
      return [
        {
          description: 'Remake Deck then fill Hand',
          gameTreePromise: S.delay(function () {
            var wn = S.clone(world);
            S.remakeDeckX(wn);
            while (S.shouldDraw(wn))
              S.drawX(wn);
            wn.enemySheepCount *= 10;
            return S.makeGameTree(wn);
          })
        }
      ];
    }

    if (S.shouldDraw(world)) {
      return [
        {
          description:
            5 - world.hand.length == 1
            ? 'Draw a card'
            : 'Draw cards',
          gameTreePromise: S.delay(function () {
            var wn = S.clone(world);
            while (S.shouldDraw(wn))
              S.drawX(wn);
            return S.makeGameTree(wn);
          })
        }
      ];
    }

    return world.hand.map(function (c, i) {
      return {
        description: 'Play ' + c.name,
        gameTreePromise: S.delay(function () {
          return S.makeGameTree(world, {step: 'play', handIndex: i});
        })
      };
    });
  };

  S.listPossibleMovesForPlayingCard = function (world, state) {
    // TODO: Implement more cards.
    throw 'Invalid operation: state = ' + JSON.stringify(state);
  };

  // UI  {{{1

  function textizeCards(cs) {
    if (cs.length == 0)
      return '-';
    else
      return cs.map(function (c) {return c.name;}).join(', ');
  }

  function nodizeMove(m) {
    var $m = $('<input>');
    $m.attr({
      type: 'button',
      value: m.description
    });
    $m.click(function () {
      drawState(S.force(m.gameTreePromise));
    });
    return $m;
  }

  function drawState(gameTree) {
    var w = gameTree.world;
    [1, 3, 10, 30, 100, 300, 1000].forEach(function (rank) {
      $('#sheepStock' + rank + ' > .count').text(w.sheepStock[rank].length);
    });
    $('#enemySheepCount > .count').text(w.enemySheepCount);
    $('#field > .cards').text(
      w.field
      .map(function (c) {return c.rank;})
      .join(', ')
    );
    $('#hand > .cards').text(textizeCards(w.hand));
    $('#deck > .count').text(w.deck.length);
    $('#discardPile > .cards').text(textizeCards(w.discardPile));
    $('#exile > .cards').text(textizeCards(w.exile));

    $('#message').text(
      gameTree.moves.length == 0
      ? S.judgeGame(gameTree.world).description
      : 'Choose a move:'
    );
    $('#moves').empty().append(gameTree.moves.map(nodizeMove));
  }

  //}}}1
})(shephy, jQuery);

// vim: expandtab softtabstop=2 shiftwidth=2 foldmethod=marker
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var hb = require('express3-handlebars');

app.engine('hbs', hb({extname:'hbs',defaultLayout:"main.hbs"}));
app.set('view engine', 'hbs');

app.get('/', function(req, res){
  res.render('index',{greeting:randElement(greetings),title:req.url});
});

app.listen(3000);

var greetings = ["Hello","こんにちは","夜露死苦"]

function randElement(ary) {
        return ary[Math.floor(Math.random() * ary.length)];
    }
<commit_msg>adding node-static to depend<commit_after>var express = require('express');
var app = express();
var hb = require('express3-handlebars');
var http = require("http");

app.engine('hbs', hb({extname:'hbs',defaultLayout:"main.hbs"}));
app.set('view engine', 'hbs');

app.get('/', function(req, res){
  res.render('index',{greeting:randElement(greetings),title:req.url});
});

app.listen(3000);

//static server
var file = new require('node-static').Server('./public');

http.createServer(function (request, response) {
    request.addListener('end', function () {
        file.serve(request, response);
    }).resume();
}).listen(3000);

var greetings = ["Hello","こんにちは","夜露死苦"]

function randElement(ary) {
        return ary[Math.floor(Math.random() * ary.length)];
    }
<|endoftext|>


<commit_before>"use strict";

var fs = require("fs");
var nopt = require("nopt");
var path = require("path");
var jsdocFlow = require("./index");

var opts = nopt({
    "file": path
}, {
    "f": "--file"
});

if (!opts.file) {
	console.log("Usage: node app.js -f path/to/file.js");
	process.exit(1);
	return;
}

console.log(
	jsdocFlow(fs.readFileSync(opts.file, "utf8"))
);<commit_msg>s/tabs/spaces/<commit_after>"use strict";

var fs = require("fs");
var nopt = require("nopt");
var path = require("path");
var jsdocFlow = require("./index");

var opts = nopt({
    "file": path
}, {
    "f": "--file"
});

if (!opts.file) {
    console.log("Usage: node app.js -f path/to/file.js");
    process.exit(1);
    return;
}

console.log(
    jsdocFlow(fs.readFileSync(opts.file, "utf8"))
);<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

app.post('/hook', function (req, res){

	var now = new Date();

	var fs = require('fs');
fs.writeFile("test.txt", "Hey there!" + now.getDate(), function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
});

res.send(200);

});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>changed output format<commit_after>
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

app.post('/hook', function (req, res){

	var now = new Date();

	var fs = require('fs');
fs.writeFile("git.txt", "There was a push to remote repo at " + now.getTime(), function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved!");
    }
});

res.send(200);

});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<|endoftext|>


<commit_before>window.onload = linkAudio;
var mouseDownEvent;
var vibranceMode = false;
var strobeMode = true;
var inverseMode = false;
var colourShift = true;
var increment = true;
var pulseSpacing = 20;
var pulse = 1;
var pulseMode = false;
var visualizerElement;
var foregroundElement;
var settingsFXElement;
var audioTag;
var sredHex = "05";
var sgrnHex = "10";
var sbluHex = "15";
var oredHex = "33";
var ogrnHex = "aa";
var obluHex = "ff";
var audioData;
var audioDataBackup;
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var source1;
var source2;
var gainNode;
var analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
var HEIGHT;
var WIDTH;
var barHeight = 2;
var barWidth = 5;
var barSpacing = 1;
var bleed = 10;
var fgColour = "33aaff";
var bgColour = "051015";
var barSize = 55;
var activeBufferLength = bufferLength / 0.666;
var radio = getUrlVars()["src"];
analyser.getByteTimeDomainData(dataArray);
var fps;
var lastFrame = new Date();
var lastFrameFrame = lastFrame;
var title;

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
    // From http://papermashup.com/read-url-get-variables-withjavascript/
}

function checkUrl(){
    if(radio){
        document.querySelector("source").setAttribute("src",radio);
        document.getElementById("Stream").load();
        document.getElementById("Stream").play();
        var split = radio.split(".com")[0].split(".");
        radioName = split[split.length-1];
        radioName = radioName[0].toUpperCase() + radioName.slice(1);
    }
}

function init(){
  checkUrl();
    HEIGHT = window.innerHeight;
    WIDTH = window.innerWidth;
  canvas.height = HEIGHT;
  canvas.width = WIDTH;
    for(var i = 0; i < WIDTH / 55; i++){
        $("#bars").append("

");
        $("#bars-blur").append("

");
    }
  visualizerElement = document.getElementById("visualizer");
  foregroundElement = document.getElementById("foreground");
  settingsFXElement = document.getElementById("settings-fx-wrapper");
  visualizerElement.setAttribute("style","background:#"+bgColour);
  sredHex = parseInt(bgColour[0]+bgColour[1], 16);
  sgrnHex = parseInt(bgColour[2]+bgColour[3], 16);
  sbluHex = parseInt(bgColour[4]+bgColour[5], 16);
  oredHex = parseInt(fgColour[0]+fgColour[1], 16);
  ogrnHex = parseInt(fgColour[2]+fgColour[3], 16);
  obluHex = parseInt(fgColour[4]+fgColour[5], 16);
  setVol(0.5);
  anim();
}

function GetInfo(){
  var element = document.getElementById("Stream");
}

$(window).resize(function(){
    HEIGHT = window.innerHeight;
    WIDTH = window.innerWidth;
  canvas.height = HEIGHT;
  canvas.width = WIDTH;
});

function SettingsToggle(){
  if(document.getElementById("settings").style.left === "-230px" || !document.getElementById("settings").style.left){
    document.getElementById("settings").style.left = "0px";
    document.getElementById("settings-toggle").style.margin = "0px";
    document.getElementById("settings-toggle").innerHTML = "<";
  }else{
    document.getElementById("settings").style.left = "-230px";
    document.getElementById("settings-toggle").style.margin = "0px -60px 0px 0px";
    document.getElementById("settings-toggle").innerHTML = ">";
  }
}

function NewSource(){
  radio = document.getElementById("srInput").value;
 document.querySelector("source").setAttribute("src",radio);
  document.getElementById("Stream").load();
  document.getElementById("Stream").play();
  window.history.pushState("Radio Visualizer","Canvas Web Audio API Music Visualizer",window.location.href.split("?")[0] + "?src=" + radio);
  var split = radio.split(".com")[0].split(".");
  radioName = split[split.length-1];
  radioName = radioName[0].toUpperCase() + radioName.slice(1);
}

function NewBGColour(){
  var input = document.getElementById("bgInput").value;
  input = input.replace("#","");
  if(input.length === 6){
    bgColour = input;
    $("svg").css({"fill":"#" + bgColour, "stroke":"#"+fgColour});
    visualizerElement.setAttribute("style","background:#"+bgColour);
  }
  else if(parseInt(input) !== "NaN" && input.legnth < 4){
    bgColour = parseInt(input,16).toString(16);
    $("svg").css({"fill":"#" + bgColour, "stroke":"#"+fgColour});
    visualizerElement.setAttribute("style","background:#"+bgColour);
  }
  else{
    alert("Please enter decimal or hex code");
  }
  oredHex = parseInt(fgColour[0]+fgColour[1], 16);
  ogrnHex = parseInt(fgColour[2]+fgColour[3], 16);
  obluHex = parseInt(fgColour[4]+fgColour[5], 16);
}

function NewFGColour(){
  var input = document.getElementById("fgInput").value;
  input = input.replace("#","");
  if(input.length === 6){
    fgColour = input;
    if(parseInt(fgColour[0]) < 1 && parseInt(fgColour[2]) < 1 && parseInt(fgColour[4]) < 1){
      document.body.style.color = "#ffffff";
      $('input').css('color','#ffffff');
    }else{
      document.body.style.color = "#"+fgColour;
      $('input').css('color','#'+fgColour);
      $("#current-volume").css({"fill":"#" + bgColour});
    }
  }
  else if(parseInt(input) !== "NaN" && input.legnth < 4){
    fgColour = parseInt(input,16).toString(16);
    document.body.style.color = "#"+fgColour;
    $('input').css('color','#'+fgColour);
  }
  else{
    alert("Please enter decimal or hex code");
  }
  sredHex = parseInt(bgColour[0]+bgColour[1], 16);
  sgrnHex = parseInt(bgColour[2]+bgColour[3], 16);
  sbluHex = parseInt(bgColour[4]+bgColour[5], 16);
}

function NewBleedQuality(){
  bleed = parseInt(document.getElementById("bqInput").value);
}

function NewBarHeight(){
  barHeight = 2 - document.getElementById("bhInput").value;
}

function NewBarWidth(){
  barWidth = parseInt(document.getElementById("bwInput").value);
}

function NewBarSpacing(){
  barSpacing = parseInt(document.getElementById("bsInput").value);
}

function anim(){
  pulse = 1;
  drawVisual = requestAnimationFrame(anim);
  analyser.getByteFrequencyData(dataArray);
  var mean = 0;
  canvasCtx.fillStyle = "#3af";
  canvasCtx.clearRect( 0 , 0 , WIDTH, HEIGHT );
    for(var i = 0; i < bufferLength * 0.666; i++) {
    var v = dataArray[i] / 128.0;
    var h = v * HEIGHT/2;
    mean += h;
    var sred = sredHex;
    var sgrn = sgrnHex;
    var sblu = sbluHex;
    var ored = oredHex;
    var ogrn = ogrnHex;
    var oblu = obluHex;
    var tred  = ored / 2;
    var tgrn  = ogrn / 2;
    var tblu  = oblu / 2;
    var amp = 0;
    var loud = Math.abs(dataArray[i]);
    var cred = sred;
    var cgrn = sgrn;
    var cblu = sblu;
    if(pulseMode === true){
            opacity = (1 / pulseSpacing) * pulse;
    }else{
      opacity = 1;
    }

    if(loud > amp) {
      amp = loud;
    }
    if(vibranceMode === true){
      document.body.setAttribute("style","-webkit-filter:brightness(" + (amp/256 + 1) + ")");
    }else{
      document.body.removeAttribute("style");
    }
    var redinc = Math.floor((tred - sred) / bleed);
    var grninc = Math.floor((tgrn - sgrn) / bleed);
    var bluinc = Math.floor((tblu - sblu) / bleed);

    for(var o = 0; o < bleed;o++){
      if(o < bleed - 1){
        //--TODO-- Check for outerbars mode
        cred += redinc;
        cgrn += grninc;
        cblu += bluinc;

        red = cred;
        green = cgrn;
        blue = cblu;
        canvasCtx.fillStyle = "rgba(" + red + "," + green + "," + blue + "," + opacity + ")";
        canvasCtx.fillRect(i * (barWidth + barSpacing), HEIGHT/2 - ((2-(o/bleed))*h/(2*barHeight)), barWidth, (((2-(o/bleed))*h)/barHeight));
      }else{
        red = ored;
        green = ogrn;
        blue = oblu;
        canvasCtx.fillStyle = "rgba(" + red + "," + green + "," + blue + "," + opacity + ")";
        canvasCtx.fillRect(i * (barWidth + barSpacing), HEIGHT/2 - h/(barHeight * 2), barWidth, h/barHeight);
      }
    }
    if(increment === true){
      pulse++;
    }
    else{
      pulse--;
    }
    if(pulse > pulseSpacing -1){
      increment = false;
    }else if(pulse < 1){
      increment = true;
    }
      mean = 0;
    }
  var total = Math.floor(audioTag.currentTime);
  var seconds = Math.floor(total % 60).toString();
  var minutes = Math.floor(total/60 % 60).toString();
  var hours = Math.floor(total/3600).toString();
  var ouput;
  if(hours.length === 1){
    hours = "0" + hours;
  }
  if(minutes.length === 1){
    minutes = "0" + minutes;
  }
  if(seconds.length === 1){
    seconds = "0" + seconds;
  }
  canvasCtx.strokeStyle = "#"+fgColour;
  canvasCtx.lineWidth = 3;
  canvasCtx.font = "30px Play";
  canvasCtx.strokeText(hours + ":" + minutes + ":" + seconds,10,HEIGHT/2+30);
  canvasCtx.font = "60px Play";
  canvasCtx.strokeText(radioName,10,HEIGHT/2);
  canvasCtx.fillStyle = "#"+bgColour;
  canvasCtx.font = "30px Play";
  canvasCtx.fillText(hours + ":" + minutes + ":" + seconds,10,HEIGHT/2+30);
  canvasCtx.font = "60px Play";
  canvasCtx.fillText(radioName,10,HEIGHT/2);

  var now = new Date();
  if(now - lastFrameFrame > 100){
    fps = Math.floor(1000 / (now - lastFrame));
    lastFrameFrame = now;
  }
  canvasCtx.font = "30px Play";
  canvasCtx.strokeStyle = "#"+fgColour;
  canvasCtx.strokeText(title,WIDTH/2 - 100,HEIGHT/2 + 10);
  canvasCtx.fillText(title,WIDTH/2 - 100,HEIGHT/2 + 10);
  lastFrame = now;
}

function linkAudio(){
    gainNode = audioCtx.createGain();
    analyser.connect(gainNode);
    gainNode.connect(audioCtx.destination);
    canvas = document.getElementById("visualizer");
    audioTag = document.querySelector('audio');
    canvasCtx = canvas.getContext("2d");
    source1 = audioCtx.createMediaElementSource(audioTag);
    source1.connect(analyser);
    init();
}

function start(){
    document.getElementById("Stream").play();
}

function pause(){
    document.getElementById("Stream").pause();
}

$('#volume-bar').mousedown(function () {
    setVol($('#volume-bar').val());
    mouseDownEvent = setInterval(function () {
        setVol($('#volume-bar').val());
    }, 100);
});
$('#volume-bar').mouseup(function () {
    clearInterval(mouseDownEvent);
});
$('#volume-bar').mouseout(function () {
    clearInterval(mouseDownEvent);
});

function setVol(value){
  gainNode.gain.value = value;
  document.getElementById("current-volume").style.width = (119 * value) + "px";
}

$(".filter-toggle").click(function(){
  firstChild = this.children[0];
  secondChild = this.children[1];

  if(firstChild.hasAttribute("style")){
    firstChild.removeAttribute("style");
    secondChild.setAttribute("style","opacity:0.2;");
  }else{
    firstChild.setAttribute("style","opacity:0.2;");
    secondChild.removeAttribute("style");
  }
});

function toggleFX(string){
  if(string === "vibrance"){
    vibranceMode = !vibranceMode;
  }else if(string === "strobe"){
    strobeMode = !strobeMode;
  }else if(string === "inverse"){
    inverseMode = !inverseMode;
  }else if(string === "colourShift"){
    if(!colourShift){
      colourShift = setInterval(function(){$("#body-fx-wrapper").css("-webkit-filter", "hue-rotate("+(Math.random() * 360)+"deg)");},1000);
    }else{
      clearInterval(colourShift);
      colourShift = false;
    }
  }else if(string === "pulse"){
    pulseMode = !pulseMode;
  }
}

(function worker() {
  $.ajax({
    url: 'fetcher.php?host='+host,
    success: function(data) {
      title = data;
      document.title = data;
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 3000);
    }
  });
})();<commit_msg>Clean some code<commit_after>window.onload = linkAudio;
var mouseDownEvent;
var vibranceMode = false;
var strobeMode = true;
var inverseMode = false;
var colourShift = true;
var increment = true;
var pulseSpacing = 20;
var pulse = 1;
var pulseMode = false;
var visualizerElement;
var foregroundElement;
var settingsFXElement;
var audioTag;
var sredHex = "05";
var sgrnHex = "10";
var sbluHex = "15";
var oredHex = "33";
var ogrnHex = "aa";
var obluHex = "ff";
var audioData;
var audioDataBackup;
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var source1;
var source2;
var gainNode;
var analyser = audioCtx.createAnalyser();
analyser.fftSize = 2048;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);
var HEIGHT;
var WIDTH;
var barHeight = 2;
var barWidth = 5;
var barSpacing = 1;
var bleed = 10;
var fgColour = "33aaff";
var bgColour = "051015";
var barSize = 55;
var activeBufferLength = bufferLength / 0.666;
var radio = getUrlVars()["src"];
analyser.getByteTimeDomainData(dataArray);
var fps;
var lastFrame = new Date();
var lastFrameFrame = lastFrame;
var title;

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
    // From http://papermashup.com/read-url-get-variables-withjavascript/
}

function checkUrl() {
    if(radio){
        document.querySelector("source").setAttribute("src",radio);
        document.getElementById("Stream").load();
        document.getElementById("Stream").play();
        var split = radio.split(".com")[0].split(".");
        radioName = split[split.length-1];
        radioName = radioName[0].toUpperCase() + radioName.slice(1);
    }
}

function init() {
    checkUrl();
    HEIGHT = window.innerHeight;
    WIDTH = window.innerWidth;
    canvas.height = HEIGHT;
    canvas.width = WIDTH;
    for(var i = 0; i < WIDTH / 55; i++) {
        $("#bars").append("

");
        $("#bars-blur").append("

");
    }
    visualizerElement = document.getElementById("visualizer");
    foregroundElement = document.getElementById("foreground");
    settingsFXElement = document.getElementById("settings-fx-wrapper");
    visualizerElement.setAttribute("style","background:#"+bgColour);
    sredHex = parseInt(bgColour[0]+bgColour[1], 16);
    sgrnHex = parseInt(bgColour[2]+bgColour[3], 16);
    sbluHex = parseInt(bgColour[4]+bgColour[5], 16);
    oredHex = parseInt(fgColour[0]+fgColour[1], 16);
    ogrnHex = parseInt(fgColour[2]+fgColour[3], 16);
    obluHex = parseInt(fgColour[4]+fgColour[5], 16);
    setVol(0.5);
    anim();
}

function GetInfo() {
    var element = document.getElementById("Stream");
}

$(window).resize(function() {
    HEIGHT = window.innerHeight;
    WIDTH = window.innerWidth;
    canvas.height = HEIGHT;
    canvas.width = WIDTH;
});

function SettingsToggle() {
    if(document.getElementById("settings").style.left === "-230px" || !document.getElementById("settings").style.left) {
        document.getElementById("settings").style.left = "0px";
        document.getElementById("settings-toggle").style.margin = "0px";
        document.getElementById("settings-toggle").innerHTML = "<";
    } else {
        document.getElementById("settings").style.left = "-230px";
        document.getElementById("settings-toggle").style.margin = "0px -60px 0px 0px";
        document.getElementById("settings-toggle").innerHTML = ">";
    }
}

function NewSource() {
    radio = document.getElementById("srInput").value;
    document.querySelector("source").setAttribute("src", radio);
    document.getElementById("Stream").load();
    document.getElementById("Stream").play();
    window.history.pushState("Radio Visualizer", "Canvas Web Audio API Music Visualizer", window.location.href.split("?")[0] + "?src=" + radio);
    var split = radio.split(".com")[0].split(".");
    radioName = split[split.length - 1];
    radioName = radioName[0].toUpperCase() + radioName.slice(1);
}

function NewBGColour() {
    var input = document.getElementById("bgInput").value;
    input = input.replace("#", "");
    if(input.length === 6 ){
        bgColour = input;
        $("svg").css({
            "fill": "#" + bgColour,
            "stroke": "#" + fgColour
        });

        visualizerElement.setAttribute("style", "background:#" + bgColour);
    }
    else if (parseInt(input) !== "NaN" && input.legnth < 4) {
        bgColour = parseInt(input, 16).toString(16);
        $("svg").css({
            "fill": "#" + bgColour,
            "stroke": "#" + fgColour
        });
        visualizerElement.setAttribute("style", "background:#" + bgColour);
    }
    else{
        alert("Please enter decimal or hex code");
    }
    oredHex = parseInt(fgColour[0] + fgColour[1], 16);
    ogrnHex = parseInt(fgColour[2] + fgColour[3], 16);
    obluHex = parseInt(fgColour[4] + fgColour[5], 16);
}

function NewFGColour() {
    var input = document.getElementById("fgInput").value;
    input = input.replace("#", "");
    if(input.length === 6) {
        fgColour = input;
        if(parseInt(fgColour[0]) < 1 && parseInt(fgColour[2]) < 1 && parseInt(fgColour[4]) < 1){
            document.body.style.color = "#ffffff";
            $('input').css('color', '#ffffff');
        } else {
            document.body.style.color = "#" + fgColour;
            $('input').css('color','#' + fgColour);
            $("#current-volume").css({
                "fill": "#" + bgColour
            });
        }
    } else if (parseInt(input) !== "NaN" && input.legnth < 4) {
        fgColour = parseInt(input, 16).toString(16);
        document.body.style.color = "#" + fgColour;
        $('input').css('color','#' + fgColour);
    } else {
        alert("Please enter decimal or hex code");
    }

    sredHex = parseInt(bgColour[0]+bgColour[1], 16);
    sgrnHex = parseInt(bgColour[2]+bgColour[3], 16);
    sbluHex = parseInt(bgColour[4]+bgColour[5], 16);
}

function NewBleedQuality() {
    bleed = parseInt(document.getElementById("bqInput").value);
}

function NewBarHeight() {
    barHeight = 2 - document.getElementById("bhInput").value;
}

function NewBarWidth() {
    barWidth = parseInt(document.getElementById("bwInput").value);
}

function NewBarSpacing() {
    barSpacing = parseInt(document.getElementById("bsInput").value);
}

function anim() {
    pulse = 1;
    drawVisual = requestAnimationFrame(anim);
    analyser.getByteFrequencyData(dataArray);
    var mean = 0;
    canvasCtx.fillStyle = "#3af";
    canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
    for (var i = 0; i < bufferLength * 0.666; i++) {
        var v = dataArray[i] / 128.0;
        var h = v * HEIGHT/2;
        mean += h;
        var sred = sredHex;
        var sgrn = sgrnHex;
        var sblu = sbluHex;
        var ored = oredHex;
        var ogrn = ogrnHex;
        var oblu = obluHex;
        var tred  = ored / 2;
        var tgrn  = ogrn / 2;
        var tblu  = oblu / 2;
        var amp = 0;
        var loud = Math.abs(dataArray[i]);
        var cred = sred;
        var cgrn = sgrn;
        var cblu = sblu;

        if (pulseMode === true) {
            opacity = (1 / pulseSpacing) * pulse;
        } else {
            opacity = 1;
        }

        if (loud > amp) {
          amp = loud;
        }
        if (vibranceMode === true) {
            document.body.setAttribute("style", "-webkit-filter:brightness(" + (amp/256 + 1) + ")");
        } else {
            document.body.removeAttribute("style");
        }

        var redinc = Math.floor((tred - sred) / bleed);
        var grninc = Math.floor((tgrn - sgrn) / bleed);
        var bluinc = Math.floor((tblu - sblu) / bleed);

        for (var o = 0; o < bleed; o++) {
            if (o < bleed - 1) {
                cred += redinc;
                cgrn += grninc;
                cblu += bluinc;

                red = cred;
                green = cgrn;
                blue = cblu;
                canvasCtx.fillStyle = "rgba(" + red + "," + green + "," + blue + "," + opacity + ")";
                canvasCtx.fillRect(i * (barWidth + barSpacing), HEIGHT/2 - ((2-(o/bleed))*h/(2*barHeight)), barWidth, (((2-(o/bleed))*h)/barHeight));
            } else {
                red = ored;
                green = ogrn;
                blue = oblu;
                canvasCtx.fillStyle = "rgba(" + red + "," + green + "," + blue + "," + opacity + ")";
                canvasCtx.fillRect(i * (barWidth + barSpacing), HEIGHT/2 - h/(barHeight * 2), barWidth, h/barHeight);
            }
        }

        if (increment === true) {
            pulse++;
        } else {
            pulse--;
        }

        if (pulse > pulseSpacing -1) {
            increment = false;
        } else if (pulse < 1) {
            increment = true;
        }
        mean = 0;
    }

    var total = Math.floor(audioTag.currentTime);
    var seconds = Math.floor(total % 60).toString();
    var minutes = Math.floor(total/60 % 60).toString();
    var hours = Math.floor(total / 3600).toString();
    var ouput;

    if (hours.length === 1) {
        hours = "0" + hours;
    }
    if (minutes.length === 1) {
        minutes = "0" + minutes;
    }

    if (seconds.length === 1) {
        seconds = "0" + seconds;
    }

    canvasCtx.strokeStyle = "#" + fgColour;
    canvasCtx.lineWidth = 3;
    canvasCtx.font = "30px Play";
    canvasCtx.strokeText(hours + ":" + minutes + ":" + seconds, 10, HEIGHT / 2 + 30);
    canvasCtx.font = "60px Play";
    canvasCtx.strokeText(radioName,10,HEIGHT/2);
    canvasCtx.fillStyle = "#"+bgColour;
    canvasCtx.font = "30px Play";
    canvasCtx.fillText(hours + ":" + minutes + ":" + seconds, 10, HEIGHT / 2 + 30);
    canvasCtx.font = "60px Play";
    canvasCtx.fillText(radioName, 10, HEIGHT / 2);

    var now = new Date();
    if (now - lastFrameFrame > 100) {
        fps = Math.floor(1000 / (now - lastFrame));
        lastFrameFrame = now;
    }
    canvasCtx.font = "30px Play";
    canvasCtx.strokeStyle = "#" + fgColour;
    canvasCtx.strokeText(title, WIDTH / 2 - 100, HEIGHT / 2 + 10);
    canvasCtx.fillText(title, WIDTH / 2 - 100, HEIGHT / 2 + 10);
    lastFrame = now;
}

function linkAudio() {
    gainNode = audioCtx.createGain();
    analyser.connect(gainNode);
    gainNode.connect(audioCtx.destination);
    canvas = document.getElementById("visualizer");
    audioTag = document.querySelector('audio');
    canvasCtx = canvas.getContext("2d");
    source1 = audioCtx.createMediaElementSource(audioTag);
    source1.connect(analyser);
    init();
}

function start() {
    document.getElementById("Stream").play();
}

function pause() {
    document.getElementById("Stream").pause();
}

$('#volume-bar').mousedown(function () {
    setVol($('#volume-bar').val());
    mouseDownEvent = setInterval(function () {
        setVol($('#volume-bar').val());
    }, 100);
});
$('#volume-bar').mouseup(function () {
    clearInterval(mouseDownEvent);
});
$('#volume-bar').mouseout(function () {
    clearInterval(mouseDownEvent);
});

function setVol(value) {
    gainNode.gain.value = value;
    document.getElementById("current-volume").style.width = (119 * value) + "px";
}

$(".filter-toggle").click(function() {
    firstChild = this.children[0];
    secondChild = this.children[1];

    if(firstChild.hasAttribute("style")){
        firstChild.removeAttribute("style");
        secondChild.setAttribute("style", "opacity:0.2;");
    } else {
        firstChild.setAttribute("style", "opacity:0.2;");
        secondChild.removeAttribute("style");
    }
});

function toggleFX(string) {
    if(string === "vibrance") {
        vibranceMode = !vibranceMode;
    } else if (string === "strobe") {
        strobeMode = !strobeMode;
    } else if (string === "inverse") {
        inverseMode = !inverseMode;
    } else if (string === "colourShift") {
        if (!colourShift) {
            colourShift = setInterval(function() {
                $("#body-fx-wrapper").css("-webkit-filter", "hue-rotate(" + (Math.random() * 360) + "deg)");
            }, 1000);
        } else {
            clearInterval(colourShift);
            colourShift = false;
        }
    } else if (string === "pulse") {
        pulseMode = !pulseMode;
    }
}

(function worker() {
    $.ajax({
        url: 'fetcher.php?host='+host,
        success: function(data) {
            title = data;
            document.title = data;
        },
        complete: function() {
            // Schedule the next request when the current one's complete
            setTimeout(worker, 3000);
        }
    });
})();<|endoftext|>


<commit_before>
var http = require('http');

function writeOutputForm(response, code) {
	var fs = require('fs');

	fs.readFile('./form.html',function (err, form) {
		if (err) {
			throw err;
		}

		var html = form.toString();

		if (code) {
			html.replace("{code}", code);
		} else {
			html.replace("{code}", "JSON.stringify(api);");
		}

		response.write(html);

		response.end();
	});
}

var server = http.createServer();

server.on('request', function(request, response) {
	console.log('Got a hit.');

	response.writeHead(200, "OK", {'Content-Type': 'text/html'});

	switch (request.method + request.url) {
		case 'GET/':
			outForm(response, null);
			break;

		case 'POST/run':
			var reply = '';

			request.on('data', function(chunk) {
				console.log("Received body data: " + chunk.toString());

				reply += chunk.toString();
			});

			request.on('end', function() {
				try {
					var concierge = require('./concierge.js');
					var queryString = require('querystring');
					var runner = require("./runner");

					concierge.__fixup(request,response);

					codeToRun = queryString.parse(reply).code.trim();

					var result = runner.run(concierge, codeToRun);

					response.write(result);
				} catch (err) {
					response.write("Unknown error.");
				}

				writeOutputForm(response, reply);
			});

			break;

		default:
			response.writeHead(301, {'Location': '/'});
			response.end( "Nothing to see here. Move along. Nothing to see." );
			break;
	}
});

server.listen(8000, "127.0.0.1");

console.log('Server running at http://127.0.0.1:8000/');
<commit_msg>Remove extra spaces.<commit_after>
var http = require('http');

function writeOutputForm(response, code) {
	var fs = require('fs');

	fs.readFile('./form.html',function (err, form) {
		if (err) {
			throw err;
		}

		var html = form.toString();

		if (code) {
			html.replace("{code}", code);
		} else {
			html.replace("{code}", "JSON.stringify(api);");
		}

		response.write(html);

		response.end();
	});
}

var server = http.createServer();

server.on('request', function(request, response) {
	console.log('Got a hit.');

	response.writeHead(200, "OK", {'Content-Type': 'text/html'});

	switch (request.method + request.url) {
		case 'GET/':
			outForm(response, null);
			break;

		case 'POST/run':
			var reply = '';

			request.on('data', function(chunk) {
				console.log("Received body data: " + chunk.toString());

				reply += chunk.toString();
			});

			request.on('end', function() {
				try {
					var concierge = require('./concierge.js');
					var queryString = require('querystring');
					var runner = require("./runner");

					concierge.__fixup(request,response);

					codeToRun = queryString.parse(reply).code.trim();

					var result = runner.run(concierge, codeToRun);

					response.write(result);
				} catch (err) {
					response.write("Unknown error.");
				}

				writeOutputForm(response, reply);
			});

			break;

		default:
			response.writeHead(301, {'Location': '/'});
			response.end("Nothing to see here. Move along. Nothing to see.");
			break;
	}
});

server.listen(8000, "127.0.0.1");

console.log('Server running at http://127.0.0.1:8000/');
<|endoftext|>


<commit_before>/*
 * Module dependencies.
 */
const fs = require('fs');
const path = require('path');
const util = require('util');
const express = require('express');
const compression = require('compression');
const session = require('express-session');
const bodyParser = require('body-parser');
const logger = require('morgan');
const chalk = require('chalk');
const errorHandler = require('errorhandler');
const lusca = require('lusca');
const dotenv = require('dotenv');
const MongoStore = require('connect-mongo')(session);
const flash = require('express-flash');
const mongoose = require('mongoose');
const passport = require('passport');
const expressValidator = require('express-validator');
const sass = require('node-sass-middleware');
const multer = require('multer');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

/*
 * Load environment variables from .env file, where API keys and passwords are configured.
 */
dotenv.load({path: '.env'});

/*
 * Controllers (route handlers).
 */
const homeController = require('./controllers/home');
const userController = require('./controllers/user');
const submissionController = require('./controllers/submission');
const apiController = require('./controllers/api');
const contestController = require('./controllers/contest');

/*
 * Build-up Webpack compiler
 */
const webpackConfigGenerator = require('./webpack.config.js');
const webpackConfig = webpackConfigGenerator({}, {mode: process.env.NODE_ENV});
const compiler = webpack(webpackConfig);

/*
 * API keys and Passport configuration.
 */
const passportConfig = require('./config/passport');

const upload = multer();

/*
 * Create Express server.
 */
const app = express();
const io = require('./lib/socket-io');

/*
 * Connect to MongoDB.
 */
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', () => {
	throw new Error(
		`${chalk.red(
			'✗'
		)} MongoDB connection error. Please make sure MongoDB is running.`
	);
});

/*
 * Express configuration.
 */
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(compression());
app.use(
	sass({
		src: path.join(__dirname, 'public'),
		dest: path.join(__dirname, 'public'),
	})
);
app.use(
	webpackDevMiddleware(compiler, {publicPath: webpackConfig.output.publicPath})
);
if (process.env.NODE_ENV === 'development') {
	app.use(webpackHotMiddleware(compiler));
}
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(upload.fields([{name: 'file', maxCount: 1}]));
app.use(expressValidator());
app.use(
	session({
		resave: true,
		saveUninitialized: true,
		secret: process.env.SESSION_SECRET,
		store: new MongoStore({
			url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
			autoReconnect: true,
		}),
	})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
	lusca.csrf()(req, res, next);
});
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use(async (req, res, next) => {
	const hash = await util.promisify(fs.readFile)(
		path.resolve(__dirname, '.git/refs/heads/master')
	);

	res.locals.user = req.user;
	res.locals.hash = hash.toString().trim();
	res.locals.env = process.env.NODE_ENV;

	next();
});
app.use((req, res, next) => {
	// After successful login, redirect back to the intended page
	if (
		!req.user &&
		req.path !== '/login' &&
		req.path !== '/signup' &&
		!req.path.match(/^\/auth/) &&
		!req.path.match(/\./)
	) {
		req.session.returnTo = req.path;
	} else if (req.user && req.path === '/account') {
		req.session.returnTo = req.path;
	}
	next();
});
app.use(express.static(path.join(__dirname, 'public'), {maxAge: 31557600000}));

/*
 * Primary app routes.
 */
app.get('/', homeController.index);
app.get('/login', userController.getLogin);
app.get('/logout', userController.logout);
app.get('/account', passportConfig.isAuthenticated, userController.getAccount);
app.get('/contests/:contest', contestController.base, contestController.index);
app.get(
	'/contests/:contest/rule',
	contestController.base,
	contestController.rule
);
app.get(
	'/contests/:contest/submissions',
	contestController.base,
	submissionController.getSubmissions
);
app.get(
	'/contests/:contest/submissions/:submission',
	contestController.base,
	submissionController.getSubmission
);
app.get(
	'/contests/:contest/submissions/:submission/raw',
	contestController.base,
	submissionController.getRawSubmission
);
app.get(
	'/contests/:contest/admin',
	passportConfig.isAuthenticated,
	contestController.base,
	submissionController.getAdmin
);

app.get('/submissions/:submission', submissionController.getOldSubmission);

app.get(
	'/api/contests/:contest/submission',
	passportConfig.isAuthenticated,
	apiController.contest,
	apiController.getSubmission
);
app.post(
	'/api/contests/:contest/submission',
	passportConfig.isAuthenticated,
	apiController.contest,
	apiController.postSubmission
);
app.post(
	'/api/contests/:contest/execution',
	passportConfig.isAuthenticated,
	apiController.contest,
	apiController.postExecution
);
app.get(
	'/api/contests/:contest/languages',
	apiController.contest,
	apiController.getLanguages
);

/*
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get(
	'/auth/twitter/callback',
	passport.authenticate('twitter', {failureRedirect: '/login'}),
	(req, res) => {
		res.redirect(req.session.returnTo || '/');
	}
);

/*
 * Error Handler.
 */
app.use(errorHandler());

/*
 * Start Express server.
 */
const server = app.listen(app.get('port'), () => {
	console.log(
		'%s App is running at http://localhost:%d in %s mode',
		chalk.green('✓'),
		app.get('port'),
		app.get('env')
	);
	console.log('  Press CTRL-C to stop\n');
});

io.attach(server);

module.exports = app;
<commit_msg>Catch hash error in app.js<commit_after>/*
 * Module dependencies.
 */
const fs = require('fs');
const path = require('path');
const util = require('util');
const express = require('express');
const compression = require('compression');
const session = require('express-session');
const bodyParser = require('body-parser');
const logger = require('morgan');
const chalk = require('chalk');
const errorHandler = require('errorhandler');
const lusca = require('lusca');
const dotenv = require('dotenv');
const MongoStore = require('connect-mongo')(session);
const flash = require('express-flash');
const mongoose = require('mongoose');
const passport = require('passport');
const expressValidator = require('express-validator');
const sass = require('node-sass-middleware');
const multer = require('multer');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

/*
 * Load environment variables from .env file, where API keys and passwords are configured.
 */
dotenv.load({path: '.env'});

/*
 * Controllers (route handlers).
 */
const homeController = require('./controllers/home');
const userController = require('./controllers/user');
const submissionController = require('./controllers/submission');
const apiController = require('./controllers/api');
const contestController = require('./controllers/contest');

/*
 * Build-up Webpack compiler
 */
const webpackConfigGenerator = require('./webpack.config.js');
const webpackConfig = webpackConfigGenerator({}, {mode: process.env.NODE_ENV});
const compiler = webpack(webpackConfig);

/*
 * API keys and Passport configuration.
 */
const passportConfig = require('./config/passport');

const upload = multer();

/*
 * Create Express server.
 */
const app = express();
const io = require('./lib/socket-io');

/*
 * Connect to MongoDB.
 */
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', () => {
	throw new Error(
		`${chalk.red(
			'✗'
		)} MongoDB connection error. Please make sure MongoDB is running.`
	);
});

/*
 * Express configuration.
 */
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(compression());
app.use(
	sass({
		src: path.join(__dirname, 'public'),
		dest: path.join(__dirname, 'public'),
	})
);
app.use(
	webpackDevMiddleware(compiler, {publicPath: webpackConfig.output.publicPath})
);
if (process.env.NODE_ENV === 'development') {
	app.use(webpackHotMiddleware(compiler));
}
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(upload.fields([{name: 'file', maxCount: 1}]));
app.use(expressValidator());
app.use(
	session({
		resave: true,
		saveUninitialized: true,
		secret: process.env.SESSION_SECRET,
		store: new MongoStore({
			url: process.env.MONGODB_URI || process.env.MONGOLAB_URI,
			autoReconnect: true,
		}),
	})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
	lusca.csrf()(req, res, next);
});
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use(async (req, res, next) => {
	const hash = await util.promisify(fs.readFile)(
		path.resolve(__dirname, '.git/refs/heads/master')
	).catch(() => Math.floor(Math.random() * 1e10));

	res.locals.user = req.user;
	res.locals.hash = hash.toString().trim();
	res.locals.env = process.env.NODE_ENV;

	next();
});
app.use((req, res, next) => {
	// After successful login, redirect back to the intended page
	if (
		!req.user &&
		req.path !== '/login' &&
		req.path !== '/signup' &&
		!req.path.match(/^\/auth/) &&
		!req.path.match(/\./)
	) {
		req.session.returnTo = req.path;
	} else if (req.user && req.path === '/account') {
		req.session.returnTo = req.path;
	}
	next();
});
app.use(express.static(path.join(__dirname, 'public'), {maxAge: 31557600000}));

/*
 * Primary app routes.
 */
app.get('/', homeController.index);
app.get('/login', userController.getLogin);
app.get('/logout', userController.logout);
app.get('/account', passportConfig.isAuthenticated, userController.getAccount);
app.get('/contests/:contest', contestController.base, contestController.index);
app.get(
	'/contests/:contest/rule',
	contestController.base,
	contestController.rule
);
app.get(
	'/contests/:contest/submissions',
	contestController.base,
	submissionController.getSubmissions
);
app.get(
	'/contests/:contest/submissions/:submission',
	contestController.base,
	submissionController.getSubmission
);
app.get(
	'/contests/:contest/submissions/:submission/raw',
	contestController.base,
	submissionController.getRawSubmission
);
app.get(
	'/contests/:contest/admin',
	passportConfig.isAuthenticated,
	contestController.base,
	submissionController.getAdmin
);

app.get('/submissions/:submission', submissionController.getOldSubmission);

app.get(
	'/api/contests/:contest/submission',
	passportConfig.isAuthenticated,
	apiController.contest,
	apiController.getSubmission
);
app.post(
	'/api/contests/:contest/submission',
	passportConfig.isAuthenticated,
	apiController.contest,
	apiController.postSubmission
);
app.post(
	'/api/contests/:contest/execution',
	passportConfig.isAuthenticated,
	apiController.contest,
	apiController.postExecution
);
app.get(
	'/api/contests/:contest/languages',
	apiController.contest,
	apiController.getLanguages
);

/*
 * OAuth authentication routes. (Sign in)
 */
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get(
	'/auth/twitter/callback',
	passport.authenticate('twitter', {failureRedirect: '/login'}),
	(req, res) => {
		res.redirect(req.session.returnTo || '/');
	}
);

/*
 * Error Handler.
 */
app.use(errorHandler());

/*
 * Start Express server.
 */
const server = app.listen(app.get('port'), () => {
	console.log(
		'%s App is running at http://localhost:%d in %s mode',
		chalk.green('✓'),
		app.get('port'),
		app.get('env')
	);
	console.log('  Press CTRL-C to stop\n');
});

io.attach(server);

module.exports = app;
<|endoftext|>


<commit_before>const express = require('express');
const app = express();
const portNumber = process.env.PORT || 3000;

const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}
const path = require('path');

const users = require('./routes/users');
const token = require('./routes/token');
const resorts = require('./routes/resorts');
const trails = require('./routes/trails');
const ratings = require('./routes/ratings');
const favorites = require('./routes/favorites');

app.use(bodyParser.json());
app.use(cookieParser());

app.use('/apidoc', express.static(path.join(__dirname, 'apidoc')));
app.get('/', (req, res) => {
  res.status(200).send('Welcome to skiski.');
};

app.use(users);
app.use(token);
app.use(resorts);
app.use(trails);
app.use(ratings);
app.use(favorites);

app.use((req, res) => {
  res.sendStatus(404);
});

app.listen(portNumber, () => {
  console.log(`Listening on port ${portNumber}`);
});

module.exports = app;
<commit_msg>Fix defect for root route<commit_after>const express = require('express');
const app = express();
const portNumber = process.env.PORT || 3000;

const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}
const path = require('path');

const users = require('./routes/users');
const token = require('./routes/token');
const resorts = require('./routes/resorts');
const trails = require('./routes/trails');
const ratings = require('./routes/ratings');
const favorites = require('./routes/favorites');

app.use(bodyParser.json());
app.use(cookieParser());

app.use('/apidoc', express.static(path.join(__dirname, 'apidoc')));
app.get('/', (req, res) => {
  res.status(200).send('Welcome to skiski.');
});

app.use(users);
app.use(token);
app.use(resorts);
app.use(trails);
app.use(ratings);
app.use(favorites);

app.use((req, res) => {
  res.sendStatus(404);
});

app.listen(portNumber, () => {
  console.log(`Listening on port ${portNumber}`);
});

module.exports = app;
<|endoftext|>


<commit_before>var express = require('express'),
    mongo = require('mongodb'),
    Q = require('q'),
    passport = require('passport'),
    TwitterStrategy = require('passport-twitter').Strategy;

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/storypull';

var dbQ = Q.defer(),
    dbPromise = dbQ.promise;

mongo.Db.connect(mongoUri, function (err, db) {
    db.users = db.collection('users');
    db.stories = db.collection('stories');
    db.grafs = db.collection('grafs');
    dbQ.resolve(db);
});

function makeUri(req, path) {
    return req.protocol + "://" + req.get('host') + path;
}

function makeUUID() {
    return 'xxxxxxxxxxxx'.replace(/[x]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
}

function getStory(req, slug, callback, errCallback) {
    dbPromise.done(function(db) {
        db.stories.findOne({'slug': req.params.slug}, function(err, story) {
            if (err) {
                return errCallback(err);
            }
            if (story===null) {
                return errCallback({'status': 'Not found'});
            }
            story.uri = makeUri(req, '/api/stories/' + story.slug);
            var options = {'sort': [['sequence', 1], ['created_at', 1]]};
            db.grafs.find({'story': story.slug}, options).toArray(function(err, results) {
                if (err) {
                    return errCallback(err);
                }
                story.grafs = results;
                return callback(story, db);
            });
        });
    });
}

var app = express();
app.use(express.logger());
app.use(express.errorHandler());
app.use(express.static(__dirname + '/static'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: process.env.SECRET || 'foobar' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);

passport.use(new TwitterStrategy({
    consumerKey: process.env.TWITTER_CONSUMER_KEY,
    consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
    callbackURL: process.env.TWITTER_CALLBACK_URL
  },
  function(token, tokenSecret, profile, done) {
    dbPromise.done(function(db) {
        delete profile._json.status;
        delete profile._json.entities;

        db.users.findOne({'screen_name': profile.username}, function(err, user) {
            if (user!==null) {
                done(null, user);
            }
            db.users.insert(profile._json, function(err, docs) {
                done(null, docs);
            });
        });
    });
  }
));

passport.serializeUser(function(user, done) {
    done(null, user.screen_name);
});

passport.deserializeUser(function(id, done) {
    dbPromise.done(function(db) {
        db.users.findOne({'screen_name': id}, function(err, user) {
            done(err, user);
        });
    });
});

app.get('/api/status', function(req, res) {
    res.jsonp({'status': 'ok', 'user': req.user});
});

app.get('/api/auth/twitter', passport.authenticate('twitter'));

app.get('/api/auth/callback',
  passport.authenticate('twitter', { successRedirect: '/',
                                     failureRedirect: '/' }));

app.post('/api/import', function(req, res){
    dbPromise.done(function(db) {
        var stories = req.body.stories || [];

        stories.forEach(function(story) {
            var grafs = story.grafs || [];
            story.created_at = new Date();
            story.last_change = story.created_at;

            db.grafs.remove({'story': story.slug}, {}, function(err, docs) {
                grafs.forEach(function(graf, sequence) {
                    graf.story = story.slug;
                    graf.sequence = sequence + 1;
                    graf.key = makeUUID();
                    graf.created_at = story.created_at;
                    db.grafs.insert(graf, function(err, docs) {});
                });
            });
            delete story.grafs;
            db.stories.update({'slug': story.slug}, story, {'upsert': true}, function(err, docs) {});
        });
        res.jsonp({'status': 'ok'});
    });
});

app.get('/api/stories', function(req, res) {
    dbPromise.done(function(db) {
        db.stories.find().toArray(function(err, results) {
            results.forEach(function(story) {
                story.uri = makeUri(req, '/api/stories/' + story.slug);
            });
            res.jsonp({'results': results});
        });
    });
});

app.get('/api/stories/:slug', function(req, res) {
    getStory(req, req.params.slug, function(story) {
        res.jsonp(story);
    }, function(err) {
        res.status(404).jsonp(err);
    });
});

app.post('/api/stories/:slug/graf', function(req, res) {
    getStory(req, req.params.slug, function(story, db) {
        var graf = req.body;

        if (!story) {
            res.status(404).jsonp({'status': 'No such story'});
        }

        if (!req.user) {
            res.status(401).jsonp({'status': 'Not logged in'});
        }

        if (!graf || !graf.text || graf.text.length===0) {
            res.status(400).jsonp({'status': 'No text'});
        }

        graf.latest = true;
        graf.author = req.user.screen_name;
        graf.approved = (story.author === req.user.screen_name);
        graf.created_at = new Date();

        if (!graf.key && !graf.sequence) {
            var max = 0;
            // todo: generate and update sequence - implement shifting.
            story.grafs.forEach(function(g) {
                if (g.sequence > max) {
                    max = g.sequence;
                }
            });
            graf.sequence = max + 1;
        }

        graf.key = graf.key || makeUUID();

        db.stories.update({'slug': story.slug}, {'$set': {'last_change': graf.created_at}},
            {}, function(err, docs) {});
        var query = graf.approved ? {'$set': {'latest': false}} : {'$set': {'current': false, 'latest': false}};
        db.grafs.update({'slug': story.slug, 'key': graf.key}, query, {}, function(err, docs) {
            db.grafs.insert(graf, function(err, docs) {
                res.jsonp(docs);
            });
        });

    }, function(err) {
        res.status(404).jsonp(err);
    });
});

var port = parseInt(process.env.PORT, 10) || 3000;
app.listen(port);
//console.log('Listening on port ' + port);

<commit_msg>add user info to story output. <commit_after>var express = require('express'),
    mongo = require('mongodb'),
    Q = require('q'),
    passport = require('passport'),
    TwitterStrategy = require('passport-twitter').Strategy;

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/storypull';

var dbQ = Q.defer(),
    dbPromise = dbQ.promise;

mongo.Db.connect(mongoUri, function (err, db) {
    db.users = db.collection('users');
    db.stories = db.collection('stories');
    db.grafs = db.collection('grafs');
    dbQ.resolve(db);
});

function makeUri(req, path) {
    return req.protocol + "://" + req.get('host') + path;
}

function makeUUID() {
    return 'xxxxxxxxxxxx'.replace(/[x]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
}

function getProfiles(screen_names, callback) {
    dbPromise.done(function(db) {
        db.users.find({'screen_name': {'$in': screen_names}}).toArray(function(err, results) {
            var profiles = {};
            results.forEach(function(p) {
                profiles[p.screen_name] = p;
            });
            callback(profiles);
        });
    });
}

function getStory(req, slug, callback, errCallback) {
    dbPromise.done(function(db) {
        db.stories.findOne({'slug': req.params.slug}, function(err, story) {
            if (err) {
                return errCallback(err);
            }
            if (story===null) {
                return errCallback({'status': 'Not found'});
            }
            story.uri = makeUri(req, '/api/stories/' + story.slug);
            var options = {'sort': [['sequence', 1], ['created_at', 1]]};
            db.grafs.find({'story': story.slug}, options).toArray(function(err, results) {
                if (err) {
                    return errCallback(err);
                }
                var screen_names = [story.author];
                story.grafs = results;
                story.grafs.forEach(function(g) {
                    if (g.author && screen_names.indexOf(g.author) == -1) {
                        screen_names.push(g.author);
                    }
                });
                getProfiles(screen_names, function(profiles) {
                    story.author_data = profiles[story.author];
                    story.grafs.forEach(function(g) {
                        g.author_data = profiles[story.author];
                    });
                    return callback(story, db);
                });
            });
        });
    });
}

var app = express();
app.use(express.logger());
app.use(express.errorHandler());
app.use(express.static(__dirname + '/static'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ secret: process.env.SECRET || 'foobar' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);

passport.use(new TwitterStrategy({
    consumerKey: process.env.TWITTER_CONSUMER_KEY,
    consumerSecret: process.env.TWITTER_CONSUMER_SECRET,
    callbackURL: process.env.TWITTER_CALLBACK_URL
  },
  function(token, tokenSecret, profile, done) {
    dbPromise.done(function(db) {
        delete profile._json.status;
        delete profile._json.entities;

        db.users.findOne({'screen_name': profile.username}, function(err, user) {
            if (user!==null) {
                done(null, user);
            }
            db.users.insert(profile._json, function(err, docs) {
                done(null, docs);
            });
        });
    });
  }
));

passport.serializeUser(function(user, done) {
    done(null, user.screen_name);
});

passport.deserializeUser(function(id, done) {
    dbPromise.done(function(db) {
        db.users.findOne({'screen_name': id}, function(err, user) {
            done(err, user);
        });
    });
});

app.get('/api/status', function(req, res) {
    res.jsonp({'status': 'ok', 'user': req.user});
});

app.get('/api/auth/twitter', passport.authenticate('twitter'));

app.get('/api/auth/callback',
  passport.authenticate('twitter', { successRedirect: '/',
                                     failureRedirect: '/' }));

app.post('/api/import', function(req, res){
    dbPromise.done(function(db) {
        var stories = req.body.stories || [];

        stories.forEach(function(story) {
            var grafs = story.grafs || [];
            story.created_at = new Date();
            story.last_change = story.created_at;

            db.grafs.remove({'story': story.slug}, {}, function(err, docs) {
                grafs.forEach(function(graf, sequence) {
                    graf.story = story.slug;
                    graf.sequence = sequence + 1;
                    graf.key = makeUUID();
                    graf.created_at = story.created_at;
                    db.grafs.insert(graf, function(err, docs) {});
                });
            });
            delete story.grafs;
            db.stories.update({'slug': story.slug}, story, {'upsert': true}, function(err, docs) {});
        });
        res.jsonp({'status': 'ok'});
    });
});

app.get('/api/stories', function(req, res) {
    dbPromise.done(function(db) {
        db.stories.find().toArray(function(err, results) {
            results.forEach(function(story) {
                story.uri = makeUri(req, '/api/stories/' + story.slug);
            });
            res.jsonp({'results': results});
        });
    });
});

app.get('/api/stories/:slug', function(req, res) {
    getStory(req, req.params.slug, function(story) {
        res.jsonp(story);
    }, function(err) {
        res.status(404).jsonp(err);
    });
});

app.post('/api/stories/:slug/graf', function(req, res) {
    getStory(req, req.params.slug, function(story, db) {
        var graf = req.body;

        if (!story) {
            res.status(404).jsonp({'status': 'No such story'});
        }

        if (!req.user) {
            res.status(401).jsonp({'status': 'Not logged in'});
        }

        if (!graf || !graf.text || graf.text.length===0) {
            res.status(400).jsonp({'status': 'No text'});
        }

        graf.latest = true;
        graf.author = req.user.screen_name;
        graf.approved = (story.author === req.user.screen_name);
        graf.created_at = new Date();

        if (!graf.key && !graf.sequence) {
            var max = 0;
            // todo: generate and update sequence - implement shifting.
            story.grafs.forEach(function(g) {
                if (g.sequence > max) {
                    max = g.sequence;
                }
            });
            graf.sequence = max + 1;
        }

        graf.key = graf.key || makeUUID();

        db.stories.update({'slug': story.slug}, {'$set': {'last_change': graf.created_at}},
            {}, function(err, docs) {});
        var query = graf.approved ? {'$set': {'latest': false}} : {'$set': {'current': false, 'latest': false}};
        db.grafs.update({'slug': story.slug, 'key': graf.key}, query, {}, function(err, docs) {
            db.grafs.insert(graf, function(err, docs) {
                res.jsonp(docs);
            });
        });

    }, function(err) {
        res.status(404).jsonp(err);
    });
});

var port = parseInt(process.env.PORT, 10) || 3000;
app.listen(port);
//console.log('Listening on port ' + port);

<|endoftext|>


<commit_before>/** @jsx React.DOM */

var _ = require('lodash');
var spawn = require('child_process').spawn;
var fs = require('fs');
var http = require('http');
var md = require('html-md');
var gui = require('nw.gui');

//var flow = new EventEmitter();
//
//document.getElementById('openBlog').addEventListener('click', function() {
//  var chooser = document.getElementById('fileDialog');
//  chooser.addEventListener('change', function() {
//    var blogDir = this.value;
//    flow.emit('startJekyll', blogDir);
//    flow.emit('getMarkdownFiles', blogDir);
//  });
//  chooser.click();
//});
//
//function getUrl() {
//  var path = document.getElementsByTagName('iframe')[0].contentWindow.location.pathname;
//  flow.emit('iframeUrl', path);
//}
//
//flow.on('loading', function() {
//  document.getElementById('home').innerHTML = '
Loading...
';
//});
//
//flow.on('editMode', function() {
//  console.log('EDIT MODE IS ON');
//  document.getElementById('savePost').classList.remove('hidden');
//  document.getElementById('publishPost').classList.remove('hidden');
//});
//
//flow.on('startHttpServer', function(path) {
//  var server = spawn('node', ['node_modules/http-server/bin/http-server', path + '/_site']);
//
//  server.stdout.once('data', function (data) {
//    console.log('stdout: ' + data);
//    var url = 'http://localhost:8080';
//    document.querySelector('body').classList.remove('cover');
//    document.getElementById('main').innerHTML = '';
//    flow.emit('showTopBar');
//    flow.emit('getMarkdownFiles');
//  });
//
//  server.stderr.on('data', function (data) {
//    console.log('stderr: ' + data);
//  });
//
//  server.on('close', function (code) {
//    console.log('child process exited with code ' + code);
//  });
//});
//
//flow.on('startJekyll', function(source) {
//  flow.emit('loading');
//  var child = exec('jekyll build -s ' + source, function(err, stdout, stderr) {
//    console.log(stdout);
//    flow.emit('startHttpServer', source);
//  });
//});
//
//flow.on('showTopBar', function() {
//  document.querySelector('.fixed').classList.remove('hidden');
//});
//
//flow.on('getMarkdownFiles', function(path) {
//  fs.readdir(path + '/_posts', function(err, files) {
//
//    if (!files) {
//      alert('No posts found');
//    }
//
//    var posts = _.filter(files, function(file) {
//      var extension = file.split('.').pop();
//      return extension === 'md' || extension === 'markdown'
//    });
//
//    flow.emit('checkIfInEditMode', posts);
//  });
//});
//
//
//flow.on('checkIfInEditMode', function(posts) {
//  flow.on('iframeUrl', function(url) {
//    console.log(posts);
//    console.log(url);
//
//    var url = url.replace(/\//g, '');
//    var posts = _.map(posts, function(post) { return post.split('-').slice(3).join('-').split('.').shift() });
//  });
//});

//flow.on('readMarkdownFiles', function(path, posts) {
//
//  var renderer = new marked.Renderer();
//
//  renderer.image = function(href, title, text) {
//    var out = '' : '>';
//    return out;
//  };
//
//  _.each(posts, function(post) {
//
//    var file = fs.readFileSync(path + '/_posts/' + post, 'utf8');
//
//    $('.highlight').each(function(index, element) {
//      console.log('found highlight');
//      var language = $(this).find('code').attr('class');
//      var text = $(this).text();
//      $(this).text('{% highlight js %}\n' + text + '\n{% endhighlight %}');
//    });
//
//    $('.side-nav').append('
' + post + '
');
//    var html = marked(file, { renderer: renderer });
//    $('#editor').html(html);
//    var options = {
//      editor: document.getElementById('editor')
//    };
//    var editor = new Pen(options);
//  });
//
//});

var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;

var Home = React.createClass({
  componentDidMount: function() {
    if (!this.props.blogDidLoad) {
      this.refs.fileDialog.getDOMNode().setAttribute('nwdirectory', '');
      this.refs.fileDialog.getDOMNode().addEventListener('change', this.updatePath);
    }
  },
  handleBlogDidLoad: function(value) {
    this.props.updateBlogDidLoad(value);
  },
  handleClick: function() {
    this.refs.fileDialog.getDOMNode().click();
  },
  handleUpdatePosts: function(path) {
    var files = fs.readdirSync(path + '/_posts');

    var posts = _.filter(files, function(file) {
      var extension = file.split('.').pop();
      return extension === 'md' || extension === 'markdown'
    });

    this.props.updatePosts(posts);
  },
  updatePath: function(e) {
    this.props.updatePath(e.target.value);

    var jekyll = spawn('jekyll', ['serve', '--watch', '-s', e.target.value]);

    jekyll.stdout.once('data', function (data) {
      this.handleBlogDidLoad(true);
      console.log('stdout: ' + data);
    }.bind(this));
    jekyll.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
    });
    jekyll.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });
    jekyll.on('close', function (code) {
      console.log('child process exited with code ' + code);
    });

    var win = gui.Window.get();

    win.on('close', function() {
      jekyll.kill();
      this.close(true);
    });

    this.handleUpdatePosts(e.target.value);
  },
  render: function() {
    var view = null;

    if (this.props.blogDidLoad) {
      document.body.classList.remove('cover');
      view = (

          <Topbar blogDidLoad={this.props.blogDidLoad} editMode={this.props.editMode} />

      );
    } else {
      view = (

          <button ref="openBlog" onClick={this.handleClick} className="btn outline">Open Blog</button>
          <input ref="fileDialog" type="file" className="hidden" />

{this.props.path}

{this.props.posts}

Select a local Jekyll blog

      );
    }

    return
{view}
;
  }
});

var Topbar = React.createClass({
  render: function() {
    return (

 New Post

 Save

 Publish

Close

    );
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      blogDidLoad: false,
      editMode: false,
      path: '',
      url: 'http://localhost:4000',
      posts: []
    }
  },
  updatePath: function(path) {
    this.setState({
      path: path
    });
  },
  updatePosts: function(posts) {
    this.setState({
      posts: posts
    });
  },
  updateBlogDidLoad: function(value) {
    this.setState({
      blogDidLoad: value
    })
  },
  render: function() {
    return (

        <Home
          blogDidLoad={this.state.blogDidLoad}
          updateBlogDidLoad={this.updateBlogDidLoad}
          editMode={this.state.editMode}
          updatePath={this.updatePath}
          updatePosts={this.updatePosts}
          path={this.state.path}
          url={this.state.url}
          posts={this.state.posts}
        />

    );
  }
});

React.renderComponent(
  <App />,
  document.body
);
<commit_msg>Iframe is now properly loaded when blogDidLoad state is changed<commit_after>/** @jsx React.DOM */

var _ = require('lodash');
var spawn = require('child_process').spawn;
var fs = require('fs');
var http = require('http');
var md = require('html-md');
var gui = require('nw.gui');

//var flow = new EventEmitter();
//
//document.getElementById('openBlog').addEventListener('click', function() {
//  var chooser = document.getElementById('fileDialog');
//  chooser.addEventListener('change', function() {
//    var blogDir = this.value;
//    flow.emit('startJekyll', blogDir);
//    flow.emit('getMarkdownFiles', blogDir);
//  });
//  chooser.click();
//});
//
//function getUrl() {
//  var path = document.getElementsByTagName('iframe')[0].contentWindow.location.pathname;
//  flow.emit('iframeUrl', path);
//}
//
//flow.on('loading', function() {
//  document.getElementById('home').innerHTML = '
Loading...
';
//});
//
//flow.on('editMode', function() {
//  console.log('EDIT MODE IS ON');
//  document.getElementById('savePost').classList.remove('hidden');
//  document.getElementById('publishPost').classList.remove('hidden');
//});
//
//flow.on('startHttpServer', function(path) {
//  var server = spawn('node', ['node_modules/http-server/bin/http-server', path + '/_site']);
//
//  server.stdout.once('data', function (data) {
//    console.log('stdout: ' + data);
//    var url = 'http://localhost:8080';
//    document.querySelector('body').classList.remove('cover');
//    document.getElementById('main').innerHTML = '';
//    flow.emit('showTopBar');
//    flow.emit('getMarkdownFiles');
//  });
//
//  server.stderr.on('data', function (data) {
//    console.log('stderr: ' + data);
//  });
//
//  server.on('close', function (code) {
//    console.log('child process exited with code ' + code);
//  });
//});
//
//flow.on('startJekyll', function(source) {
//  flow.emit('loading');
//  var child = exec('jekyll build -s ' + source, function(err, stdout, stderr) {
//    console.log(stdout);
//    flow.emit('startHttpServer', source);
//  });
//});
//
//flow.on('showTopBar', function() {
//  document.querySelector('.fixed').classList.remove('hidden');
//});
//
//flow.on('getMarkdownFiles', function(path) {
//  fs.readdir(path + '/_posts', function(err, files) {
//
//    if (!files) {
//      alert('No posts found');
//    }
//
//    var posts = _.filter(files, function(file) {
//      var extension = file.split('.').pop();
//      return extension === 'md' || extension === 'markdown'
//    });
//
//    flow.emit('checkIfInEditMode', posts);
//  });
//});
//
//
//flow.on('checkIfInEditMode', function(posts) {
//  flow.on('iframeUrl', function(url) {
//    console.log(posts);
//    console.log(url);
//
//    var url = url.replace(/\//g, '');
//    var posts = _.map(posts, function(post) { return post.split('-').slice(3).join('-').split('.').shift() });
//  });
//});

//flow.on('readMarkdownFiles', function(path, posts) {
//
//  var renderer = new marked.Renderer();
//
//  renderer.image = function(href, title, text) {
//    var out = '' : '>';
//    return out;
//  };
//
//  _.each(posts, function(post) {
//
//    var file = fs.readFileSync(path + '/_posts/' + post, 'utf8');
//
//    $('.highlight').each(function(index, element) {
//      console.log('found highlight');
//      var language = $(this).find('code').attr('class');
//      var text = $(this).text();
//      $(this).text('{% highlight js %}\n' + text + '\n{% endhighlight %}');
//    });
//
//    $('.side-nav').append('
' + post + '
');
//    var html = marked(file, { renderer: renderer });
//    $('#editor').html(html);
//    var options = {
//      editor: document.getElementById('editor')
//    };
//    var editor = new Pen(options);
//  });
//
//});

var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;

var Home = React.createClass({
  componentDidMount: function() {
    if (!this.props.blogDidLoad) {
      this.refs.fileDialog.getDOMNode().setAttribute('nwdirectory', '');
      this.refs.fileDialog.getDOMNode().addEventListener('change', this.updatePath);
    }
  },
  handleBlogDidLoad: function(value) {
    this.props.updateBlogDidLoad(value);
  },
  handleClick: function() {
    this.refs.fileDialog.getDOMNode().click();
  },
  handleUpdatePosts: function(path) {
    var files = fs.readdirSync(path + '/_posts');

    var posts = _.filter(files, function(file) {
      var extension = file.split('.').pop();
      return extension === 'md' || extension === 'markdown'
    });

    this.props.updatePosts(posts);
  },
  updatePath: function(e) {
    this.props.updatePath(e.target.value);

    var jekyll = spawn('jekyll', ['serve', '--watch', '-s', e.target.value]);

    jekyll.stdout.once('data', function (data) {
      console.log('stdout: ' + data);
    }.bind(this));
    jekyll.stdout.on('data', function (data) {
      var target = 'Server running...';
      var target2 = 'Address already in use';
      var line = data.toString();
      if (line.match(target) && line.match(target).length) {
        this.handleBlogDidLoad(true);
      } else if (line.match(target2) && line.match(target2).length) {
        this.handleBlogDidLoad(true);
      }
    }.bind(this));
    jekyll.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });
    jekyll.on('close', function (code) {
      console.log('child process exited with code ' + code);
    });

    process.on('exit', function() {
      jekyll.kill();
    });

    var win = gui.Window.get();

    win.on('close', function() {
      alert('bye');
      jekyll.kill();
      this.close(true);
    });

    this.handleUpdatePosts(e.target.value);
  },
  render: function() {
    var view = null;

    if (this.props.blogDidLoad) {
      document.body.classList.remove('cover');
      view = (

          <Topbar blogDidLoad={this.props.blogDidLoad} editMode={this.props.editMode} />

      );
    } else {
      view = (

          <button ref="openBlog" onClick={this.handleClick} className="btn outline">Open Blog</button>
          <input ref="fileDialog" type="file" className="hidden" />

{this.props.path}

{this.props.posts}

Select a local Jekyll blog

      );
    }

    return
{view}
;
  }
});

var Topbar = React.createClass({
  render: function() {
    return (

 New Post

 Save

 Publish

Close

    );
  }
});

var App = React.createClass({
  getInitialState: function() {
    return {
      blogDidLoad: false,
      editMode: false,
      path: '',
      url: 'http://localhost:4000',
      posts: []
    }
  },
  updatePath: function(path) {
    this.setState({
      path: path
    });
  },
  updatePosts: function(posts) {
    this.setState({
      posts: posts
    });
  },
  updateBlogDidLoad: function(value) {
    this.setState({
      blogDidLoad: value
    })
  },
  render: function() {
    return (

        <Home
          blogDidLoad={this.state.blogDidLoad}
          updateBlogDidLoad={this.updateBlogDidLoad}
          editMode={this.state.editMode}
          updatePath={this.updatePath}
          updatePosts={this.updatePosts}
          path={this.state.path}
          url={this.state.url}
          posts={this.state.posts}
        />

    );
  }
});

React.renderComponent(
  <App />,
  document.body
);
<|endoftext|>


<commit_before>'use strict';

var express = require( 'express' ),
    netiam  = require( 'netiam' ),
    app     = express(),
    server  = require( 'http' ).createServer( app ),
    netiam  = netiam( app );

netiam
    .get( '/' )
    .custom( function( resource, req, res ) {
        resource.data = {
            'Hello': 'World!'
        };
    } )
    .json();

server.listen( 3000 );
<commit_msg>fix: duplicate variable declaration<commit_after>'use strict';

var express = require( 'express' ),
    app     = express(),
    server  = require( 'http' ).createServer( app ),
    netiam  = require( 'netiam' )( app );

netiam
    .get( '/' )
    .custom( function( resource, req, res ) {
        resource.data = {
            'Hello': 'World!'
        };
    } )
    .json();

server.listen( 3000 );
<|endoftext|>