<commit_before>
var PARSERS = require('./parsers')

var MARKER_START = '/**'
var MARKER_START_SKIP = '/***'
var MARKER_END = '*/'

/* ------- util functions ------- */

function merge (/* ...objects */) {
  var k, obj
  var res = {}
  var objs = Array.prototype.slice.call(arguments)

  for (var i = 0, l = objs.length; i < l; i++) {
    obj = objs[i]
    for (k in obj) {
      if (obj.hasOwnProperty(k)) {
        res[k] = obj[k]
      }
    }
  }
  return res
}

function find (list, filter) {
  var k
  var i = list.length
  var matchs = true

  while (i--) {
    for (k in filter) {
      if (filter.hasOwnProperty(k)) {
        matchs = (filter[k] === list[i][k]) && matchs
      }
    }
    if (matchs) { return list[i] }
  }
  return null
}

/* ------- parsing ------- */

/**
 * Parses "@tag {type} name description"
 * @param {string} str Raw doc string
 * @param {Array[function]} parsers Array of parsers to be applied to the source
 * @returns {object} parsed tag node
 */
function parse_tag (str, parsers) {
  if (typeof str !== 'string' || str[0] !== '@') { return null }

  var data = parsers.reduce(function (state, parser) {
    var result

    try {
      result = parser(state.source, merge({}, state.data))
    } catch (err) {
      state.data.errors = (state.data.errors || [])
        .concat(parser.name + ': ' + err.message)
    }

    if (result) {
      state.source = state.source.slice(result.source.length)
      state.data = merge(state.data, result.data)
    }

    return state
  }, {
    source: str,
    data: {}
  }).data

  data.optional = !!data.optional
  data.type = data.type === undefined ? '' : data.type
  data.name = data.name === undefined ? '' : data.name
  data.description = data.description === undefined ? '' : data.description

  return data
}

/**
 * Parses comment block (array of String lines)
 */
function parse_block (source, opts) {
  var trim = opts.trim
    ? function trim (s) { return s.trim() }
    : function trim (s) { return s }

  var source_str = source
    .map(function (line) { return trim(line.source) })
    .join('\n')

  source_str = trim(source_str)

  var start = source[0].number

  // merge source lines into tags
  // we assume tag starts with "@"
  source = source
    .reduce(function (tags, line) {
      line.source = trim(line.source)

      if (line.source.match(/^\s*@(\w+)/)) {
        tags.push({source: [line.source], line: line.number})
      } else {
        var tag = tags[tags.length - 1]
        tag.source.push(line.source)
      }

      return tags
    }, [{source: []}])
    .map(function (tag) {
      tag.source = trim(tag.source.join('\n'))
      return tag
    })

  // Block description
  var description = source.shift()

  // skip if no descriptions and no tags
  if (description.source === '' && source.length === 0) {
    return null
  }

  var tags = source.reduce(function (tags, tag) {
    var tag_node = parse_tag(tag.source, opts.parsers)

    if (!tag_node) { return tags }

    tag_node.line = tag.line
    tag_node.source = tag.source

    if (opts.dotted_names && tag_node.name.indexOf('.') !== -1) {
      var parent_name
      var parent_tag
      var parent_tags = tags
      var parts = tag_node.name.split('.')

      while (parts.length > 1) {
        parent_name = parts.shift()
        parent_tag = find(parent_tags, {
          tag: tag_node.tag,
          name: parent_name
        })

        if (!parent_tag) {
          parent_tag = {
            tag: tag_node.tag,
            line: Number(tag_node.line),
            name: parent_name,
            type: '',
            description: ''
          }
          parent_tags.push(parent_tag)
        }

        parent_tag.tags = parent_tag.tags || []
        parent_tags = parent_tag.tags
      }

      tag_node.name = parts[0]
      parent_tags.push(tag_node)
      return tags
    }

    return tags.concat(tag_node)
  }, [])

  return {
    tags: tags,
    line: start,
    description: description.source,
    source: source_str
  }
}

/**
 * Produces `extract` function with internal state initialized
 */
function mkextract (opts) {
  var chunk = null
  var indent = 0
  var number = 0

  opts = merge({}, {
    trim: true,
    dotted_names: false,
    parsers: [
      PARSERS.parse_tag,
      PARSERS.parse_type,
      PARSERS.parse_name,
      PARSERS.parse_description
    ]
  }, opts || {})

  /**
   * Read lines until they make a block
   * Return parsed block once fullfilled or null otherwise
   */
  return function extract (line) {
    var result = null
    var startPos = line.indexOf(MARKER_START)
    var endPos = line.indexOf(MARKER_END)

    // if open marker detected and it's not skip one
    if (startPos !== -1 && line.indexOf(MARKER_START_SKIP) !== startPos) {
      chunk = []
      indent = startPos + MARKER_START.length
    }

    // if we are on middle of comment block
    if (chunk) {
      var lineStart = indent

      // figure out if we slice from opening marker pos
      // or line start is shifted to the left
      var nonSpaceChar = line.match(/\S/)

      // skip for the first line starting with /** (fresh chunk)
      // it always has the right indentation
      if (chunk.length > 0 && nonSpaceChar) {
        if (nonSpaceChar[0] === '*') {
          lineStart = nonSpaceChar.index + 2
        } else if (nonSpaceChar.index < indent) {
          lineStart = nonSpaceChar.index
        }
      }

      // slice the line until end or until closing marker start
      chunk.push({
        number: number,
        source: line.slice(lineStart, endPos === -1 ? line.length : endPos)
      })

      // finalize block if end marker detected
      if (endPos !== -1) {
        result = parse_block(chunk, opts)
        chunk = null
        indent = 0
      }
    }

    number += 1
    return result
  }
}

/* ------- Public API ------- */

module.exports = function parse (source, opts) {
  var block
  var blocks = []
  var extract = mkextract(opts)
  var lines = source.split(/\n/)

  for (var i = 0, l = lines.length; i < l; i++) {
    block = extract(lines.shift())
    if (block) {
      blocks.push(block)
    }
  }

  return blocks
}

module.exports.PARSERS = PARSERS
module.exports.mkextract = mkextract
<commit_msg>add line not start with star join previous line options<commit_after>
var PARSERS = require('./parsers')

var MARKER_START = '/**'
var MARKER_START_SKIP = '/***'
var MARKER_END = '*/'

/* ------- util functions ------- */

function merge (/* ...objects */) {
  var k, obj
  var res = {}
  var objs = Array.prototype.slice.call(arguments)

  for (var i = 0, l = objs.length; i < l; i++) {
    obj = objs[i]
    for (k in obj) {
      if (obj.hasOwnProperty(k)) {
        res[k] = obj[k]
      }
    }
  }
  return res
}

function find (list, filter) {
  var k
  var i = list.length
  var matchs = true

  while (i--) {
    for (k in filter) {
      if (filter.hasOwnProperty(k)) {
        matchs = (filter[k] === list[i][k]) && matchs
      }
    }
    if (matchs) { return list[i] }
  }
  return null
}

/* ------- parsing ------- */

/**
 * Parses "@tag {type} name description"
 * @param {string} str Raw doc string
 * @param {Array[function]} parsers Array of parsers to be applied to the source
 * @returns {object} parsed tag node
 */
function parse_tag (str, parsers) {
  if (typeof str !== 'string' || str[0] !== '@') { return null }

  var data = parsers.reduce(function (state, parser) {
    var result

    try {
      result = parser(state.source, merge({}, state.data))
    } catch (err) {
      state.data.errors = (state.data.errors || [])
        .concat(parser.name + ': ' + err.message)
    }

    if (result) {
      state.source = state.source.slice(result.source.length)
      state.data = merge(state.data, result.data)
    }

    return state
  }, {
    source: str,
    data: {}
  }).data

  data.optional = !!data.optional
  data.type = data.type === undefined ? '' : data.type
  data.name = data.name === undefined ? '' : data.name
  data.description = data.description === undefined ? '' : data.description

  return data
}

/**
 * Parses comment block (array of String lines)
 */
function parse_block (source, opts) {
  var trim = opts.trim
    ? function trim (s) { return s.trim() }
    : function trim (s) { return s }

  var source_str = source
    .map(function (line) { return trim(line.source) })
    .join('\n')

  source_str = trim(source_str)

  var start = source[0].number

  // merge source lines into tags
  // we assume tag starts with "@"
  source = source
    .reduce(function (tags, line) {
      line.source = trim(line.source)

      if (line.source.match(/^\s*@(\w+)/)) {
        tags.push({source: [line.source], line: line.number})
      } else {
        var tag = tags[tags.length - 1]
        if (opts.join !== undefined && opts.join !== false && opts.join !== 0
            && !line.startWithStar && tag.source.length > 0) {
          var source
          if (typeof opts.join === 'string') {
            source = opts.join + line.source.replace(/^\s+/, '')
          } else if (typeof opts.join === 'number') {
            source = line.source
          } else {
            source = ' ' + line.source.replace(/^\s+/, '')
          }
          tag.source[tag.source.length - 1] += source
        } else {
          tag.source.push(line.source)
        }
      }

      return tags
    }, [{source: []}])
    .map(function (tag) {
      tag.source = trim(tag.source.join('\n'))
      return tag
    })

  // Block description
  var description = source.shift()

  // skip if no descriptions and no tags
  if (description.source === '' && source.length === 0) {
    return null
  }

  var tags = source.reduce(function (tags, tag) {
    var tag_node = parse_tag(tag.source, opts.parsers)

    if (!tag_node) { return tags }

    tag_node.line = tag.line
    tag_node.source = tag.source

    if (opts.dotted_names && tag_node.name.indexOf('.') !== -1) {
      var parent_name
      var parent_tag
      var parent_tags = tags
      var parts = tag_node.name.split('.')

      while (parts.length > 1) {
        parent_name = parts.shift()
        parent_tag = find(parent_tags, {
          tag: tag_node.tag,
          name: parent_name
        })

        if (!parent_tag) {
          parent_tag = {
            tag: tag_node.tag,
            line: Number(tag_node.line),
            name: parent_name,
            type: '',
            description: ''
          }
          parent_tags.push(parent_tag)
        }

        parent_tag.tags = parent_tag.tags || []
        parent_tags = parent_tag.tags
      }

      tag_node.name = parts[0]
      parent_tags.push(tag_node)
      return tags
    }

    return tags.concat(tag_node)
  }, [])

  return {
    tags: tags,
    line: start,
    description: description.source,
    source: source_str
  }
}

/**
 * Produces `extract` function with internal state initialized
 */
function mkextract (opts) {
  var chunk = null
  var indent = 0
  var number = 0

  opts = merge({}, {
    trim: true,
    dotted_names: false,
    parsers: [
      PARSERS.parse_tag,
      PARSERS.parse_type,
      PARSERS.parse_name,
      PARSERS.parse_description
    ]
  }, opts || {})

  /**
   * Read lines until they make a block
   * Return parsed block once fullfilled or null otherwise
   */
  return function extract (line) {
    var result = null
    var startPos = line.indexOf(MARKER_START)
    var endPos = line.indexOf(MARKER_END)

    // if open marker detected and it's not skip one
    if (startPos !== -1 && line.indexOf(MARKER_START_SKIP) !== startPos) {
      chunk = []
      indent = startPos + MARKER_START.length
    }

    // if we are on middle of comment block
    if (chunk) {
      var lineStart = indent
      var startWithStar = false

      // figure out if we slice from opening marker pos
      // or line start is shifted to the left
      var nonSpaceChar = line.match(/\S/)

      // skip for the first line starting with /** (fresh chunk)
      // it always has the right indentation
      if (chunk.length > 0 && nonSpaceChar) {
        if (nonSpaceChar[0] === '*') {
          lineStart = nonSpaceChar.index + 2
          startWithStar = true
        } else if (nonSpaceChar.index < indent) {
          lineStart = nonSpaceChar.index
        }
      }

      // slice the line until end or until closing marker start
      chunk.push({
        number: number,
        startWithStar: startWithStar,
        source: line.slice(lineStart, endPos === -1 ? line.length : endPos)
      })

      // finalize block if end marker detected
      if (endPos !== -1) {
        result = parse_block(chunk, opts)
        chunk = null
        indent = 0
      }
    }

    number += 1
    return result
  }
}

/* ------- Public API ------- */

module.exports = function parse (source, opts) {
  var block
  var blocks = []
  var extract = mkextract(opts)
  var lines = source.split(/\n/)

  for (var i = 0, l = lines.length; i < l; i++) {
    block = extract(lines.shift())
    if (block) {
      blocks.push(block)
    }
  }

  return blocks
}

module.exports.PARSERS = PARSERS
module.exports.mkextract = mkextract
<|endoftext|>


<commit_before>/**
 * @file Defines the provider settings.
 *
 * Will set the path to Mongo, and applications id
 * Most of the configuration can be done using system environment variables.
 */

// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
var default_port = 8000;
if(node_env === "production") {
  default_port = 80;
}

if(!process.env.GMAIL_ID) {
  console.log("GMAIL_ID not specified, api will not work.");
}
if (!process.env.GMAIL_SECRET){
  console.log("GMAIL_SECRET not specified, api will not work.");
}
if (!process.env.GMAIL_CLUESTR_ID){
  console.log("GMAIL_CLUESTR_ID not specified, api will not work.");
}
if (!process.env.GMAIL_CLUESTR_SECRET){
  console.log("GMAIL_CLUESTR_SECRET not specified, api will not work.");
}
if (!process.env.NUMBER_OF_MAILS_TO_RETRIEVE){
  console.log("NUMBER_OF_MAILS_TO_RETRIEVE not specified, api will not work.");
}
if (!process.env.GMAIL_TEST_REFRESH_TOKEN){
  console.log("GMAIL_TEST_REFRESH_TOKEN not specified, api will not work.");
}
if (!process.env.GMAIL_TEST_ACCOUNT_NAME) {
  console.log("GMAIL_TEST_ACCOUNT_NAME not specified, api will not work.");
}
if (!process.env.GOOGLE_CONNECT_URL) {
  console.log("GOOGLE__CONNECT_URL not specified, api will not work.");
}
if (!process.env.GMAIL_CALLBACK_URL) {
  console.log("GMAIL_CALLBACK_URL not specified, api will not work.");
}

// Exports configuration
module.exports = {
  env: node_env,
  port: process.env.PORT || default_port,
  mongo_url: process.env.MONGO_URL || ("mongodb://localhost/provider-gmail-" + node_env),

  max_concurrency: process.env.GMAIL_MAX_CONCURRENCY || 5,
  workers: process.env.WORKERS || 2,

  google_id: process.env.GMAIL_ID,
  google_secret: process.env.GMAIL_SECRET,
  google_callback: process.env.GMAIL_CALLBACK_URL,

  connect_url: process.env.GOOGLE_CONNECT_URL,
  cluestr_id: process.env.GMAIL_CLUESTR_ID,
  cluestr_secret: process.env.GMAIL_CLUESTR_SECRET,
  number_of_mails_to_retrieve: process.env.NUMBER_OF_MAILS_TO_RETRIEVE,

  test_refresh_token: process.env.GMAIL_TEST_REFRESH_TOKEN,
  test_account: process.env.GMAIL_TEST_ACCOUNT_NAME
};
<commit_msg>Removed double underscoreé<commit_after>/**
 * @file Defines the provider settings.
 *
 * Will set the path to Mongo, and applications id
 * Most of the configuration can be done using system environment variables.
 */

// node_env can either be "development" or "production"
var node_env = process.env.NODE_ENV || "development";
var default_port = 8000;
if(node_env === "production") {
  default_port = 80;
}

if(!process.env.GMAIL_ID) {
  console.log("GMAIL_ID not specified, api will not work.");
}
if (!process.env.GMAIL_SECRET){
  console.log("GMAIL_SECRET not specified, api will not work.");
}
if (!process.env.GMAIL_CLUESTR_ID){
  console.log("GMAIL_CLUESTR_ID not specified, api will not work.");
}
if (!process.env.GMAIL_CLUESTR_SECRET){
  console.log("GMAIL_CLUESTR_SECRET not specified, api will not work.");
}
if (!process.env.NUMBER_OF_MAILS_TO_RETRIEVE){
  console.log("NUMBER_OF_MAILS_TO_RETRIEVE not specified, api will not work.");
}
if (!process.env.GMAIL_TEST_REFRESH_TOKEN){
  console.log("GMAIL_TEST_REFRESH_TOKEN not specified, api will not work.");
}
if (!process.env.GMAIL_TEST_ACCOUNT_NAME) {
  console.log("GMAIL_TEST_ACCOUNT_NAME not specified, api will not work.");
}
if (!process.env.GOOGLE_CONNECT_URL) {
  console.log("GOOGLE_CONNECT_URL not specified, api will not work.");
}
if (!process.env.GMAIL_CALLBACK_URL) {
  console.log("GMAIL_CALLBACK_URL not specified, api will not work.");
}

// Exports configuration
module.exports = {
  env: node_env,
  port: process.env.PORT || default_port,
  mongo_url: process.env.MONGO_URL || ("mongodb://localhost/provider-gmail-" + node_env),

  max_concurrency: process.env.GMAIL_MAX_CONCURRENCY || 5,
  workers: process.env.WORKERS || 2,

  google_id: process.env.GMAIL_ID,
  google_secret: process.env.GMAIL_SECRET,
  google_callback: process.env.GMAIL_CALLBACK_URL,

  connect_url: process.env.GOOGLE_CONNECT_URL,
  cluestr_id: process.env.GMAIL_CLUESTR_ID,
  cluestr_secret: process.env.GMAIL_CLUESTR_SECRET,
  number_of_mails_to_retrieve: process.env.NUMBER_OF_MAILS_TO_RETRIEVE,

  test_refresh_token: process.env.GMAIL_TEST_REFRESH_TOKEN,
  test_account: process.env.GMAIL_TEST_ACCOUNT_NAME
};
<|endoftext|>


<commit_before>// Jaksot-taulukko ja koodit-taulukko ladataan tiedostosta lukkariTaulukot.js

// Rakentaa linkin josta lukkari löytyy
function haeJakso(){
	var linkki = "";
    x = nykyinenJakso();
    if (x != 4 && x != 5)
    {
        alkupvm = jaksot[x][0].replace(/\./gi, "");
        loppupvm = jaksot[x][1].replace(/\./gi, "");
        linkki = "http://www.rpkk.fi/lukkarit/lukkari_show.php?toiminto=luokka&jalku="+alkupvm+"&jloppu="+loppupvm+"&jjakso="+x+"&luokka=D3";
        //var linkki = "jakso2.html";

        $("#lukkarinimet").load(linkki + " .lukkari_table2", function(){
            korvaa();
        });
        $("#lukkarikoodit").load(linkki + " .lukkari_table2");
        console.log("ARGH");
    }
    else{
        linkki = "img/toissa.jpg";
        $("#lukkarinimet").html("");
        $("#lukkarikoodit").html("");
    }
	$("#jaksoNumero").text($("#"+x).text());
}

// Hakee nykyisen jakson päivämäärän perusteella
function nykyinenJakso(){
	var nyt = Date.today();
	//var nyt = Date.parse(prompt("Anna testipäivämäärä")); //debug

	for (var i = 1; i <= 7; i++){
		loppupvm_seuraava = Date.parse(jaksot[i+1][1]);
		alkupvm = Date.parse(jaksot[i][0]);
		loppupvm = Date.parse(jaksot[i][1]);

		// Tarkistaa onko nykyinen päivämäärä jonkun jakson sisällä ja palauttaa jakson
		if(nyt >= alkupvm && nyt <= loppupvm){
			return i;
		}
		// Tarkista onko jakso mennyt ohi mutta uusi ei ole vielä alkanut(viikonloput jaksojen välissä)
		// Ja palautaa uuden jakson
		else if(nyt < loppupvm_seuraava && nyt >= loppupvm)
			return i+1;
	}
	// Palauttaa viimeisen jakson jos koulu loppunut
	if(nyt > jaksot[7][1])
	return 7;
}

// Korvaa talukosta koodit nimillä
function korvaa(){
	$("#lukkarinimet td").each(function(){
		var text = $(this).html(), i;
		for(i in koodit){
			text = text.replace(i, koodit[i]);
		}
		$(this).html(text);
	});
}

$(document).ready(function(){

	// Hae oikea jakso ja muuta jaksolistan vakioarvo samaksi
	haeJakso();

	$("#ruokalista").load("ruokalistaa.php");

	$(".jakso").click(function(){
		haeJakso($(this).attr("id"));
	});

	// Vaihtaa nimet koodeiksi ja toisinpäin
	$("#toggle").click(function(){
		$(".lukkari").toggle();
	});
});
<commit_msg>Finally fixed schedule loading<commit_after>// Jaksot-taulukko ja koodit-taulukko ladataan tiedostosta lukkariTaulukot.js

// Rakentaa linkin josta lukkari löytyy
function haeJakso(x){
	$("#lukkarinimet").html("");
	$("#lukkarikoodit").html("");
	var linkki = "";
	if (typeof x == "undefined")
		x = nykyinenJakso();
	if (x != 4 && x != 5)
	{
		alkupvm = jaksot[x][0].replace(/\./gi, "");
		loppupvm = jaksot[x][1].replace(/\./gi, "");
		linkki = "http://www.rpkk.fi/lukkarit/lukkari_show.php?toiminto=luokka&jalku="+alkupvm+"&jloppu="+loppupvm+"&jjakso="+x+"&luokka=D3";
		//var linkki = "jakso2.html";

		$("#lukkarinimet").load(linkki + " .lukkari_table2", function(){
			korvaa();
		});
		$("#lukkarikoodit").load(linkki + " .lukkari_table2");
	}
	else{
		linkki = "img/toissa.jpg";
		$("#lukkarinimet").html("");
		$("#lukkarikoodit").html("");
	}
	$("#jaksoNumero").text($("#"+x).text());
}

// Hakee nykyisen jakson päivämäärän perusteella
function nykyinenJakso(){
	var nyt = Date.today();
	//var nyt = Date.parse(prompt("Anna testipäivämäärä")); //debug

	for (var i = 1; i <= 7; i++){
		loppupvm_seuraava = Date.parse(jaksot[i+1][1]);
		alkupvm = Date.parse(jaksot[i][0]);
		loppupvm = Date.parse(jaksot[i][1]);

		// Tarkistaa onko nykyinen päivämäärä jonkun jakson sisällä ja palauttaa jakson
		if(nyt >= alkupvm && nyt <= loppupvm)
			return i;
		// Tarkista onko jakso mennyt ohi mutta uusi ei ole vielä alkanut(viikonloput jaksojen välissä)
		// Ja palautaa uuden jakson
		else if(nyt < loppupvm_seuraava && nyt >= loppupvm)
			return i+1;
	}
	// Palauttaa viimeisen jakson jos koulu loppunut
	return 7;
}

// Korvaa talukosta koodit nimillä
function korvaa(){
	$("#lukkarinimet td").each(function(){
		var text = $(this).html(), i;
		for(i in koodit){
			text = text.replace(i, koodit[i]);
		}
		$(this).html(text);
	});
}

$(document).ready(function(){

	// Hae oikea jakso ja muuta jaksolistan vakioarvo samaksi
	haeJakso();

	$("#ruokalista").load("ruokalistaa.php");

	$(".jakso").click(function(){
		haeJakso($(this).attr("id"));
	});

	// Vaihtaa nimet koodeiksi ja toisinpäin
	$("#toggle").click(function(){
		$(".lukkari").toggle();
	});
});
<|endoftext|>


<commit_before>app.controller('HomeController', function ($scope, $location, $http, $interval, AuthService, ngProgress) {
    ngProgress.reset();
    ngProgress.start();
    AuthService.refresh();
    $scope.user = AuthService.getUser();
    $scope.items = {};
    $scope.resuls = {};

    $http.get("/api/service/queries")
        .success(function (data) {
            $scope.items = eval(data);
            ngProgress.complete();
        })
        .error(function (error) {
            console.log(error);
        });

    $scope.loginPath = function () {
        return "/login?path=" + $location.path();
    };

    $scope.$watch(function () {
        return AuthService.getUser();
    }, function () {
        $scope.user = AuthService.getUser();
    });

    $scope.isAuthenticated = AuthService.isAuthenticated();
    $scope.$watch(function () {
        return AuthService.isAuthenticated();
    }, function () {
        $scope.isAuthenticated = AuthService.isAuthenticated();
    });

    $scope.isAdmin = AuthService.isAdmin();
    $scope.$watch(function () {
        return AuthService.isAuthenticated();
    }, function () {
        $scope.isAdmin = AuthService.isAdmin();
    });

    $scope.launchRequest = function (index) {
        var item = $scope.items[index].request;
        ngProgress.reset();
        ngProgress.start();
        $http.post("/api/execute/query/", item)
            .success(function (data) {
                console.log(data);
                ngProgress.complete();
                requestCallback(data.jobId);
            })
            .error(function (error) {
                console.log(error);
            });
    };

    var requestCallback = function (jobId) {
        var stop;
        $scope.startListenResult = function () {
            if (angular.isDefined(stop)) return;

            stop = $interval(function () {
                $http.get("/api/execute/result/" + jobId)
                    .success(function (data) {
                        if (data.jobComplete === true) {
                            $scope.stopFight();
                            $scope.resuls = eval(data);

                        }
                    })
                    .error(function (error) {

                    });
            }, 1000);
        };
        $scope.stopListenResult = function () {
            if (angular.isDefined(stop)) {
                $interval.cancel(stop);
                stop = undefined;
            }
        };
        $scope.startListenResult(jobId);
    };
});<commit_msg>FIx JS<commit_after>app.controller('HomeController', function ($scope, $location, $http, $interval, AuthService, ngProgress) {
    ngProgress.reset();
    ngProgress.start();
    AuthService.refresh();
    $scope.user = AuthService.getUser();
    $scope.items = {};
    $scope.resuls = {};

    $http.get("/api/service/queries")
        .success(function (data) {
            $scope.items = eval(data);
            ngProgress.complete();
        })
        .error(function (error) {
            console.log(error);
        });

    $scope.loginPath = function () {
        return "/login?path=" + $location.path();
    };

    $scope.$watch(function () {
        return AuthService.getUser();
    }, function () {
        $scope.user = AuthService.getUser();
    });

    $scope.isAuthenticated = AuthService.isAuthenticated();
    $scope.$watch(function () {
        return AuthService.isAuthenticated();
    }, function () {
        $scope.isAuthenticated = AuthService.isAuthenticated();
    });

    $scope.isAdmin = AuthService.isAdmin();
    $scope.$watch(function () {
        return AuthService.isAuthenticated();
    }, function () {
        $scope.isAdmin = AuthService.isAdmin();
    });

    $scope.launchRequest = function (index) {
        var item = $scope.items[index].request;
        ngProgress.reset();
        ngProgress.start();
        $http.post("/api/execute/query/", item)
            .success(function (data) {
                console.log(data);
                ngProgress.complete();
                requestCallback(data.jobId);
            })
            .error(function (error) {
                console.log(error);
            });
    };

    var requestCallback = function (jobId) {
        var stop;
        $scope.startListenResult = function () {
            if (angular.isDefined(stop)) return;

            stop = $interval(function () {
                $http.get("/api/execute/result/" + jobId)
                    .success(function (data) {
                        if (data.jobComplete === true) {
                            $scope.stopListenResult();
                            $scope.resuls = eval(data);
                            console.log(data);

                        }
                    })
                    .error(function (error) {

                    });
            }, 1000);
        };
        $scope.stopListenResult = function () {
            if (angular.isDefined(stop)) {
                $interval.cancel(stop);
                stop = undefined;
            }
        };
        $scope.startListenResult(jobId);
    };
});<|endoftext|>


<commit_before>import log from '../logger';
import { waitForCondition } from 'asyncbox';
import B from 'bluebird';
import { util } from 'appium-support';

let commands = {}, helpers = {}, extensions = {};

commands.implicitWait = function (ms) {
  this.implicitWaitMs = parseInt(ms, 10);
  log.debug(`Set implicit wait to ${ms}ms`);
};

commands.timeouts = async function (name, duration) {
  if (name === 'command') {
    this.newCommandTimeoutMs = duration;
  }
};

helpers.clearNewCommandTimeout = function () {
  if (this.noCommandTimer) {
    this.noCommandTimer.cancel();
    this.noCommandTimer = null;
  }
};

helpers.startNewCommandTimeout = function (cmd) {
  // make sure there are no rogue timeouts
  this.clearNewCommandTimeout();

  // if command timeout is 0, it is disabled
  if(!this.newCommandTimeoutMs) return;

  this.noCommandTimer = util.cancellableDelay(this.newCommandTimeoutMs);
  this.noCommandTimer
    .then(async () => {
      log.warn(`Shutting down because we waited ` +
               `${this.newCommandTimeoutMs / 1000} seconds for a command`);
      await this.startUnexpectedShutdown(new Error(`Command ${cmd} timed out!`));
    })
    .catch(B.CancellationError, (/*err*/) => {
      // ignore
    });
};

helpers.implicitWaitForCondition = async (condFn) => {
  log.debug(`Waiting up to ${this.implicitWaitMs} ms for condition`);
  let wrappedCondFn = async function (...args) {
    // reset command timeout
    this.clearNewCommandTimeout();

    return await condFn(...args);
  }.bind(this); // TODO: fix jshint and use an arrow function
  return await waitForCondition(wrappedCondFn, {
    waitMs: this.implicitWaitMs, intervalMs: 500, logger: log
  });
};

Object.assign(extensions, commands, helpers);
export { commands, helpers};
export default extensions;
<commit_msg>Fix bug in timeout setting<commit_after>import log from '../logger';
import { waitForCondition } from 'asyncbox';
import B from 'bluebird';
import { util } from 'appium-support';

let commands = {}, helpers = {}, extensions = {};

commands.implicitWait = function (ms) {
  this.implicitWaitMs = parseInt(ms, 10);
  log.debug(`Set implicit wait to ${ms}ms`);
};

commands.timeouts = async function (name, duration) {
  if (name === 'command') {
    this.newCommandTimeoutMs = duration;
  }
};

helpers.clearNewCommandTimeout = function () {
  if (this.noCommandTimer) {
    this.noCommandTimer.cancel();
    this.noCommandTimer = null;
  }
};

helpers.startNewCommandTimeout = function (cmd) {
  // make sure there are no rogue timeouts
  this.clearNewCommandTimeout();

  // if command timeout is 0, it is disabled
  if(!this.newCommandTimeoutMs) return;

  this.noCommandTimer = util.cancellableDelay(this.newCommandTimeoutMs);
  this.noCommandTimer
    .then(async () => {
      log.warn(`Shutting down because we waited ` +
               `${this.newCommandTimeoutMs / 1000} seconds for a command`);
      await this.startUnexpectedShutdown(new Error(`Command ${cmd} timed out!`));
    })
    .catch(B.CancellationError, (/*err*/) => {
      // ignore
    });
};

helpers.implicitWaitForCondition = async function (condFn) {
  log.debug(`Waiting up to ${this.implicitWaitMs} ms for condition`);
  let wrappedCondFn = async function (...args) {
    // reset command timeout
    this.clearNewCommandTimeout();

    return await condFn(...args);
  }.bind(this); // TODO: fix jshint and use an arrow function
  return await waitForCondition(wrappedCondFn, {
    waitMs: this.implicitWaitMs, intervalMs: 500, logger: log
  });
};

Object.assign(extensions, commands, helpers);
export { commands, helpers };
export default extensions;
<|endoftext|>


<commit_before>var ogs = require('open-graph-scraper');
var express = require('express');
var ElasticSearch = require('elasticsearch');
var moment = require("moment-timezone");
var camoUrl = require('camo-url')({
	host : process.env.CAMO_HOST,
	key : process.env.CAMO_KEY
});
var URL = require('url');
var app = express();
var es = new ElasticSearch.Client({
	host : process.env.ES_URL,
	apiVersion : process.env.ES_VERSION
});

var esIndex = process.env.ES_INDEX;
var esType = process.env.ES_TYPE;

var INFO = "INFO";
var WARN = "WARN";
var ERR = "ERROR";

var BLOCKED_EXTENSIONS = ['pdf', 'gif', 'jpg', 'jpeg', 'png', 'svg'];

var CACHABLE_ERRORS = ['Page Not Found'];

var cacheInDays = parseInt(process.env.CACHE_IN_DAYS, 10) || 28;

function stringToUnderscore(input) {
	return input.replace(/([A-Z])/g, function ($1) {
		return "_" + $1.toLowerCase();
	});
}

function log(level, message) {
	console.log(JSON.stringify({time : moment(new Date()).format(), severity : level, message : message}));
}

function cacheExpired(date) {
	return moment(date).add(cacheInDays, 'days').isBefore(moment(new Date()));
}

function defaultOutput(url) {
	return Object.assign({}, {
		_url : url,
		_scrapedAt : parseInt(moment(new Date()).format('x'), 10),
		_cacheResponse : false,
		data : {}
	});
}

function postProcess(url, data) {
	var result = defaultOutput(url);

	// Format images for their special cases
	['ogImage', 'twitterImage'].forEach(function (key) {
		if (data[key]) {
			if (!data[key].url) {
				delete data[key];
			} else if (data[key].url) {
				var imageUrl = resolveRelative(data[key].url, url);
				if (process.env.CAMO_KEY && process.env.CAMO_HOST) {
					imageUrl = camoUrl(imageUrl);
				}
				var image = Object.assign({}, {value : imageUrl});
				Object.keys(data[key]).filter(function (e) {
					return e !== 'url';
				}).forEach(function (innerKey) {
					image[innerKey] = [{value : data[key][innerKey]}];
				});
				data[key] = image;
			}
		}
	});

	// Now map this to useful structures
	Object.keys(data).forEach(function (originalKey) {
		if (data[originalKey] === null || typeof data[originalKey] === 'undefined') {
			return;
		}

		var key;
		if (originalKey.startsWith('og')) {
			key = stringToUnderscore(originalKey.substring(2)).substring(1);
		}
		else if (originalKey.startsWith('twitter')) {
			key = stringToUnderscore(originalKey);
		} else {
			return;
		}

		if (data[originalKey].value) {
			result.data[key] = [data[originalKey]]
		} else {
			result.data[key] = [{value : data[originalKey]}]
		}
	});

	if (!result.data.url) {
		result.data.url = [{value : url}];
	}

	return result;
}

function resolveRelative(path, base) {
	// Absolute URL
	if (path.match(/^[a-z]*:\/\//)) {
		return path;
	}
	// Protocol relative URL
	if (path.indexOf("//") === 0) {
		return base.replace(/\/\/.*/, path)
	}
	// Upper directory
	if (path.indexOf("../") === 0) {
		return resolveRelative(path.slice(3), base.replace(/\/[^\/]*$/, ''));
	}
	// Relative to the root
	if (path.indexOf('/') === 0) {
		if (!base.endsWith('/')) {
			base += '/';
		}
		var match = base.match(/(\w*:\/\/)?[^\/]*\//) || [base];
		return match[0] + path.slice(1);
	}
	//relative to the current directory
	return base.replace(/\/[^\/]*$/, "") + '/' + path.replace(/^\.\//, '');
}

if (process.env.ES_URL) {
	log(INFO, "Connected to Elasticsearch " + process.env.ES_VERSION + " on " + process.env.ES_URL + " using index '" + esIndex + "' with type '" + esType + "'. Using a cache of " + cacheInDays + " days.");
}

function cacheEntryIsValid(error, response, url) {
	if (!process.env.ES_URL) {
		// No ES cache entry is set
		log(WARN, "No ES cache specified, so skipping it");
		return false;
	}
	if (error) {
		if (error.status === 404) {
			log(INFO, "Getting new value for '" + url + "' since never seen that before");
		} else {
			log(WARN, "Got an error [" + error.status + "] while fetching URL '" + url + "' from ES cache");
		}
		return false;
	}
	if (!response._source || !response._source._scrapedAt) {
		log(WARN, 'Formatting error in cache, refetching ' + url);
		return false;
	}
	if (cacheExpired(response._source._scrapedAt)) {
		// cache is just expired
		log(INFO, "Getting new value for '" + url + "' since the cache expired");
		return false;
	}
	return true;
}

function workWorkWork(req, res) {
	var urlToFetch = req.query.url;
	var pathname = URL.parse(urlToFetch).pathname;
	var blockedResource = BLOCKED_EXTENSIONS.filter(function (extension) {
			return pathname.endsWith(extension);
		}).length > 0;
	if (blockedResource) {
		// Return standard format for misbehaving clients
		var blockedError = defaultOutput(urlToFetch);
		blockedError.error = 'This resource is blocked from fetching opengraph data';
		res.status(403).json(blockedError);
		return;
	}

	var encodedUrl = encodeURI(urlToFetch);
	es.get({index : esIndex, type : esType, id : encodedUrl}, function (err, response) {
		if (cacheEntryIsValid(err, response, urlToFetch)) {
			// If there is an error, we do not have the opengraph data so we return a 404
			var statusCode = !response._source.error ? 200 : 404;
			res.status(statusCode).json(response._source);
		} else {
			var options = {
				url : urlToFetch,
				timeout : 5000
			};
			ogs(options, function (err, ogData) {
				var resultData;
				if (err || !ogData.success) {
					// Return the data to the client
					resultData = defaultOutput(urlToFetch);
					resultData.err = ogData.err;

					res.status(404).json(resultData);

					if (CACHABLE_ERRORS.indexOf(ogData.err) === -1) {
						// If this is a more permanent failure, we cache it
						log(ERR, 'Error while fetching OG data for ' + urlToFetch + ': ' + JSON.stringify(ogData));
						return;
					}
				} else {
					// All went well, postprocess and send to client
					resultData = postProcess(urlToFetch, ogData.data);
					res.json(resultData);
				}

				if (process.env.ES_URL) {
					resultData._cacheResponse = true;
					es.index({index : esIndex, type : esType, id : encodedUrl, body : resultData}, function (err) {
						if (err) {
							log(WARN, 'Could not save value to cache due to error: ' + err);
						}
					});
				}
			});
		}
	});
}

app.get('/opengraph', workWorkWork);
app.get('/_health', function (req, res) {
	res.end('Jolly good here');
});
app.listen(7070, function () {
	log(INFO, 'Server is listening');
});

<commit_msg>Rescue urls which start with "www." and which do not include an protocol<commit_after>var ogs = require('open-graph-scraper');
var express = require('express');
var ElasticSearch = require('elasticsearch');
var moment = require("moment-timezone");
var camoUrl = require('camo-url')({
	host : process.env.CAMO_HOST,
	key : process.env.CAMO_KEY
});
var URL = require('url');
var app = express();
var es = new ElasticSearch.Client({
	host : process.env.ES_URL,
	apiVersion : process.env.ES_VERSION
});

var esIndex = process.env.ES_INDEX;
var esType = process.env.ES_TYPE;

var INFO = "INFO";
var WARN = "WARN";
var ERR = "ERROR";

var BLOCKED_EXTENSIONS = ['pdf', 'gif', 'jpg', 'jpeg', 'png', 'svg'];

var CACHABLE_ERRORS = ['Page Not Found'];

var cacheInDays = parseInt(process.env.CACHE_IN_DAYS, 10) || 28;

function stringToUnderscore(input) {
	return input.replace(/([A-Z])/g, function ($1) {
		return "_" + $1.toLowerCase();
	});
}

function log(level, message) {
	console.log(JSON.stringify({time : moment(new Date()).format(), severity : level, message : message}));
}

function cacheExpired(date) {
	return moment(date).add(cacheInDays, 'days').isBefore(moment(new Date()));
}

function defaultOutput(url) {
	return Object.assign({}, {
		_url : url,
		_scrapedAt : parseInt(moment(new Date()).format('x'), 10),
		_cacheResponse : false,
		data : {}
	});
}

function postProcess(url, data) {
	var result = defaultOutput(url);

	// Format images for their special cases
	['ogImage', 'twitterImage'].forEach(function (key) {
		if (data[key]) {
			if (!data[key].url) {
				delete data[key];
			} else if (data[key].url) {
				var imageUrl = resolveRelative(data[key].url, url);
				if (process.env.CAMO_KEY && process.env.CAMO_HOST) {
					imageUrl = camoUrl(imageUrl);
				}
				var image = Object.assign({}, {value : imageUrl});
				Object.keys(data[key]).filter(function (e) {
					return e !== 'url';
				}).forEach(function (innerKey) {
					image[innerKey] = [{value : data[key][innerKey]}];
				});
				data[key] = image;
			}
		}
	});

	// Now map this to useful structures
	Object.keys(data).forEach(function (originalKey) {
		if (data[originalKey] === null || typeof data[originalKey] === 'undefined') {
			return;
		}

		var key;
		if (originalKey.startsWith('og')) {
			key = stringToUnderscore(originalKey.substring(2)).substring(1);
		}
		else if (originalKey.startsWith('twitter')) {
			key = stringToUnderscore(originalKey);
		} else {
			return;
		}

		if (data[originalKey].value) {
			result.data[key] = [data[originalKey]]
		} else {
			result.data[key] = [{value : data[originalKey]}]
		}
	});

	if (!result.data.url) {
		result.data.url = [{value : url}];
	}

	return result;
}

function resolveRelative(path, base) {
	// Somebody forgot to properly set a protocol on an otherwise absolute url
	if (path.indexOf("www.") == 0) {
		return 'http://' + path;
	}

	// Absolute URL
	if (path.match(/^[a-z]*:\/\//)) {
		return path;
	}
	// Protocol relative URL
	if (path.indexOf("//") === 0) {
		return base.replace(/\/\/.*/, path)
	}
	// Upper directory
	if (path.indexOf("../") === 0) {
		return resolveRelative(path.slice(3), base.replace(/\/[^\/]*$/, ''));
	}
	// Relative to the root
	if (path.indexOf('/') === 0) {
		if (!base.endsWith('/')) {
			base += '/';
		}
		var match = base.match(/(\w*:\/\/)?[^\/]*\//) || [base];
		return match[0] + path.slice(1);
	}
	//relative to the current directory
	return base.replace(/\/[^\/]*$/, "") + '/' + path.replace(/^\.\//, '');
}

if (process.env.ES_URL) {
	log(INFO, "Connected to Elasticsearch " + process.env.ES_VERSION + " on " + process.env.ES_URL + " using index '" + esIndex + "' with type '" + esType + "'. Using a cache of " + cacheInDays + " days.");
}

function cacheEntryIsValid(error, response, url) {
	if (!process.env.ES_URL) {
		// No ES cache entry is set
		log(WARN, "No ES cache specified, so skipping it");
		return false;
	}
	if (error) {
		if (error.status === 404) {
			log(INFO, "Getting new value for '" + url + "' since never seen that before");
		} else {
			log(WARN, "Got an error [" + error.status + "] while fetching URL '" + url + "' from ES cache");
		}
		return false;
	}
	if (!response._source || !response._source._scrapedAt) {
		log(WARN, 'Formatting error in cache, refetching ' + url);
		return false;
	}
	if (cacheExpired(response._source._scrapedAt)) {
		// cache is just expired
		log(INFO, "Getting new value for '" + url + "' since the cache expired");
		return false;
	}
	return true;
}

function workWorkWork(req, res) {
	var urlToFetch = req.query.url;
	var pathname = URL.parse(urlToFetch).pathname;
	var blockedResource = BLOCKED_EXTENSIONS.filter(function (extension) {
			return pathname.endsWith(extension);
		}).length > 0;
	if (blockedResource) {
		// Return standard format for misbehaving clients
		var blockedError = defaultOutput(urlToFetch);
		blockedError.error = 'This resource is blocked from fetching opengraph data';
		res.status(403).json(blockedError);
		return;
	}

	var encodedUrl = encodeURI(urlToFetch);
	es.get({index : esIndex, type : esType, id : encodedUrl}, function (err, response) {
		if (cacheEntryIsValid(err, response, urlToFetch)) {
			// If there is an error, we do not have the opengraph data so we return a 404
			var statusCode = !response._source.error ? 200 : 404;
			res.status(statusCode).json(response._source);
		} else {
			var options = {
				url : urlToFetch,
				timeout : 5000
			};
			ogs(options, function (err, ogData) {
				var resultData;
				if (err || !ogData.success) {
					// Return the data to the client
					resultData = defaultOutput(urlToFetch);
					resultData.err = ogData.err;

					res.status(404).json(resultData);

					if (CACHABLE_ERRORS.indexOf(ogData.err) === -1) {
						// If this is a more permanent failure, we cache it
						log(ERR, 'Error while fetching OG data for ' + urlToFetch + ': ' + JSON.stringify(ogData));
						return;
					}
				} else {
					// All went well, postprocess and send to client
					resultData = postProcess(urlToFetch, ogData.data);
					res.json(resultData);
				}

				if (process.env.ES_URL) {
					resultData._cacheResponse = true;
					es.index({index : esIndex, type : esType, id : encodedUrl, body : resultData}, function (err) {
						if (err) {
							log(WARN, 'Could not save value to cache due to error: ' + err);
						}
					});
				}
			});
		}
	});
}

app.get('/opengraph', workWorkWork);
app.get('/_health', function (req, res) {
	res.end('Jolly good here');
});
app.listen(7070, function () {
	log(INFO, 'Server is listening');
});

<|endoftext|>


<commit_before>describe('Event Test Suite', function () {
    'use strict';

    var expect = chai.expect;

    function inject(callback, isAysnc) {
        return function (done) {
            seajs.use(['/plugin/events'], function (Events) {

                if (isAysnc) {
                    callback(Events, done);
                } else {
                    callback(Events);
                    done();
                }

            });
        };
    }

    it('on and trigger', inject(function (Events) {
        var obj = {
            counter: 0
        };
        Object.assign(obj, Events);
        obj.on('event', function() {
            obj.counter += 1;
        });
        obj.trigger('event');
        expect(obj.counter).to.equal(1);
        obj.trigger('event');
        obj.trigger('event');
        obj.trigger('event');
        obj.trigger('event');
        expect(obj.counter).to.equal(5);
    }));

    it('binding and triggering multiple events', inject(function (Events) {
        var obj = {
            counter: 0
        };
        Object.assign(obj, Events);

        obj.on('a b c', function() {
            obj.counter += 1;
        });

        obj.trigger('a');
        expect(obj.counter).to.equal(1);

        obj.trigger('a b');
        expect(obj.counter).to.equal(3);

        obj.trigger('c');
        expect(obj.counter).to.equal(4);

        obj.off('a c');
        obj.trigger('a b c');
        expect(obj.counter).to.equal(5);
    }));

    it('binding and triggering with event maps', inject(function(Events) {
        var obj = {counter: 0};
        Object.assign(obj, Events);

        function increment() {
            this.counter += 1;
        }

        obj.on({
            a: increment,
            b: increment,
            c: increment
        });

        obj.trigger('a');
        expect(obj.counter).to.equal(1);

        obj.trigger('a b');
        expect(obj.counter).to.equal(3);

        obj.trigger('c');
        expect(obj.counter).to.equal(4);

        obj.off({
            a: increment,
            c: increment
        });
        obj.trigger('a b c');
        expect(obj.counter).to.equal(5);
    }));

    it('binding and triggering multiple event names with event maps', inject(function(Events) {
        var obj = {counter: 0};
        Object.assign(obj, Events);

        var increment = function() {
            this.counter += 1;
        };

        obj.on({
            'a b c': increment
        });

        obj.trigger('a');
        expect(obj.counter).to.equal(1);

        obj.trigger('a b');
        expect(obj.counter).to.equal(3);

        obj.trigger('c');
        expect(obj.counter).to.equal(4);

        obj.off({
            'a c': increment
        });
        obj.trigger('a b c');
        expect(obj.counter).to.equal(5);
    }));

    it('binding and trigger with event maps context', inject(function(Events) {
        var obj = {counter: 0};
        var context = {};
        Object.assign(obj, Events);

        obj.on({
            a: function() {
                // 'defaults `context` to `callback` param'
                expect(this).to.equal(context);
            }
        }, context).trigger('a');

        obj.off().on({
            a: function() {
                // 'will not override explicit `context` param'
                expect(this).to.equal(context);
            }
        }, obj, context).trigger('a');
    }));

    it('listenTo and stopListening', inject(function(Events) {
        var a = Object.assign({name: 'a'}, Events);
        var b = Object.assign({name: 'b'}, Events);
        a.listenTo(b, 'all', function(){
            expect(true).to.be.true;
        });
        b.trigger('anything');
        a.listenTo(b, 'all', function(){
            expect(true).to.be.false;
        });
        a.stopListening();
        b.trigger('anything');
    }));

    it('listenTo and stopListening with event maps', inject(function(Events) {
        var a = Object.assign({name: 'a'}, Events);
        var b = Object.assign({name: 'b'}, Events);
        var counter = 0;
        function cb(){
            counter += 1;
        };
        var counter2 = 0;
        function cb2(){
            counter2 += 1;
        };
        a.listenTo(b, {event: cb});
        b.trigger('event');
        expect(counter).to.equal(1);
        a.listenTo(b, {event2: cb2});
        b.on('event2', cb2);
        a.stopListening(b, {event2: cb2});
        b.trigger('event event2');
        expect(counter).to.equal(2);
        expect(counter2).to.equal(1);
        a.stopListening();
        b.trigger('event event2');
        expect(counter).to.equal(2);
        expect(counter2).to.equal(2);
    }));

    it('stopListening with omitted args', inject(function(Events) {
        var a = Object.assign({name: 'a'}, Events);
        var b = Object.assign({name: 'b'}, Events);
        var counter = 0;
        function cb() {
            counter += 1;
        }
        a.listenTo(b, 'event', cb);
        b.on('event', cb);
        a.listenTo(b, 'event2', cb);
        a.stopListening(null, {event: cb});
        b.trigger('event event2');
        expect(counter).to.equal(2);
        b.off();
        a.listenTo(b, 'event event2', cb);
        a.stopListening(null, 'event');
        a.stopListening();
        b.trigger('event2');
        expect(counter).to.equal(2);
    }));

    it('listenToOnce', inject(function(Events) {
        // Same as the previous test, but we use once rather than having to explicitly unbind
        var obj = {counterA: 0, counterB: 0};
        Object.assign(obj, Events);
        var incrA = function(){ obj.counterA += 1; obj.trigger('event'); };
        var incrB = function(){ obj.counterB += 1; };
        obj.listenToOnce(obj, 'event', incrA);
        obj.listenToOnce(obj, 'event', incrB);
        obj.trigger('event');
        expect(obj.counterA).to.equal(1);
        expect(obj.counterB).to.equal(1);
    }));

    it('listenToOnce and stopListening', inject(function(Events) {
        var a = Object.assign({}, Events);
        var b = Object.assign({}, Events);
        var counter = 0;
        a.listenToOnce(b, 'all', function() { counter += 1; });
        b.trigger('anything');
        b.trigger('anything');
        expect(1).to.equal(counter);
        a.listenToOnce(b, 'all', function() { counter += 1; });
        a.stopListening();
        b.trigger('anything');
        expect(1).to.equal(counter);
    }));

    it('listenTo, listenToOnce and stopListening', inject(function(Events) {
        var a = Object.assign({}, Events);
        var b = Object.assign({}, Events);
        var counter = 0;
        a.listenToOnce(b, 'all', function() { counter += 1; });
        b.trigger('anything');
        b.trigger('anything');
        expect(1).to.equal(counter);
        a.listenTo(b, 'all', function() { counter += 1; });
        a.stopListening();
        b.trigger('anything');
        expect(1).to.equal(counter);
    }));

    it('listenTo and stopListening with event maps', inject(function(Events) {
        var a = Object.assign({}, Events);
        var b = Object.assign({}, Events);
        var counter = 0;
        a.listenTo(b, {change: function(){ counter += 1; }});
        b.trigger('change');
        expect(counter).to.equal(1);
        a.listenTo(b, {change: function(){ counter += 1; }});
        a.stopListening();
        b.trigger('change');
        expect(counter).to.equal(1);
    }));
});
<commit_msg>添加测试用例：`listenTo yourself`<commit_after>describe('Event Test Suite', function () {
    'use strict';

    var expect = chai.expect;

    function inject(callback, isAysnc) {
        return function (done) {
            seajs.use(['/plugin/events'], function (Events) {

                if (isAysnc) {
                    callback(Events, done);
                } else {
                    callback(Events);
                    done();
                }

            });
        };
    }

    it('on and trigger', inject(function (Events) {
        var obj = {
            counter: 0
        };
        Object.assign(obj, Events);
        obj.on('event', function() {
            obj.counter += 1;
        });
        obj.trigger('event');
        expect(obj.counter).to.equal(1);
        obj.trigger('event');
        obj.trigger('event');
        obj.trigger('event');
        obj.trigger('event');
        expect(obj.counter).to.equal(5);
    }));

    it('binding and triggering multiple events', inject(function (Events) {
        var obj = {
            counter: 0
        };
        Object.assign(obj, Events);

        obj.on('a b c', function() {
            obj.counter += 1;
        });

        obj.trigger('a');
        expect(obj.counter).to.equal(1);

        obj.trigger('a b');
        expect(obj.counter).to.equal(3);

        obj.trigger('c');
        expect(obj.counter).to.equal(4);

        obj.off('a c');
        obj.trigger('a b c');
        expect(obj.counter).to.equal(5);
    }));

    it('binding and triggering with event maps', inject(function(Events) {
        var obj = {counter: 0};
        Object.assign(obj, Events);

        function increment() {
            this.counter += 1;
        }

        obj.on({
            a: increment,
            b: increment,
            c: increment
        });

        obj.trigger('a');
        expect(obj.counter).to.equal(1);

        obj.trigger('a b');
        expect(obj.counter).to.equal(3);

        obj.trigger('c');
        expect(obj.counter).to.equal(4);

        obj.off({
            a: increment,
            c: increment
        });
        obj.trigger('a b c');
        expect(obj.counter).to.equal(5);
    }));

    it('binding and triggering multiple event names with event maps', inject(function(Events) {
        var obj = {counter: 0};
        Object.assign(obj, Events);

        var increment = function() {
            this.counter += 1;
        };

        obj.on({
            'a b c': increment
        });

        obj.trigger('a');
        expect(obj.counter).to.equal(1);

        obj.trigger('a b');
        expect(obj.counter).to.equal(3);

        obj.trigger('c');
        expect(obj.counter).to.equal(4);

        obj.off({
            'a c': increment
        });
        obj.trigger('a b c');
        expect(obj.counter).to.equal(5);
    }));

    it('binding and trigger with event maps context', inject(function(Events) {
        var obj = {counter: 0};
        var context = {};
        Object.assign(obj, Events);

        obj.on({
            a: function() {
                // 'defaults `context` to `callback` param'
                expect(this).to.equal(context);
            }
        }, context).trigger('a');

        obj.off().on({
            a: function() {
                // 'will not override explicit `context` param'
                expect(this).to.equal(context);
            }
        }, obj, context).trigger('a');
    }));

    it('listenTo and stopListening', inject(function(Events) {
        var a = Object.assign({name: 'a'}, Events);
        var b = Object.assign({name: 'b'}, Events);
        a.listenTo(b, 'all', function(){
            expect(true).to.be.true;
        });
        b.trigger('anything');
        a.listenTo(b, 'all', function(){
            expect(true).to.be.false;
        });
        a.stopListening();
        b.trigger('anything');
    }));

    it('listenTo and stopListening with event maps', inject(function(Events) {
        var a = Object.assign({name: 'a'}, Events);
        var b = Object.assign({name: 'b'}, Events);
        var counter = 0;
        function cb(){
            counter += 1;
        };
        var counter2 = 0;
        function cb2(){
            counter2 += 1;
        };
        a.listenTo(b, {event: cb});
        b.trigger('event');
        expect(counter).to.equal(1);
        a.listenTo(b, {event2: cb2});
        b.on('event2', cb2);
        a.stopListening(b, {event2: cb2});
        b.trigger('event event2');
        expect(counter).to.equal(2);
        expect(counter2).to.equal(1);
        a.stopListening();
        b.trigger('event event2');
        expect(counter).to.equal(2);
        expect(counter2).to.equal(2);
    }));

    it('stopListening with omitted args', inject(function(Events) {
        var a = Object.assign({name: 'a'}, Events);
        var b = Object.assign({name: 'b'}, Events);
        var counter = 0;
        function cb() {
            counter += 1;
        }
        a.listenTo(b, 'event', cb);
        b.on('event', cb);
        a.listenTo(b, 'event2', cb);
        a.stopListening(null, {event: cb});
        b.trigger('event event2');
        expect(counter).to.equal(2);
        b.off();
        a.listenTo(b, 'event event2', cb);
        a.stopListening(null, 'event');
        a.stopListening();
        b.trigger('event2');
        expect(counter).to.equal(2);
    }));

    it('listenToOnce', inject(function(Events) {
        // Same as the previous test, but we use once rather than having to explicitly unbind
        var obj = {counterA: 0, counterB: 0};
        Object.assign(obj, Events);
        var incrA = function(){ obj.counterA += 1; obj.trigger('event'); };
        var incrB = function(){ obj.counterB += 1; };
        obj.listenToOnce(obj, 'event', incrA);
        obj.listenToOnce(obj, 'event', incrB);
        obj.trigger('event');
        expect(obj.counterA).to.equal(1);
        expect(obj.counterB).to.equal(1);
    }));

    it('listenToOnce and stopListening', inject(function(Events) {
        var a = Object.assign({}, Events);
        var b = Object.assign({}, Events);
        var counter = 0;
        a.listenToOnce(b, 'all', function() { counter += 1; });
        b.trigger('anything');
        b.trigger('anything');
        expect(1).to.equal(counter);
        a.listenToOnce(b, 'all', function() { counter += 1; });
        a.stopListening();
        b.trigger('anything');
        expect(1).to.equal(counter);
    }));

    it('listenTo, listenToOnce and stopListening', inject(function(Events) {
        var a = Object.assign({}, Events);
        var b = Object.assign({}, Events);
        var counter = 0;
        a.listenToOnce(b, 'all', function() { counter += 1; });
        b.trigger('anything');
        b.trigger('anything');
        expect(1).to.equal(counter);
        a.listenTo(b, 'all', function() { counter += 1; });
        a.stopListening();
        b.trigger('anything');
        expect(1).to.equal(counter);
    }));

    it('listenTo and stopListening with event maps', inject(function(Events) {
        var a = Object.assign({}, Events);
        var b = Object.assign({}, Events);
        var counter = 0;
        a.listenTo(b, {change: function(){ counter += 1; }});
        b.trigger('change');
        expect(counter).to.equal(1);
        a.listenTo(b, {change: function(){ counter += 1; }});
        a.stopListening();
        b.trigger('change');
        expect(counter).to.equal(1);
    }));

    it('listenTo yourself', inject(function(Events) {
        var e = Object.assign({}, Events);
        var counter = 0;
        e.listenTo(e, 'foo', function(){ counter += 1; });
        e.trigger('foo');
        expect(counter).to.equal(1);
    }));
});
<|endoftext|>


<commit_before>var KoaNeo4jApp = require('koa-neo4j');

console.log(KoaNeo4jApp);

var app = new KoaNeo4jApp({
    apis: [
        {
            method: 'GET',
            route: '/articles/:skip/:limit',
            cypherQueryFile: './cypher/articles.cyp'
        },
        {
            method: 'POST',
            route: '/articles',
            cypherQueryFile: './cypher/articles.cyp'
        }
    ],
    neo4j: {
        boltUrl: 'bolt://localhost',
        user: 'neo4j',
        password: 'k'
    }
});

// You can use `app.defineAPI` for better code organisation
// Perform post-processing on values return by the cypher query via `postProcess`

app.defineAPI({
    method: 'GET',
    route: '/articles/processed',
    cypherQueryFile: './cypher/articles.cyp',
    postProcess: function (result) {
        // Perform postprocessing on 'result' returned by executing the cypher query
        result.push({extra:'record'});
        // ...
        return result;
    }
});

// Routes can be guarded by role restriction using `allowedRoles`

app.configureAuthentication({
    userCypherQueryFile: './cypher/user.cyp',
        rolesCypherQueryFile: './cypher/roles.cyp',
        route: '/auth',
        secret: 'secret'
});

app.defineAPI({
    method: 'POST',
    route: '/articles/restricted',
    preProcess: function (params) {
        // Perform postprocessing on 'result' returned by executing the cypher query
        params.extra = 'extra parameter!';
        // ...
        return params;
    },
    cypherQueryFile: './cypher/articles.cyp',
    allowedRoles: ['admin']
});

// `app.router` is a standard koa-router which could be utilised to expand server's functionality
// visit github.com/alexmingoia/koa-router FMI

app.router.get('/noncypher', function (ctx, next) {
    ctx.body = "Using router you can do other things that don't need Cypher!";
    return next();
});

app.listen(3001, function () {
    console.log('App listening on port 3001.');
});
<commit_msg>more comments<commit_after>var KoaNeo4jApp = require('koa-neo4j');

console.log(KoaNeo4jApp);

var app = new KoaNeo4jApp({
    apis: [
        {
            method: 'GET',
            route: '/articles/:skip/:limit',
            cypherQueryFile: './cypher/articles.cyp'
        },
        {
            method: 'POST',
            route: '/articles',
            cypherQueryFile: './cypher/articles.cyp'
        }
    ],
    neo4j: {
        boltUrl: 'bolt://localhost',
        user: 'neo4j',
        password: 'k'
    }
});

// You can use `app.defineAPI` for better code organisation
// Perform post-processing on values return by the cypher query via `postProcess` lifecycle hook

app.defineAPI({
    method: 'GET',
    route: '/articles/processed',
    cypherQueryFile: './cypher/articles.cyp',
    postProcess: function (result) {
        // Perform postprocessing on 'result' returned by executing the cypher query
        result.push({extra:'record'});
        // ...
        return result;
    }
});

// Authentication and roles can be configured either by
// supplying an `authentication` key in config or by `app.configureAuthentication
// Routes can be guarded by role restriction using `allowedRoles`
// Another lifecycle hook is `postProcess` which is demonstrated below

app.configureAuthentication({
    userCypherQueryFile: './cypher/user.cyp',
    rolesCypherQueryFile: './cypher/roles.cyp',
    route: '/auth',
    secret: 'secret'
});

app.defineAPI({
    method: 'POST',
    route: '/articles/restricted',
    preProcess: function (params) {
        // Perform prrprocessing on 'params' which will be given to the cypher query
        params.extra = 'extra parameter!';
        // ...
        return params;
    },
    cypherQueryFile: './cypher/articles.cyp',
    allowedRoles: ['admin']
});

// `app.router` is a standard koa-router which could be utilised to expand server's functionality
// visit github.com/alexmingoia/koa-router FMI

app.router.get('/noncypher', function (ctx, next) {
    ctx.body = "Using router you can do other things that don't need Cypher!";
    return next();
});

app.listen(3001, function () {
    console.log('App listening on port 3001.');
});
<|endoftext|>


<commit_before>/**
 * @file Defines the hydrater settings.
 */

// nodeEnv can either be "development" or "production"
var nodeEnv = process.env.nodeEnv || "development";
var defaultPort = 8000;

// Number of tesseract instance to run simultaneously per cluster
var defaultConcurrency = 1;

if(nodeEnv === "production") {
  defaultPort = 80;
}

// Exports configuration
module.exports = {
  env: nodeEnv,
  port: process.env.PORT || defaultPort,

  concurrency: process.env.OCR_CONCURRENCY || defaultConcurrency,
  redisUrl: process.env.REDIS_URL,
  appName: process.env.APP_NAME || "ocr-hydrater",

  opbeat: {
    organizationId: process.env.OPBEAT_ORGANIZATION_ID,
    appId: process.env.OPBEAT_APP_ID,
    secretToken: process.env.OPBEAT_SECRET_TOKEN
  }
};
<commit_msg>Change env vars<commit_after>/**
 * @file Defines the hydrater settings.
 */

// nodeEnv can either be "development" or "production"
var nodeEnv = process.env.nodeEnv || "development";
var defaultPort = 8000;

// Number of tesseract instance to run simultaneously per cluster
var defaultConcurrency = 1;

if(nodeEnv === "production") {
  defaultPort = 80;
}

// Exports configuration
module.exports = {
  env: nodeEnv,
  port: process.env.PORT || defaultPort,

  concurrency: process.env.CONCURRENCY || defaultConcurrency,
  tasksPerProcess: process.env.TASKS_PER_PROCESS,

  redisUrl: process.env.REDIS_URL,
  appName: process.env.APP_NAME || "ocr-hydrater",

  opbeat: {
    organizationId: process.env.OPBEAT_ORGANIZATION_ID,
    appId: process.env.OPBEAT_APP_ID,
    secretToken: process.env.OPBEAT_SECRET_TOKEN
  }
};
<|endoftext|>


<commit_before>// MiniMap animation slow (Chrome profile)?
// reset animation include, MiniMap ignores animation options
L.Map.include({
    setView: function (center, zoom) {
        this._resetView(L.latLng(center), this._limitZoom(zoom));
        return this;
    }
});

// MiniMap (overview map)
function init(map) {
    L.Map.mergeOptions({
        zoomsliderControl: false,
        zoomDisplayControl: false
    });
    var osmMini = new L.OSM.Mapnik({
        opacity: 0.7
    });
    var miniMap = new L.Control.MiniMap(osmMini, {
        toggleDisplay: false,
        //zoomLevelOffset: -5,
        width: 164,
        height: 164
    }).addTo(map);
    miniMap._container.parentNode.removeChild(miniMap._container);
    document.getElementById('minimap').appendChild(miniMap._container);

    // tiles/bounds.js to display data extract bbox
    if (bounds) {
        var boundsGroup = L.featureGroup(window.bounds);
        boundsGroup.setStyle({
            weight: 2,
            dashArray: '10, 5',
            color: 'black',
            opacity: 1,
            fill: false
        });
        miniMap._miniMap.addLayer(boundsGroup);
    }
}

module.exports.init = init;
<commit_msg>avoid resetting main map on MiniMap add<commit_after>// MiniMap animation slow (Chrome profile)?
// reset animation include, MiniMap ignores animation options
L.Map.include({
    setView: function (center, zoom) {
        this._resetView(L.latLng(center), this._limitZoom(zoom));
        return this;
    }
});

// patch to avoid resetting main map on MiniMap add (_mainMapMoving=false initially)
// (addTo > _miniMap.setView > 'moveend' > _onMiniMapMoved > _mainMap.setView)
L.Control.MyMiniMap = L.Control.MiniMap.extend({
    onAdd: function (map) {
        L.Control.MiniMap.prototype.onAdd.call(this, map);
        this._mainMapMoving = true;
        return this._container;
    }
});

// MiniMap (overview map)
function init(map) {
    L.Map.mergeOptions({
        zoomsliderControl: false,
        zoomDisplayControl: false
    });
    var osmMini = new L.OSM.Mapnik({
        opacity: 0.7
    });
    var miniMap = new L.Control.MyMiniMap(osmMini, {
        toggleDisplay: false,
        //zoomLevelOffset: -5,
        width: 164,
        height: 164
    }).addTo(map);
    miniMap._container.parentNode.removeChild(miniMap._container);
    document.getElementById('minimap').appendChild(miniMap._container);

    // tiles/bounds.js to display data extract bbox
    if (bounds) {
        var boundsGroup = L.featureGroup(window.bounds);
        boundsGroup.setStyle({
            weight: 2,
            dashArray: '10, 5',
            color: 'black',
            opacity: 1,
            fill: false
        });
        miniMap._miniMap.addLayer(boundsGroup);
    }
}

module.exports.init = init;
<|endoftext|>


<commit_before>var io = require('socket.io'),
    connect = require('connect');

// required to set up custom event emitters.
// this event emitter uses an emit method that is
// unrelated to the socket.io emit method, because
// the events are only sent and received internally
var util = require('util');
var EventEmitter = require('events').EventEmitter;

// more custom event setup.
// this is the CONSTRUCTOR
var PartnerListener = function () {
    this.wakeUp = function ( partnerSocket ) {
        this.emit('wakeUp', partnerSocket );
    }
}
util.inherits( PartnerListener, EventEmitter );

var app = connect().use(connect.static('public')).listen(80);
var chat_room = io.listen(app);

var venters = [];
var listeners = [];

chat_room.sockets.on('connection', function (socket) {
    socket.on('identify', function(data) {
        // venters are true
        // listeners are false
        chattype = data.chattype;

        // who are we chatting with
        var partner;

        // check the opposite queue. if someone is waiting, match them.
        if ( ( chattype ? listeners : venters ).length > 0 ){
            // get the first partner from the array, assign it, and slice it
            // FIFO FTW
            queuedPartner = ( chattype ? listeners : venters ).shift();
            partner = queuedPartner.partnerSocket
            socket.emit('entrance', {
                message: "You're now connected to a " + (!chattype ? 'venter' : 'listener') + "."
            });
            // now we can set up actual chat events.
            setUpChatEvents();

            // and let our partner know to set up actual chat events.
            // wakeUp() forces the wakeup event on the listener object
            queuedPartner.partnerListener.wakeUp( socket );
        } else {
            // if no one is waiting, we add a custom event listener so we know when we're matched with a partner.
            var partnerListener = new PartnerListener();
            // then we add ourselves to the queue, sending a reference to the event listener with it
            ( chattype ? venters : listeners ).push({ 'partnerSocket': socket, 'partnerListener': partnerListener });
            socket.emit('entrance', {
                message: "We're finding you a " + ( !chattype ? 'venter' : 'listener' ) + "."
            });

            partnerListener.once('wakeUp', function ( partnerSocket ) {
                partner = partnerSocket;
                socket.emit('foundpartner', {
                    message: "You're now connected to a " + (chattype ? 'venter' : 'listener') + "."
                });
                setUpChatEvents();
            });

        }

        // relies on partner being in scope
        function setUpChatEvents() {

            socket.on('chat', function (data) {
                partner.emit('chat', {
                    message: data.message
                });
            });

            socket.on('typing', function (data) {
                partner.emit('is typing', {
                    message: data.message
                });
            });

            socket.on('clearedtextfield', function () {
                partner.emit('clearedtextfield');
            });

            socket.on('stoppedtyping', function (data) {
                partner.emit('stopped', {
                    message: data.message
                });
            });
        }
    });

    socket.on('disconnect', function () {
        socket.broadcast.emit('exit', {
            message: 'Your partner has disconnected.'
        });
    });
});
<commit_msg>Bug fixes<commit_after>var io = require('socket.io'),
    connect = require('connect');

// required to set up custom event emitters.
// this event emitter uses an emit method that is
// unrelated to the socket.io emit method, because
// the events are only sent and received internally
var util = require('util');
var EventEmitter = require('events').EventEmitter;

// more custom event setup.
// this is the CONSTRUCTOR
var PartnerListener = function () {
    this.wakeUp = function ( partnerSocket ) {
        this.emit('wakeUp', partnerSocket );
    }
}
util.inherits( PartnerListener, EventEmitter );

var app = connect().use(connect.static('public')).listen(80);
var chat_room = io.listen(app);

var venters = [];
var listeners = [];

chat_room.sockets.on('connection', function (socket) {
    socket.on('identify', function(data) {
        // venters are true
        // listeners are false
        chattype = data.chattype;

        // who are we chatting with
        var partner;

        // check the opposite queue. if someone is waiting, match them.
        if ( ( chattype ? listeners : venters ).length > 0 ){
            // get the first partner from the array, assign it, and slice it
            // FIFO FTW
            queuedPartner = ( chattype ? listeners : venters ).shift();
            partner = queuedPartner.partnerSocket
            socket.emit('entrance', {
                message: "You're now connected to a " + (!chattype ? 'venter' : 'listener') + "."
            });
            // now we can set up actual chat events.
            setUpChatEvents();

            // and let our partner know to set up actual chat events.
            // wakeUp() forces the wakeup event on the listener object
            queuedPartner.partnerListener.wakeUp( socket );
        } else {
            // if no one is waiting, we add a custom event listener so we know when we're matched with a partner.
            var partnerListener = new PartnerListener();
            // then we add ourselves to the queue, sending a reference to the event listener with it
            ( chattype ? venters : listeners ).push({ 'partnerSocket': socket, 'partnerListener': partnerListener });
            socket.emit('entrance', {
                message: "We're finding you a " + ( !chattype ? 'venter' : 'listener' ) + "."
            });

            partnerListener.once('wakeUp', function ( partnerSocket ) {
                partner = partnerSocket;
                socket.emit('foundpartner', {
                    message: "You're now connected to a " + (chattype ? 'venter' : 'listener') + "."
                });
                setUpChatEvents();
            });

        }

        // relies on partner being in scope
        function setUpChatEvents() {

            socket.on('chat', function (data) {
                partner.emit('chat', {
                    message: data.message
                });
            });

            socket.on('typing', function (data) {
                partner.emit('is typing', {
                    message: data.message
                });
            });

            socket.on('clearedtextfield', function () {
                partner.emit('clearedtextfield');
            });

            socket.on('stoppedtyping', function (data) {
                partner.emit('stopped', {
                    message: data.message
                });
            });

            socket.on('disconnect', function () {
                partner.emit('exit', {
                    message: 'Your partner has disconnected.'
                });
            });
        }
    });

});
<|endoftext|>


<commit_before>//Require Module Dependencies
var hapi = require('hapi'),
	mongoose = require('mongoose'),
	Path =  require('path'),
	socketio = require('socket.io');
//Require Imports
var routes = require('./app/routes'),
	configDB = require('./config/database.js'),
	Crypter = require('./app/utils/crypting.js');

mongoose.connect(configDB.url);
mongoose.connection.on('disconnected', function() { console.log("disconnected from db...");});

var serverOptions =
{
	views :
	{
		engines :
		{
			html : require('handlebars')
		},
		basePath : __dirname,
		path : './views'
	}
}
var host = 'localhost';
var port = Number(process.env.PORT || 5000);
var server = hapi.createServer(port, serverOptions);
routes(server);

var groups = {};
server.start(function ()
{
	var io = socketio.listen(server.listener);
	io.on('connection', function (socket)
	{
		socket.on('join', function (groupId)
		{
			if (groups[groupId] == undefined)
			{
				groups[groupId] = groupId;
			}
			socket.join(groupId, function ()
			{

			});
		});
		socket.on('send message', function (data)
		{
			io.sockets. in (data.groupId).emit('send message', { 'message': data.message, 'sender': Crypter.decrypt(data.sender) });
		})
	});

	console.log('Server started on port: ' + port);
});

<commit_msg>-Implemented Orchestrate (along with the test ping function)<commit_after>//Require Module Dependencies
var hapi = require('hapi'),
	mongoose = require('mongoose'),
	Path =  require('path'),
	socketio = require('socket.io'),
	orchestrate = require('orchestrate')('2bfb3d34-cfd7-4649-b0dc-80c31b391ed9');
//Require Imports
var routes = require('./app/routes'),
	configDB = require('./config/database.js'),
	Crypter = require('./app/utils/crypting.js');

mongoose.connect(configDB.url);
mongoose.connection.on('disconnected', function() { console.log("disconnected from db...");});

orchestrate.ping()
.then(function()
{
	console.log("Orchestrate ping successful");
})
.fail(function(err)
{
	console.log("Orchestrate ping failed");
})

var serverOptions =
{
	views :
	{
		engines :
		{
			html : require('handlebars')
		},
		basePath : __dirname,
		path : './views'
	}
}
var host = 'localhost';
var port = Number(process.env.PORT || 5000);
var server = hapi.createServer(port, serverOptions);
routes(server);

var groups = {};
server.start(function ()
{
	var io = socketio.listen(server.listener);
	io.on('connection', function (socket)
	{
		socket.on('join', function (groupId)
		{
			if (groups[groupId] == undefined)
			{
				groups[groupId] = groupId;
			}
			socket.join(groupId, function ()
			{

			});
		});
		socket.on('send message', function (data)
		{
			io.sockets. in (data.groupId).emit('send message', { 'message': data.message, 'sender': Crypter.decrypt(data.sender) });
		})
	});

	console.log('Server started on port: ' + port);
});

<|endoftext|>


<commit_before>var C = 15;
var colors = require('./colors.js');
var mapCX = 1000;
var mapCY = 1000;

module.exports = {
  levelObjects:{
  	playerStart: {x: 50, y: 60},
  	levelFinish:{x: 1000, y: 1000}
  },
  gems: [
//GEM 1
    {
      position : {x: C + 25, y:(mapCY/4) * 3},
      color: colors.red
    },
//GEM 2
    {
      position : {x: 3*(mapCX/8), y:50 + C},
      color: colors.blue
    },
//GEM 3
    {
      position : {x: (3*(mapCX/4)) + C, y:(mapCY/4) * 3},
      color: colors.green
    }
  ],
  walls: [
//LINE 1
    {
      position : {x: mapCX/4, y: mapCY/2},
      spatial: {x : 1*C, y: mapCY/2},
      color: colors.red
    },
//LINE 2
    {
      position : {x: mapCX/2, y: mapCY/2},
      spatial: {x : 1*C, y: mapCY/2},
      color: colors.blue
    },
//SQUARE
    {
      position : {x: (3*(mapCX/4)), y: (mapCY/3)},
      spatial: {x : 6*C, y: 1*C},
      color: colors.green
    },
    {
      position : {x: (3*(mapCX/4))-7*C, y: (mapCY/3)+6*C},
      spatial: {x : 1*C, y: 7*C},
      color: colors.green
    },
    {
      position : {x: (3*(mapCX/4)), y: (mapCY/3)+12*C},
      spatial: {x : 6*C, y: 1*C},
      color: colors.green
    },
    {
      position : {x: (3*(mapCX/4))+7*C, y: (mapCY/3)+6*C},
      spatial: {x : 1*C, y: 7*C},
      color: colors.green
    },

//START
    {
      position : {x: C + 25, y:50 + C},
      spatial: {x : C, y: C},
      color: colors.green
    },
  ]
};
<commit_msg>player start + whitespace cleanup<commit_after>var C = 15;
var colors = require('./colors.js');
var mapCX = 1000;
var mapCY = 1000;

module.exports = {
  levelObjects:{
    playerStart: {x: C + 25, y: 50 + C},
    levelFinish:{x: 1000, y: 1000}
  },
  gems: [
    //GEM 1
    {
      position : {x: C + 25, y:(mapCY/4) * 3},
      color: colors.red
    },
    //GEM 2
    {
      position : {x: 3*(mapCX/8), y:50 + C},
      color: colors.blue
    },
    //GEM 3
    {
      position : {x: (3*(mapCX/4)) + C, y:(mapCY/4) * 3},
      color: colors.green
    }
  ],
  walls: [
    //LINE 1
    {
      position : {x: mapCX/4, y: mapCY/2},
      spatial: {x : 1*C, y: mapCY/2},
      color: colors.red
    },
    //LINE 2
    {
      position : {x: mapCX/2, y: mapCY/2},
      spatial: {x : 1*C, y: mapCY/2},
      color: colors.blue
    },
    //SQUARE
    {
      position : {x: (3*(mapCX/4)), y: (mapCY/3)},
      spatial: {x : 6*C, y: 1*C},
      color: colors.green
    },
    {
      position : {x: (3*(mapCX/4))-7*C, y: (mapCY/3)+6*C},
      spatial: {x : 1*C, y: 7*C},
      color: colors.green
    },
    {
      position : {x: (3*(mapCX/4)), y: (mapCY/3)+12*C},
      spatial: {x : 6*C, y: 1*C},
      color: colors.green
    },
    {
      position : {x: (3*(mapCX/4))+7*C, y: (mapCY/3)+6*C},
      spatial: {x : 1*C, y: 7*C},
      color: colors.green
    },

  ]
};
<|endoftext|>