<commit_before>'use strict'; // dont touch
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch
// [General]
this.name = "Statistics"; // Name of plugin REQUIRED
this.author = "LegitSoulja"; // author REQUIRED
this.description = 'Register Server Statistics'; // Desciprtion
this.compatVersion = ''; // compatable with (optional)
this.version = '1.0.0'; // version REQUIRED
this.addToHelp[1] = "stats      : Amounts of times your server updated stats";
this.commandName[1] = "stats";
this.command[1] = function(gameServer, config) {
    say("Checks > " + checks);
    return;
};
// INSERT PLUGIN BELOW
const fs = require('fs');
const http = require('http');
const request = require('request');
this.config = {
    serverName: "New Server",
    alerts: 1
};
this.configfile = 'config.ini';
var checks = 0;
var sendOut = {
    serverName: "New Server",
    serverBots: 0,
    serverPort: 0,
    gamemode: 0,
    statPort: 0,
    serverPlayers: 0,
    gameUID: "",
    recentPlayer: "null",
    ip: ""
};
var enabled = false;
// [Functions]
this.init = function(gameServer, config) {
    this.gameServer = gameServer;
    this.config = config;
    // check network
    require('dns')
        .resolve('www.google.com', function(err) {
            if (err) {
                say("No network connectivity for Statistics");
                return;
            }
        });
    checkUpdate(this.version, function(callback) {

        if (callback) {
            say("Preparing update..");
            var uc = [];
            uc[1] = "update";
            uc[2] = "Statistics";
            gameServer.consoleService.execCommand("plugin", uc);
            return;

        }else{

            say("No recent updates :)");
            enabled = true;
            function refresh() {
                getIP(function(callback) {
                    sendOut.ip = callback.toString();
                });
                getPlayers(gameServer, function(callback) {
                    sendOut.serverPlayers = callback;
                });
                getBots(gameServer, function(callback) {
                    sendOut.serverBots = callback;
                });
                sendOut.serverName = config.serverName;
                sendOut.gameUID = gameServer.uid;
                sendOut.serverPort = gameServer.config.serverPort;
                sendOut.statPort = gameServer.config.serverStatsPort;
                sendOut.gamemode = gameServer.config.serverGamemode;
                checkUpdate();
                setTimeout(function() {
                    //console.log(JSON.stringify({data: sendOut}));
                    request.post('http://stats.ogarul.tk/grab.php', {
                        form: {
                            hash: JSON.stringify({
                                data: sendOut
                            })
                        }
                    }, function(e, r, b) {
                        if (e) {
                            console.log("Could not send data");
                        }
                        else {
                            if (b) {
                                if (config.alerts === 1) {
                                    say(b);
                                }
                            }
                        }
                    });
                }, 5000);
                return;
            }
            setInterval(function() {
                refresh();
            }, 10000);
            refresh();

        }
    });

};
this.beforespawn = function(player) {
    if(enabled)
        if (typeof player.socket.remoteAddress != 'undefined') {
            sendOut.recentPlayer = player.name;
        }
        return true;
};
var checkUpdate = function(version, callback) {
    request("http://raw.githubusercontent.com/AJS-development/OgarUL-Plugin-Library/master/Statistics/version.json", function(e, r, b) {
        if(callback && typeof(callback) == 'function'){

        var parse = JSON.parse(b);
        if (parse.version !== version) {
            console.log("Found new update " + version + " > " + parse.version);
            return callback(true);
        }
        return callback(false);

        }
    });
};
var getPlayers = function(gameServer, callback) {
    var players = 0;
    for (var i in gameServer.clients) {
        if (typeof gameServer.clients[i].remoteAddress != 'undefined') {
            players++;
        }
    }
    return callback(players);
};
var getBots = function(gameServer, callback) {
    var bots = 0;
    for (var i in gameServer.clients) {
        if (typeof gameServer.clients[i].remoteAddress == 'undefined') {
            bots++;
        }
    }
    return callback(bots);
};
var getIP = function(callback) {
    request("http://stats.ogarul.tk/getip.php", function(e, r, b) {
        if (!e) {
            var p = JSON.parse(b);
            return callback(p.ip);
        }
    });
    return;
};
this.onsecond = function(gameServer) {};
var say = function(log, gameServer) {
    console.log("[Statistics] " + log);
    return;
};
module.exports = this; // dont touch
<commit_msg>Update index.js<commit_after>'use strict'; // dont touch
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch
// [General]
this.name = "Statistics"; // Name of plugin REQUIRED
this.author = "LegitSoulja"; // author REQUIRED
this.description = 'Register Server Statistics'; // Desciprtion
this.compatVersion = ''; // compatable with (optional)
this.version = '1.0.1'; // version REQUIRED
this.addToHelp[1] = "stats      : Amounts of times your server updated stats";
this.commandName[1] = "stats";
this.command[1] = function(gameServer, config) {
    say("Checks > " + checks);
    return;
};
// INSERT PLUGIN BELOW
const fs = require('fs');
const http = require('http');
const request = require('request');
this.config = {
    serverName: "New Server",
    alerts: 1
};
this.configfile = 'config.ini';
var checks = 0;
var sendOut = {
    serverName: "New Server",
    serverBots: 0,
    serverPort: 0,
    gamemode: 0,
    statPort: 0,
    serverPlayers: 0,
    gameUID: "",
    recentPlayer: "null",
    ip: ""
};
var enabled = false;
// [Functions]
this.init = function(gameServer, config) {
    this.gameServer = gameServer;
    this.config = config;
    // check network
    require('dns')
        .resolve('www.google.com', function(err) {
            if (err) {
                say("No network connectivity for Statistics");
                return;
            }
        });
    checkUpdate(this.version, function(callback) {

        if (callback) {
            say("Preparing update..");
            var uc = [];
            uc[1] = "update";
            uc[2] = "Statistics";
            gameServer.consoleService.execCommand("plugin", uc);
            return;

        }else{

            say("No recent updates :)");
            enabled = true;
            function refresh() {
                getIP(function(callback) {
                    sendOut.ip = callback.toString();
                });
                getPlayers(gameServer, function(callback) {
                    sendOut.serverPlayers = callback;
                });
                getBots(gameServer, function(callback) {
                    sendOut.serverBots = callback;
                });
                sendOut.serverName = config.serverName;
                sendOut.gameUID = gameServer.uid;
                sendOut.serverPort = gameServer.config.serverPort;
                sendOut.statPort = gameServer.config.serverStatsPort;
                sendOut.gamemode = gameServer.config.serverGamemode;
                checkUpdate();
                setTimeout(function() {
                    //console.log(JSON.stringify({data: sendOut}));
                    request.post('http://stats.ogarul.tk/grab.php', {
                        form: {
                            hash: JSON.stringify({
                                data: sendOut
                            })
                        }
                    }, function(e, r, b) {
                        if (e) {
                            console.log("Could not send data");
                        }
                        else {
                            if (b) {
                                if (config.alerts === 1) {
                                    say(b);
                                }
                            }
                        }
                    });
                }, 5000);
                return;
            }
            setInterval(function() {
                refresh();
            }, 10000);
            refresh();

        }
    });

};
this.beforespawn = function(player) {
    if(enabled)
        if (typeof player.socket.remoteAddress != 'undefined') {
            sendOut.recentPlayer = player.name;
        }
        return true;
};
var checkUpdate = function(version, callback) {
    request("http://raw.githubusercontent.com/AJS-development/OgarUL-Plugin-Library/master/Statistics/version.json", function(e, r, b) {
        if(callback && typeof(callback) == 'function'){

        var parse = JSON.parse(b);
        if (parse.version !== version) {
            console.log("Found new update " + version + " > " + parse.version);
            return callback(true);
        }
        return callback(false);

        }
    });
};
var getPlayers = function(gameServer, callback) {
    var players = 0;
    for (var i in gameServer.clients) {
        if (typeof gameServer.clients[i].remoteAddress != 'undefined') {
            players++;
        }
    }
    return callback(players);
};
var getBots = function(gameServer, callback) {
    var bots = 0;
    for (var i in gameServer.clients) {
        if (typeof gameServer.clients[i].remoteAddress == 'undefined') {
            bots++;
        }
    }
    return callback(bots);
};
var getIP = function(callback) {
    request("http://stats.ogarul.tk/getip.php", function(e, r, b) {
        if (!e) {
            var p = JSON.parse(b);
            return callback(p.ip);
        }
    });
    return;
};
this.onsecond = function(gameServer) {};
var say = function(log, gameServer) {
    console.log("[Statistics] " + log);
    return;
};
module.exports = this; // dont touch
<|endoftext|>


<commit_before>$(document).ready(function() {
	var limit = 60;
	var template = Handlebars.compile($("#items-template").html());
	var $loading = $("#wrap_loading");
	var $grid = $("#grid");
	var infiniteGridService = new eg.InfiniteGridService($grid);

	function getOffset(pos) {
		var offset = 0;

		if (pos === "first") {
			offset = $("#grid").find(".item").first().data("offset");
			offset = parseInt(offset, 10) - limit;
		} else if (pos === "last") {
			offset = $("#grid").find(".item").last().data("offset");
			offset = parseInt(offset, 10) + 1;
		}
		return offset;
	};

	/*
	 아이템의 <a> 클릭시 persist 데이터를 저장
	 */
	$grid.on("click", "a", function() {
		infiniteGridService.store();
	});

	infiniteGridService.on({
		/*
		 "append" 이벤트 핸들러
		 스크롤 다운 중 최하단 아이템이 화면에 보여질 때(threshold로 보정 가능)
		 threshold가 300이면 최하단 아이템이 화면에 보여지기 300px 전에 이벤트 발생
		 로딩바를 보이고 appendAjax 메소드를 호출해 서버에 데이터를 요청함
		 응답데이터를 #grid에 append 함
		 */
		"append" : function() {
			var html = template(data.getItems(getOffset("last"), limit));
			infiniteGridService.append(html);
		},
		/*
		 "preppend" 이벤트 핸들러
		 스크롤 업 중 최상단 아이템이 화면에 보여질 때(threshold로 보정 가능)
		 threshold가 300이면 최하단 아이템이 화면에 보여지기 300px 전에 이벤트 발생
		 로딩바를 보이고 prependAjax 메소드를 호출해 서버에 데이터를 요청
		 응답데이터가 #grid에 preppend 되고 스크롤 위치가 보정
		 */
		"prepend" : function() {
			var offset = getOffset("first");
			if (offset > 0) {
				var html = template(data.getItems(offset, limit));
				infiniteGridService.prepend(html);
			}
		},
		/*
		 "layoutComplete" 이벤트 핸들러
		 append, preppend가 완료되면 발생
		 이벤트 파라미터를 통해 append인지 prepend인지 확인 가능
		 로딩바 감춤
		 */
		"layoutComplete" : function(e) {
			$loading.hide();
		}
	});

	/*
	 persist 데이터를 복원함
	 복원하지 못한다면 새로운 데이터 추가
	 */
	if (!infiniteGridService.restore()) {
		var html = template(data.getItems(1, limit));
		infiniteGridService.append(html);
	}
});<commit_msg>update style<commit_after>$(document).ready(function() {
	// 컨텐츠의 위치를 찾는 함수
	function getOffset(pos) {
		var offset = 0;
		if (pos === "first") {
			offset = $grid.find(".item").first().data("offset");
			offset = parseInt(offset, 10) - limit;
		} else if (pos === "last") {
			offset = $grid.find(".item").last().data("offset");
			offset = parseInt(offset, 10) + 1;
		}
		return offset;
	};

	var limit = 60;
	var template = Handlebars.compile($("#items-template").html());
	var $loading = $("#wrap_loading");
	var $grid = $("#grid");
	var infiniteGridService = new eg.InfiniteGridService($grid).on({
		/*
		 "append" 이벤트 핸들러
		 스크롤 다운 중 최하단 아이템이 화면에 보여질 때(threshold로 보정 가능)
		 threshold가 300이면 최하단 아이템이 화면에 보여지기 300px 전에 이벤트 발생
		 응답데이터를 #grid에 append 함
		 */
		"append" : function() {
			var html = template(data.getItems(getOffset("last"), limit));
			infiniteGridService.append(html);
		},
		/*
		 "preppend" 이벤트 핸들러
		 스크롤 업 중 최상단 아이템이 화면에 보여질 때(threshold로 보정 가능)
		 threshold가 300이면 최하단 아이템이 화면에 보여지기 300px 전에 이벤트 발생
		 응답데이터가 #grid에 preppend 되고 스크롤 위치가 보정
		 */
		"prepend" : function() {
			var offset = getOffset("first");
			if (offset > 0) {
				var html = template(data.getItems(offset, limit));
				infiniteGridService.prepend(html);
			}
		},
		/*
		 "layoutComplete" 이벤트 핸들러
		 append, preppend가 완료되면 발생
		 이벤트 파라미터를 통해 append인지 prepend인지 확인 가능
		 로딩바 감춤
		 */
		"layoutComplete" : function(e) {
			$loading.hide();
		}
	});

	/*
	 아이템의 <a> 클릭시 persist 데이터를 저장
	 */
	$grid.on("click", "a", function() {
		infiniteGridService.store();
	});

	/*
	 persist 데이터를 복원함
	 복원하지 못한다면 새로운 데이터 추가
	 */
	if (!infiniteGridService.restore()) {
		var html = template(data.getItems(1, limit));
		infiniteGridService.append(html);
	}
});<|endoftext|>


<commit_before>(function() {
'use strict';

var ids = [
	'essay',
	'blog',
	'story_content',
	'body-content',
	'story_content',
	'storyContent',
	'contentBody',
	'hldcontent',
	'contentColumn',
	'content',
	'article-container',
	'articleFullText',
	'main_text',
	'main',
	'Blog1',
	'constrictor',
	'pageLeftColumn'
];

var stripAll = function(tag) {
	var elements = document.getElementsByTagName(tag);
	elements = Array.prototype.slice.call(elements);
	elements.forEach(function(element){
		element.parentNode.removeChild(element);
	});

};

var clearStyle = function(element) {
	if (element) {
		element.className = '';
		element.removeAttribute('style');
	}
};

var stripToJust = function(element, after) {
	var parentNode = element.parentNode,
	children = parentNode.childNodes,
	nc = children.length,
	i, child, toDelete = [];

	for (i=0; i<nc; ++i) {
		child = children[i];
		if (child !== element) {
			toDelete.push(child);
		}
	}

	toDelete.map(function(node) {
		parentNode.removeChild(node);
	});

	clearStyle(parentNode);
	if (parentNode.parentNode && parentNode !== document.body) {
		stripToJust(parentNode, true);
	}

	if (after) {
		clearStyle(document.body);
		stripAll('link');
		stripAll('style');
	}
};

var styleBody = function() {
	document.body.style.fontSize = '14pt';
	document.body.style.lineHeight = '1.5em';
	document.body.style.maxWidth = '40em';
	document.body.style.margin = '0 auto';
	document.body.style.background = 'none';
};

var articles = document.getElementsByTagName('article');
var content, i;

for (i=0; i<ids.length; ++i) {
	content = document.getElementById(ids[i]);
	if (content) {
		break;
	}
}

var filterOutListItemArticles = function (articles) {
	var filtered = [];
	var article = null;
	var i=0;

	for (i=0; i<articles.length; ++i) {
		article = articles[i];
		switch(article.parentNode.tagName) {
			case 'LI':
			case 'ASIDE':
				break;
			default:
				filtered.push(article);
				break;
		}
	}

	return filtered;
};

var largestArticle = function (articles) {
	articles.sort(function(a, b){return b.clientWidth-a.clientWidth;});
	return articles[0];
};

if (articles.length > 1) {
	articles = filterOutListItemArticles(articles);
}
switch (articles.length) {
	case 0:
	if (content) {
		stripToJust(content);
	}
	break;
	case 1:
		stripToJust(articles[0]);
		break;
	default:
		stripToJust(largestArticle(articles));
		break;
}
window.zapIt = stripToJust;
styleBody();

})();<commit_msg>Updated to cope with re-design of http://www.sitepoint.com added code to enable debugging if you add #debug-ps to the page URL before clicking the Page Shaver bookmarklet.<commit_after>(function() {
'use strict';

if (window.location.hash === '#debug-ps') {
    /*jshint debug:true */
    debugger;
}

var ids = [
	'essay',
	'blog',
	'story_content',
	'body-content',
	'story_content',
	'storyContent',
	'contentBody',
	'hldcontent',
	'contentColumn',
	'content',
	'article-container',
	'articleFullText',
	'main_text',
	'main',
	'Blog1',
	'constrictor',
	'pageLeftColumn'
];

var classes = [
    'ArticleCopy' // www.sitepoint.com
];

var stripAll = function(tag) {
	var elements = document.getElementsByTagName(tag);
	elements = Array.prototype.slice.call(elements);
	elements.forEach(function(element){
		element.parentNode.removeChild(element);
	});

};

var clearStyle = function(element) {
	if (element) {
		element.className = '';
		element.removeAttribute('style');
	}
};

var stripToJust = function(element, after) {
	var parentNode = element.parentNode,
	children = parentNode.childNodes,
	nc = children.length,
	i, child, toDelete = [];

	for (i=0; i<nc; ++i) {
		child = children[i];
		if (child !== element) {
			toDelete.push(child);
		}
	}

	toDelete.map(function(node) {
		parentNode.removeChild(node);
	});

	clearStyle(parentNode);
	if (parentNode.parentNode && parentNode !== document.body) {
		stripToJust(parentNode, true);
	}

	if (after) {
		clearStyle(document.body);
		stripAll('link');
		stripAll('style');
	}
};

var styleBody = function() {
	document.body.style.fontSize = '14pt';
	document.body.style.lineHeight = '1.5em';
	document.body.style.maxWidth = '40em';
	document.body.style.margin = '0 auto';
	document.body.style.background = 'none';
};

var articles = document.getElementsByTagName('article');
var content, i;

for (i=0; i<ids.length; ++i) {
	content = document.getElementById(ids[i]);
	if (content) {
		break;
	}
}

var filterOutListItemArticles = function (articles) {
	var filtered = [];
	var article = null;
	var i=0;

	for (i=0; i<articles.length; ++i) {
		article = articles[i];
		switch(article.parentNode.tagName) {
			case 'LI':
			case 'ASIDE':
				break;
			default:
				filtered.push(article);
				break;
		}
	}

	return filtered;
};

var largestArticle = function (articles) {
	articles.sort(function(a, b){return b.clientWidth-a.clientWidth;});
	return articles[0];
};

if (articles.length > 1) {
	articles = filterOutListItemArticles(articles);
}

var findByClasses = function() {

    for (var i=0; i<classes.length; ++i) {
        var elements = document.getElementsByClassName(classes[i]);
        if (elements.length === 1) {
            return elements[i];
        }
    }
};

switch (articles.length) {
	case 0:
	if (content) {
		stripToJust(content);
	} else {
        content = findByClasses();
        if (content) {
            stripToJust(content);
        }
    }
	break;
	case 1:
		stripToJust(articles[0]);
		break;
	default:
        stripToJust(largestArticle(articles));
		break;
}

window.zapIt = stripToJust;
styleBody();

})();
<|endoftext|>


<commit_before>
function Route(sourceMAC, targetMAC, deployRate = 1) {
  this.sourceMAC = sourceMAC;
  this.targetMAC = targetMAC;
  this.deployRate = deployRate;

  this.sendCount = 0;
  this.receivedCount = 0;
  this.receivedStepCount = 0;
  this.efficiency = 0;

  this.reset = function reset() {
    this.sendCount = 0;
    this.receivedCount = 0;
    this.receivedStepCount = 0;
    this.efficiency = 0;
  }
}

function createSim(graph) {
  var self = {};

  self.sim_steps_total = 0;
  self.sim_duration = 0;
  self.routes = {};

  function shuffleArray(a) {
    for (let i = a.length; i; i--) {
      let j = Math.floor(Math.random() * i);
      [a[i - 1], a[j]] = [a[j], a[i - 1]];
    }
  }

  self.reset = function reset() {
    var intNodes = graph.getIntNodes();
    for (var i = 0; i < intNodes.length; i++) {
      intNodes[i].o.reset();
    }

    for (var id in routes) {
      routes[id].reset();
    }

    self.sim_steps_total = 0;
    self.sim_duration = 0;

    updateSimStatistics();
  }

  function updateSimStatistics() {
    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();

    var packetsBroadcastCount = 0;
    var packetsUnicastCount = 0;
    var routesSendCount = 0;
    var routesReceivedCount = 0;
    var routesTransitCount = 0;
    var routesCount = 0;

    var routing_efficiency_sum = 0;
    var routing_efficiency_count = 0;

    function countPackets(packet) {
      if (packet.destinationMAC === BROADCAST_MAC) {
        packetsBroadcastCount += 1;
      } else {
        packetsUnicastCount += 1;

        var id = packet.sourceMAC + '=>' + packet.destinationMAC;
        routesTransitCount += (id in self.routes);
      }
    }

    for (var i in intNodes) {
      var node = intNodes[i].o;
      node.incoming.forEach(countPackets);
      node.outgoing.forEach(countPackets);
    }

    for (var id in self.routes) {
      var route = self.routes[id];
      routesCount += 1;
      routesSendCount += route.sendCount;
      routesReceivedCount += route.receivedCount;

      if (!isNaN(route.efficiency)) {
        routing_efficiency_sum += route.efficiency;
        routing_efficiency_count += 1;
      }
      // console.log(route.sourceMAC + ' => ' + route.targetMAC + ', e: ' + e);
    }

    // Convert to medium percent
    var routingEfficiency = 100 * routing_efficiency_sum / routing_efficiency_count;

    $$('sim_steps_total').nodeValue = self.sim_steps_total;
    $$('sim_duration').nodeValue = (self.sim_duration / 1000);

    $$('packets_unicast_count').nodeValue = packetsUnicastCount
    $$('packets_broadcast_count').nodeValue = packetsBroadcastCount;

    function percent(value) {
      var p = (100 * value / routesSendCount);
      return isNaN(p) ? '' : (' (' + p + '%)');
    };

    $$('routes_count').nodeValue = routesCount;
    $$('routes_packets_send').nodeValue = routesSendCount;
    $$('routes_packets_received').nodeValue = routesReceivedCount + percent(routesReceivedCount);
    $$('routes_packets_transit').nodeValue = routesTransitCount + percent(routesTransitCount);
    var routesLostCount = (routesSendCount - routesReceivedCount - routesTransitCount);
    $$('routes_packets_lost').nodeValue = routesLostCount + percent(routesLostCount);

    $$('routing_efficiency').nodeValue = routingEfficiency;
  }

  function append(parent, name, content = '') {
    var e = document.createElement(name);
    if (content.length) {
      var text = document.createTextNode(content)
      e.appendChild(text);
    }
    parent.appendChild(e);
    return e;
  }

  function updateRoutesTable() {
    var tbody = $('sim_routes');

    // Remove all elements
    while (tbody.firstChild) {
      tbody.removeChild(tbody.firstChild);
    }

    for (key in self.routes) {
      var route = self.routes[key];
      var tr = append(tbody, 'tr');
      var source_td = append(tr, 'td', route.sourceMAC.slice(-5));
      var target_td = append(tr, 'td', route.targetMAC.slice(-5));
      append(tr, 'td', route.deployRate.toString());
      append(tr, 'td', route.sendCount.toString());
      append(tr, 'td', route.receivedCount.toString());
      append(tr, 'td', route.efficiency.toString() + '%');

      source_td.title = route.sourceMAC
      target_td.title = route.targetMAC;
    }
  }

  self.delRoutes = function delRoutes() {
    function delRoute(sourceNode, targetNode) {
      var id = sourceNode.mac + '=>' + targetNode.mac;
      delete routes[id];
      updateSimStatistics();
    }

    var intNodes = graph.getSelectedIntNodes();
    if (intNodes.length == 0) {
      alert('Select one source and at least one target node.');
      return;
    }

    var sourceNode = intNodes[0].o;
    for (var i = 1; i < intNodes.length; i += 1) {
      var targetNode = intNodes[i].o;
      delRoute(sourceNode, targetNode);
    }
    updateRoutesTable();
  }

  self.addRoutes = function addRoutes() {
    function addRoute(sourceNode, targetNode) {
      var id = sourceMAC + '=>' + targetMAC;
      if (!(id in self.routes)) {
        self.routes[id] = new Route(sourceMAC, targetMAC, 1);
        updateSimStatistics();
      }
    }

    var intNodes = graph.getSelectedIntNodes();
    if (intNodes.length == 0) {
      alert('Select one source and at least one target node.');
      return;
    }

    var sourceMAC = intNodes[0].o.mac;
    for (var i = 1; i < intNodes.length; i += 1) {
      var targetMAC = intNodes[i].o.mac;
      addRoute(sourceMAC, targetMAC);
    }
    updateRoutesTable();
  }

  function deployPackets_() {
    var nodes = graph.getIntNodes();
    var nodeMap = {};
    nodes.forEach(function(e) {
      nodeMap[e.o.mac] = e.o;
    });

    for (var id in self.routes) {
      var route = self.routes[id];
      if (randomBoolean(route.deployRate)) {
        var srcMAC = route.sourceMAC;
        var dstMAC = route.targetMAC;
        nodeMap[srcMAC].incoming.push(
          new Packet(srcMAC, srcMAC, srcMAC, dstMAC, self.sim_steps_total)
        );
        route.sendCount += 1
      }
    }

    updateRoutesTable();
    updateSimStatistics();
  }

  self.deployPackets = function deployPackets() {
    deployPackets_();
    graph.redraw();
  }

  function updateRouteEfficiency() {
    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();
    var dijkstra = createDijkstra(intNodes, intLinks);

    for (var id in self.routes) {
      var route = self.routes[id];
      var sourceIntNode = intNodes.find(function(e) { return e.o.mac === route.sourceMAC; });
      var targetIntNode = intNodes.find(function(e) { return e.o.mac === route.targetMAC; });
      var shortestDistance = dijkstra.getShortestDistance(sourceIntNode, targetIntNode);
      /*
      * Efficiency as rate of optimal step count weighted by rate of received packets.
      * This means packets in transit are counted as lost packets.
      */
      route.efficiency = (route.receivedStepCount / (route.receivedCount * shortestDistance)) * (route.receivedCount / route.sendCount);
    }
  }

  self.step = function step(steps_id, deploy_id) {
    var steps = getInteger(steps_id);
    var deployPacketsEnabled = getBoolean(deploy_id);

    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();

    // Map internal node index to array of link objects
    var connections = {};

    intNodes.forEach(function(n) {
      connections[n.index] = [];
    });

    intLinks.forEach(function(l) {
      connections[l.source.index].push(l);
      connections[l.target.index].push(l);
    });

    function clonePacket(packet) {
      return JSON.parse(JSON.stringify(packet));
    }

    // Get other part of the link
    function getNeighbor(intLink, intNode) {
      return (intLink.source.index !== intNode.index) ? intLink.source : intLink.target;
    }

    var date = new Date();
    var simStartTime = date.getTime();

    // _very_ simple simulation
    var len = intNodes.length;
    for (var step = 0; step < steps; step += 1) {
      self.sim_steps_total += 1;

      if (deployPacketsEnabled) {
        deployPackets_();
      }

      shuffleArray(intNodes);

      // Step nodes
      for (var i = 0; i < len; i++) {
        var intNode = intNodes[i];
        intNode.o.step();
      }

      // Move packets over links
      for (var i = 0; i < len; i++) {
        var intNode = intNodes[i];
        var intLinks = connections[intNode.index];
        // Send outgoing packets over links
        for (var p = 0; p < intNode.o.outgoing.length; p++) {
          var packet = intNode.o.outgoing[p];
          if (packet.dstMAC === BROADCAST_MAC) {
            // Handle broadcast packet
            // Send cloned apcket to all neighbors
            for (var k = 0; k < intLinks.length; k++) {
              var intLink = intLinks[k];
              var intNeigh = getNeighbor(intLink, intNode);
              packet = clonePacket(packet);

              if (randomBoolean(intLink.quality / 100)) {
                intNeigh.o.incoming.push(packet);
              } else {
                // Packet is lost
              }
            }
          } else {
            // Handle unicast packet
            var targetFound = false;
            // Send to one neighbor
            for (var k = 0; k < intLinks.length; k++) {
              var intLink = intLinks[k];
              var intNeigh = getNeighbor(intLink, intNode);
              if (packet.dstMAC === intNeigh.o.mac) {
                targetFound = true;
                if (randomBoolean(intLink.quality / 100)) {
                  intNeigh.o.incoming.push(packet);
                  // Update route stats if packet reached final destination
                  if (packet.destinationMAC === intNeigh.o.mac) {
                    var id = packet.sourceMAC + '=>' + packet.destinationMAC;
                    if (id in self.routes) {
                      var route = self.routes[id];
                      route.receivedCount += 1;
                      route.receivedStepCount += (self.sim_steps_total - packet.step);
                    }
                  }
                }
                break;
              }

              if (!targetFound) {
                console.log('packet lost because next target not found: ' + packet.dstMAC);
              }
            }
          }
        }

        // All packets should have been handled
        intNode.o.outgoing = [];
      }
    }

    self.sim_duration = date.getTime() - simStartTime;

    updateRouteEfficiency();
    updateSimStatistics();

    graph.redraw();
  }

  return self;
}<commit_msg>fix efficiency nan display<commit_after>
function Route(sourceMAC, targetMAC, deployRate = 1) {
  this.sourceMAC = sourceMAC;
  this.targetMAC = targetMAC;
  this.deployRate = deployRate;

  this.sendCount = 0;
  this.receivedCount = 0;
  this.receivedStepCount = 0;
  this.efficiency = NaN;

  this.reset = function reset() {
    this.sendCount = 0;
    this.receivedCount = 0;
    this.receivedStepCount = 0;
    this.efficiency = NaN;
  }
}

function createSim(graph) {
  var self = {};

  self.sim_steps_total = 0;
  self.sim_duration = 0;
  self.routes = {};

  function shuffleArray(a) {
    for (let i = a.length; i; i--) {
      let j = Math.floor(Math.random() * i);
      [a[i - 1], a[j]] = [a[j], a[i - 1]];
    }
  }

  self.reset = function reset() {
    var intNodes = graph.getIntNodes();
    for (var i = 0; i < intNodes.length; i++) {
      intNodes[i].o.reset();
    }

    for (var id in self.routes) {
      self.routes[id].reset();
    }

    self.sim_steps_total = 0;
    self.sim_duration = 0;

    updateSimStatistics();
  }

  function num(v, suffix = '') {
    return isNaN(v) ? '-' : (v.toString() + suffix);
  }

  function updateSimStatistics() {
    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();

    var packetsBroadcastCount = 0;
    var packetsUnicastCount = 0;
    var routesSendCount = 0;
    var routesReceivedCount = 0;
    var routesTransitCount = 0;
    var routesCount = 0;

    var routing_efficiency_sum = 0;
    var routing_efficiency_count = 0;

    function countPackets(packet) {
      if (packet.destinationMAC === BROADCAST_MAC) {
        packetsBroadcastCount += 1;
      } else {
        packetsUnicastCount += 1;

        var id = packet.sourceMAC + '=>' + packet.destinationMAC;
        routesTransitCount += (id in self.routes);
      }
    }

    for (var i in intNodes) {
      var node = intNodes[i].o;
      node.incoming.forEach(countPackets);
      node.outgoing.forEach(countPackets);
    }

    for (var id in self.routes) {
      var route = self.routes[id];
      routesCount += 1;
      routesSendCount += route.sendCount;
      routesReceivedCount += route.receivedCount;

      if (!isNaN(route.efficiency)) {
        routing_efficiency_sum += route.efficiency;
        routing_efficiency_count += 1;
      }
    }

    // Convert to medium percent
    var routingEfficiency = 100 * routing_efficiency_sum / routing_efficiency_count;

    $$('sim_steps_total').nodeValue = self.sim_steps_total;
    $$('sim_duration').nodeValue = (self.sim_duration / 1000);

    $$('packets_unicast_count').nodeValue = packetsUnicastCount
    $$('packets_broadcast_count').nodeValue = packetsBroadcastCount;

    function percent(value) {
      var p = (100 * value / routesSendCount);
      return isNaN(p) ? '' : (' (' + p + '%)');
    };

    $$('routes_count').nodeValue = routesCount;
    $$('routes_packets_send').nodeValue = routesSendCount;
    $$('routes_packets_received').nodeValue = routesReceivedCount + percent(routesReceivedCount);
    $$('routes_packets_transit').nodeValue = routesTransitCount + percent(routesTransitCount);
    var routesLostCount = (routesSendCount - routesReceivedCount - routesTransitCount);
    $$('routes_packets_lost').nodeValue = routesLostCount + percent(routesLostCount);

    $$('routing_efficiency').nodeValue = num(routingEfficiency);
  }

  function append(parent, name, content = '') {
    var e = document.createElement(name);
    if (content.length) {
      var text = document.createTextNode(content)
      e.appendChild(text);
    }
    parent.appendChild(e);
    return e;
  }

  function updateRoutesTable() {
    var tbody = $('sim_routes');

    // Remove all elements
    while (tbody.firstChild) {
      tbody.removeChild(tbody.firstChild);
    }

    for (key in self.routes) {
      var route = self.routes[key];
      var tr = append(tbody, 'tr');
      var source_td = append(tr, 'td', route.sourceMAC.slice(-5));
      var target_td = append(tr, 'td', route.targetMAC.slice(-5));
      append(tr, 'td', route.deployRate.toString());
      append(tr, 'td', route.sendCount.toString());
      append(tr, 'td', route.receivedCount.toString());
      append(tr, 'td', num(route.efficiency, '%'));

      source_td.title = route.sourceMAC
      target_td.title = route.targetMAC;
    }
  }

  self.delRoutes = function delRoutes() {
    function delRoute(sourceNode, targetNode) {
      var id = sourceNode.mac + '=>' + targetNode.mac;
      delete routes[id];
      updateSimStatistics();
    }

    var intNodes = graph.getSelectedIntNodes();
    if (intNodes.length == 0) {
      alert('Select one source and at least one target node.');
      return;
    }

    var sourceNode = intNodes[0].o;
    for (var i = 1; i < intNodes.length; i += 1) {
      var targetNode = intNodes[i].o;
      delRoute(sourceNode, targetNode);
    }
    updateRoutesTable();
  }

  self.addRoutes = function addRoutes() {
    function addRoute(sourceNode, targetNode) {
      var id = sourceMAC + '=>' + targetMAC;
      if (!(id in self.routes)) {
        self.routes[id] = new Route(sourceMAC, targetMAC, 1);
        updateSimStatistics();
      }
    }

    var intNodes = graph.getSelectedIntNodes();
    if (intNodes.length == 0) {
      alert('Select one source and at least one target node.');
      return;
    }

    var sourceMAC = intNodes[0].o.mac;
    for (var i = 1; i < intNodes.length; i += 1) {
      var targetMAC = intNodes[i].o.mac;
      addRoute(sourceMAC, targetMAC);
    }
    updateRoutesTable();
  }

  function deployPackets_() {
    var nodes = graph.getIntNodes();
    var nodeMap = {};
    nodes.forEach(function(e) {
      nodeMap[e.o.mac] = e.o;
    });

    for (var id in self.routes) {
      var route = self.routes[id];
      if (randomBoolean(route.deployRate)) {
        var srcMAC = route.sourceMAC;
        var dstMAC = route.targetMAC;
        nodeMap[srcMAC].incoming.push(
          new Packet(srcMAC, srcMAC, srcMAC, dstMAC, self.sim_steps_total)
        );
        route.sendCount += 1
      }
    }

    updateRoutesTable();
    updateSimStatistics();
  }

  self.deployPackets = function deployPackets() {
    deployPackets_();
    graph.redraw();
  }

  function updateRouteEfficiency() {
    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();
    var dijkstra = createDijkstra(intNodes, intLinks);

    for (var id in self.routes) {
      var route = self.routes[id];
      var sourceIntNode = intNodes.find(function(e) { return e.o.mac === route.sourceMAC; });
      var targetIntNode = intNodes.find(function(e) { return e.o.mac === route.targetMAC; });
      var shortestDistance = dijkstra.getShortestDistance(sourceIntNode, targetIntNode);
      /*
      * Efficiency as rate of optimal step count weighted by rate of received packets.
      * This means packets in transit are counted as lost packets.
      */
      route.efficiency = (route.receivedStepCount / (route.receivedCount * shortestDistance)) * (route.receivedCount / route.sendCount);
    }
  }

  self.step = function step(steps_id, deploy_id) {
    var steps = getInteger(steps_id);
    var deployPacketsEnabled = getBoolean(deploy_id);

    var intNodes = graph.getIntNodes();
    var intLinks = graph.getIntLinks();

    // Map internal node index to array of link objects
    var connections = {};

    intNodes.forEach(function(n) {
      connections[n.index] = [];
    });

    intLinks.forEach(function(l) {
      connections[l.source.index].push(l);
      connections[l.target.index].push(l);
    });

    function clonePacket(packet) {
      return JSON.parse(JSON.stringify(packet));
    }

    // Get other part of the link
    function getNeighbor(intLink, intNode) {
      return (intLink.source.index !== intNode.index) ? intLink.source : intLink.target;
    }

    var date = new Date();
    var simStartTime = date.getTime();

    // _very_ simple simulation
    var len = intNodes.length;
    for (var step = 0; step < steps; step += 1) {
      self.sim_steps_total += 1;

      if (deployPacketsEnabled) {
        deployPackets_();
      }

      shuffleArray(intNodes);

      // Step nodes
      for (var i = 0; i < len; i++) {
        var intNode = intNodes[i];
        intNode.o.step();
      }

      // Move packets over links
      for (var i = 0; i < len; i++) {
        var intNode = intNodes[i];
        var intLinks = connections[intNode.index];
        // Send outgoing packets over links
        for (var p = 0; p < intNode.o.outgoing.length; p++) {
          var packet = intNode.o.outgoing[p];
          if (packet.dstMAC === BROADCAST_MAC) {
            // Handle broadcast packet
            // Send cloned apcket to all neighbors
            for (var k = 0; k < intLinks.length; k++) {
              var intLink = intLinks[k];
              var intNeigh = getNeighbor(intLink, intNode);
              packet = clonePacket(packet);

              if (randomBoolean(intLink.quality / 100)) {
                intNeigh.o.incoming.push(packet);
              } else {
                // Packet is lost
              }
            }
          } else {
            // Handle unicast packet
            var targetFound = false;
            // Send to one neighbor
            for (var k = 0; k < intLinks.length; k++) {
              var intLink = intLinks[k];
              var intNeigh = getNeighbor(intLink, intNode);
              if (packet.dstMAC === intNeigh.o.mac) {
                targetFound = true;
                if (randomBoolean(intLink.quality / 100)) {
                  intNeigh.o.incoming.push(packet);
                  // Update route stats if packet reached final destination
                  if (packet.destinationMAC === intNeigh.o.mac) {
                    var id = packet.sourceMAC + '=>' + packet.destinationMAC;
                    if (id in self.routes) {
                      var route = self.routes[id];
                      route.receivedCount += 1;
                      route.receivedStepCount += (self.sim_steps_total - packet.step);
                    }
                  }
                }
                break;
              }

              if (!targetFound) {
                console.log('packet lost because next target not found: ' + packet.dstMAC);
              }
            }
          }
        }

        // All packets should have been handled
        intNode.o.outgoing = [];
      }
    }

    self.sim_duration = date.getTime() - simStartTime;

    updateRouteEfficiency();
    updateSimStatistics();

    graph.redraw();
  }

  return self;
}<|endoftext|>


<commit_before>require('dotenv').config();

const path = require('path');
const merge = require('webpack-merge');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const FaviconPlugin = require('favicons-webpack-plugin');
const HtmlPlugin = require('html-webpack-plugin');
const VueSSRClientPlugin = require('vue-server-renderer/client-plugin');
const SWPrecachePlugin = require('sw-precache-webpack-plugin');

const baseConfig = require('./webpack.base');
const createClientEnvironment = require('./env');

const rootPath = path.join(__dirname, '../../');

const isProduction = env => env.NODE_ENV === 'production';

module.exports = (env = process.env) => {
  const config = merge(baseConfig(env), {
    devtool: isProduction(env) ? 'source-map' : 'eval-source-map',
    plugins: [
      new webpack.DefinePlugin(createClientEnvironment(Object.assign(env, {
        VUE_ENV: 'client',
      }))),
      new CopyWebpackPlugin([
        {
          from: path.join(rootPath, 'static'),
          to: path.join(rootPath, 'dist/public'),
        },
      ]),
      new webpack.optimize.UglifyJsPlugin({
        compress: isProduction(env) ? { warnings: false } : false,
      }),
      new webpack.optimize.OccurrenceOrderPlugin(),
      new FaviconPlugin({
        logo: './internals/templates/favicon.png',
        prefix: 'icons/',
        persistentCache: true,
        inject: true,
        background: '#fff',
        title: 'NUSWhispers',
        icons: {
          android: isProduction(env),
          appleIcon: isProduction(env),
          appleStartup: false,
          coast: false,
          favicons: true,
          firefox: isProduction(env),
          windows: isProduction(env),
          yandex: isProduction(env),
        },
      }),
      new HtmlPlugin({
        filename: '../index.template.html',
        template: './internals/templates/index.hbs',
        inject: true,
        minify: {
          removeComments: false,
          collapseWhitespace: isProduction(env),
          removeAttributeQuotes: isProduction(env),
        },
        chunksSortMode: 'dependency',
        excludeChunks: ['app', 'vendor'], // Handled by vue-server-renderer.
      }),
      new VueSSRClientPlugin(),
    ],
  });

  if (isProduction(env)) {
    config.plugins.push(
      // Split vendor into its own file.
      new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        minChunks: module =>
          // Any required modules inside node_modules are extracted to vendor.
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(path.join(__dirname, '../node_modules')) === 0,
      }),
      // Extract webpack runtime and module manifest to its own file in order to
      // prevent vendor hash from being updated whenever app bundle is updated.
      new webpack.optimize.CommonsChunkPlugin({
        name: 'manifest',
        chunks: ['vendor'],
        minChunks: Infinity,
      }),
      new SWPrecachePlugin({
        cacheId: 'nuswhispers-vue',
        filename: 'service-worker.js',
        dontCacheBustUrlsMatching: /./,
        staticFileGlobsIgnorePatterns: [/index\.template\.html$/, /\.json$/, /\.map$/],
        runtimeCaching: [
          {
            urlPattern: /^https:\/\/www\.nuswhispers\.com\/api/,
            handler: 'networkFirst',
          },
          {
            urlPattern: '/',
            handler: 'networkFirst',
          },
          {
            urlPattern: /\/(latest|popular|success|policy)/,
            handler: 'networkFirst',
          },
          {
            urlPattern: '/confession/:id',
            handler: 'networkFirst',
          },
          {
            urlPattern: '/category/:id',
            handler: 'networkFirst',
          },
          {
            urlPattern: '/tag/:id',
            handler: 'networkFirst',
          },
          {
            urlPattern: '/search/:id',
            handler: 'networkFirst',
          },
        ],
      })
    );
  }

  return config;
};
<commit_msg>Remove OccurrenceOrderPlugin<commit_after>require('dotenv').config();

const path = require('path');
const merge = require('webpack-merge');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const FaviconPlugin = require('favicons-webpack-plugin');
const HtmlPlugin = require('html-webpack-plugin');
const VueSSRClientPlugin = require('vue-server-renderer/client-plugin');
const SWPrecachePlugin = require('sw-precache-webpack-plugin');

const baseConfig = require('./webpack.base');
const createClientEnvironment = require('./env');

const rootPath = path.join(__dirname, '../../');

const isProduction = env => env.NODE_ENV === 'production';

module.exports = (env = process.env) => {
  const config = merge(baseConfig(env), {
    devtool: isProduction(env) ? 'source-map' : 'eval-source-map',
    plugins: [
      new webpack.DefinePlugin(createClientEnvironment(Object.assign(env, {
        VUE_ENV: 'client',
      }))),
      new CopyWebpackPlugin([
        {
          from: path.join(rootPath, 'static'),
          to: path.join(rootPath, 'dist/public'),
        },
      ]),
      new webpack.optimize.UglifyJsPlugin({
        compress: isProduction(env) ? { warnings: false } : false,
      }),
      new FaviconPlugin({
        logo: './internals/templates/favicon.png',
        prefix: 'icons/',
        persistentCache: true,
        inject: true,
        background: '#fff',
        title: 'NUSWhispers',
        icons: {
          android: isProduction(env),
          appleIcon: isProduction(env),
          appleStartup: false,
          coast: false,
          favicons: true,
          firefox: isProduction(env),
          windows: isProduction(env),
          yandex: isProduction(env),
        },
      }),
      new HtmlPlugin({
        filename: '../index.template.html',
        template: './internals/templates/index.hbs',
        inject: true,
        minify: {
          removeComments: false,
          collapseWhitespace: isProduction(env),
          removeAttributeQuotes: isProduction(env),
        },
        chunksSortMode: 'dependency',
        excludeChunks: ['app', 'vendor'], // Handled by vue-server-renderer.
      }),
      new VueSSRClientPlugin(),
    ],
  });

  if (isProduction(env)) {
    config.plugins.push(
      // Split vendor into its own file.
      new webpack.optimize.CommonsChunkPlugin({
        name: 'vendor',
        minChunks: module =>
          // Any required modules inside node_modules are extracted to vendor.
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(path.join(__dirname, '../node_modules')) === 0,
      }),
      // Extract webpack runtime and module manifest to its own file in order to
      // prevent vendor hash from being updated whenever app bundle is updated.
      new webpack.optimize.CommonsChunkPlugin({
        name: 'manifest',
        chunks: ['vendor'],
        minChunks: Infinity,
      }),
      new SWPrecachePlugin({
        cacheId: 'nuswhispers-vue',
        filename: 'service-worker.js',
        dontCacheBustUrlsMatching: /./,
        staticFileGlobsIgnorePatterns: [/index\.template\.html$/, /\.json$/, /\.map$/],
        runtimeCaching: [
          {
            urlPattern: /^https:\/\/www\.nuswhispers\.com\/api/,
            handler: 'networkFirst',
          },
          {
            urlPattern: '/',
            handler: 'networkFirst',
          },
          {
            urlPattern: /\/(latest|popular|success|policy)/,
            handler: 'networkFirst',
          },
          {
            urlPattern: '/confession/:id',
            handler: 'networkFirst',
          },
          {
            urlPattern: '/category/:id',
            handler: 'networkFirst',
          },
          {
            urlPattern: '/tag/:id',
            handler: 'networkFirst',
          },
          {
            urlPattern: '/search/:id',
            handler: 'networkFirst',
          },
        ],
      })
    );
  }

  return config;
};
<|endoftext|>


<commit_before>function TimeSeriesChart() {

    this.create = function(element) {

        var series = {};

        var margin = {top: 20, right: 20, bottom: 30, left: 50},
            width = 900 - margin.left - margin.right,
            height = 300 - margin.top - margin.bottom;

        var accessDatetime = function(d) { return d.datetime; };
        var accessValue = function(d) { return d.value; };

        var xScale = d3.time.scale.utc()
            .range([0, width]);

        var yScale = d3.scale.linear()
            .range([height, 0]);

        var xAxis = d3.svg.axis()
            .scale(xScale)
            .orient("bottom");

        var yAxis = d3.svg.axis()
            .scale(yScale)
            .orient("left");

        var line =  d3.svg.line()
            .interpolate("line")
            .x(function(d) { return xScale(d.datetime); })
            .y(function(d) { return yScale(d.value); });

        var lineX =  d3.svg.line()
            .interpolate("line")
            .x(function(d) { return xScale(d.datetime); })
            .y(function(d) { return yScale.range()[0]; });

        // create chart and bind to element
        // var svg = d3.select(element).append("svg")
        //         .attr("width", width + margin.left + margin.right)
        //         .attr("height", height + margin.top + margin.bottom)
        //     .append("g")
        //         .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        /* http://stackoverflow.com/questions/16265123/resize-svg-when-window-is-resized-in-d3-js */
        var svg = d3.select(element)//.append("svg")
            // .append("div")
            .classed("svg-container", true) //container class to make it responsive
            .append("svg")
            //responsive SVG needs these 2 attributes and no width and height attr
            .attr("preserveAspectRatio", "xMinYMin meet")
            .attr("viewBox", "0 0 900 300")
            //class to make it responsive
            .classed("svg-content-responsive", true)//;
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        var chartXAxis = svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);

        var chartYAxis = svg.append("g")
            .attr("class", "y axis")
            .call(yAxis);

        /**
         * Update chart for all series
         */
        var chartUpdate = function() {
            updateChartAxis();
            updateDate();
        };

        var updateChartAxis = function() {

            // calculate extent for each series
            var extentsDatetime = [];
            var extentsValue = [];
            for (var key in series) {
                if (series.hasOwnProperty(key)) {
                    var ser = series[key];
                    extentsDatetime.push(d3.extent(ser, accessDatetime));
                    extentsValue.push(d3.extent(ser, accessValue));
                }
            }

            // select global min/max from all extents
            var min_datetime = d3.min(extentsDatetime, function(d){ return d[0]});
            var max_datetime = d3.max(extentsDatetime, function(d){ return d[1]});
            var min_value = d3.min(extentsValue, function(d){ return d[0]});
            var max_value = d3.max(extentsValue, function(d){ return d[1]});

            // update chart scales
            xScale.domain([min_datetime, max_datetime]);
            yScale.domain([min_value, max_value]);

            // update chart
            chartXAxis.call(xAxis);
            chartYAxis.call(yAxis);
        };

        var updateDate = function() {

            var data = [];
            for (var key in series) {
                if (series.hasOwnProperty(key)) {
                    data.push({ key: key, values: series[key] });
                }
            }

            var path = svg.selectAll("path").data(data, function(k,i) {
                return k.key;
            });

            path.enter().append("path")
                  // .attr("d", function(d) { return line(d.values) })
                  .attr("class", function(d) { return "line " + d.key } )
                  .attr("d", function(d) { return lineX(d.values) });

            path.transition().duration(500)
                .attr("d", function(d) { return line(d.values) } );

            path.exit().remove();
        };

        return {

            //
            addSeries: function(series_id, label, data) {

                if (series[series_id]) {
                    console.warn('Replacing series [' + series_id + '] with a new data!');
                }
                series[series_id] = data;
                chartUpdate();

                // svg.append("g")
                //     .attr("class", "x axis")
                //     .attr("transform", "translate(0," + height + ")")
                //     .call(xAxis);

                // chartXAxis.call(xAxis);

                // svg.append("g")
                //     .attr("class", "y axis")
                //     .call(yAxis);
                    // .append("text")
                    // .attr("transform", "rotate(-90)")
                    // .attr("y", 6)
                    // .attr("dy", ".71em")
                    // .style("text-anchor", "end")
                    // .text("Temperature (ºF)");
                // chartYAxis.call(yAxis);

                // var city = svg.selectAll(".series")
                //     .data(data)
                //     .enter().append("g")
                //     .attr("class", "series");
            },

            //
            disableSeries: function(series_id) {
                console.error("disableSeries method not implemented yet!");
            },

            //
            enableSeries: function(series_id) {
                console.error("enableSeries method not implemented yet!");
            }
        };
    }

}

// Make our chart globally available
window._TimeSeriesChart = new TimeSeriesChart();<commit_msg>Add transition to axes as well.<commit_after>function TimeSeriesChart() {

    this.create = function(element) {

        var series = {};

        var margin = {top: 20, right: 20, bottom: 30, left: 50},
            width = 900 - margin.left - margin.right,
            height = 300 - margin.top - margin.bottom;

        var accessDatetime = function(d) { return d.datetime; };
        var accessValue = function(d) { return d.value; };

        var xScale = d3.time.scale.utc()
            .range([0, width]);

        var yScale = d3.scale.linear()
            .range([height, 0]);

        var xAxis = d3.svg.axis()
            .scale(xScale)
            .orient("bottom");

        var yAxis = d3.svg.axis()
            .scale(yScale)
            .orient("left");

        var line =  d3.svg.line()
            .interpolate("line")
            .x(function(d) { return xScale(d.datetime); })
            .y(function(d) { return yScale(d.value); });

        var lineX =  d3.svg.line()
            .interpolate("line")
            .x(function(d) { return xScale(d.datetime); })
            .y(function(d) { return yScale.range()[0]; });

        // create chart and bind to element
        // var svg = d3.select(element).append("svg")
        //         .attr("width", width + margin.left + margin.right)
        //         .attr("height", height + margin.top + margin.bottom)
        //     .append("g")
        //         .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        /* http://stackoverflow.com/questions/16265123/resize-svg-when-window-is-resized-in-d3-js */
        var svg = d3.select(element)//.append("svg")
            // .append("div")
            .classed("svg-container", true) //container class to make it responsive
            .append("svg")
            //responsive SVG needs these 2 attributes and no width and height attr
            .attr("preserveAspectRatio", "xMinYMin meet")
            .attr("viewBox", "0 0 900 300")
            //class to make it responsive
            .classed("svg-content-responsive", true)//;
            .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        var chartXAxis = svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);

        var chartYAxis = svg.append("g")
            .attr("class", "y axis")
            .call(yAxis);

        /**
         * Update chart for all series
         */
        var chartUpdate = function() {
            updateChartAxis();
            updateDate();
        };

        var updateChartAxis = function() {

            // calculate extent for each series
            var extentsDatetime = [];
            var extentsValue = [];
            for (var key in series) {
                if (series.hasOwnProperty(key)) {
                    var ser = series[key];
                    extentsDatetime.push(d3.extent(ser, accessDatetime));
                    extentsValue.push(d3.extent(ser, accessValue));
                }
            }

            // select global min/max from all extents
            var min_datetime = d3.min(extentsDatetime, function(d){ return d[0]});
            var max_datetime = d3.max(extentsDatetime, function(d){ return d[1]});
            var min_value = d3.min(extentsValue, function(d){ return d[0]});
            var max_value = d3.max(extentsValue, function(d){ return d[1]});

            // update chart scales
            xScale.domain([min_datetime, max_datetime]);
            yScale.domain([min_value, max_value]);

            // update chart
            chartXAxis.transition().duration(500).call(xAxis);
            chartYAxis.transition().duration(500).call(yAxis);
        };

        var updateDate = function() {

            var data = [];
            for (var key in series) {
                if (series.hasOwnProperty(key)) {
                    data.push({ key: key, values: series[key] });
                }
            }

            var path = svg.selectAll("path").data(data, function(k,i) {
                return k.key;
            });

            path.enter().append("path")
                  // .attr("d", function(d) { return line(d.values) })
                  .attr("class", function(d) { return "line " + d.key } )
                  .attr("d", function(d) { return lineX(d.values) });

            path.transition().duration(500)
                .attr("d", function(d) { return line(d.values) } );

            path.exit().remove();
        };

        return {

            //
            addSeries: function(series_id, label, data) {

                if (series[series_id]) {
                    console.warn('Replacing series [' + series_id + '] with a new data!');
                }
                series[series_id] = data;
                chartUpdate();

                // svg.append("g")
                //     .attr("class", "x axis")
                //     .attr("transform", "translate(0," + height + ")")
                //     .call(xAxis);

                // chartXAxis.call(xAxis);

                // svg.append("g")
                //     .attr("class", "y axis")
                //     .call(yAxis);
                    // .append("text")
                    // .attr("transform", "rotate(-90)")
                    // .attr("y", 6)
                    // .attr("dy", ".71em")
                    // .style("text-anchor", "end")
                    // .text("Temperature (ºF)");
                // chartYAxis.call(yAxis);

                // var city = svg.selectAll(".series")
                //     .data(data)
                //     .enter().append("g")
                //     .attr("class", "series");
            },

            //
            disableSeries: function(series_id) {
                console.error("disableSeries method not implemented yet!");
            },

            //
            enableSeries: function(series_id) {
                console.error("enableSeries method not implemented yet!");
            }
        };
    }

}

// Make our chart globally available
window._TimeSeriesChart = new TimeSeriesChart();<|endoftext|>


<commit_before>/* global Zepto, document, EJS, context, ejsTemplate, TextMate */
/* global error_explanations */

Zepto(document).ready(function($) {
  // Remove the marker flag indicating that the validation window
  // for this document is showing.
  $(document).on('visibilitychange', function() {
    if (document.hidden && ('markerFile' in context) && context.markerFile) {
      TextMate.system('/bin/rm "' + context.markerFile + '"');
    }
  });

  // close the report window when the user presses ESCape
  $(document).keydown(function(e) {
    if (e.keyCode === 27) {
      e.preventDefault();
      var cmd = '"tell application \\"System Events\\" ' +
        'to keystroke \\"w\\" using command down"';
      TextMate.system('osascript -e ' + cmd, function(){});
    }
  });

  // render the template and inject it into the page
  var html = new EJS({text: ejsTemplate}).render(context);
  $('#content').html(html);

  // add links to error/warning codes, when available
  $('.issue-code').each(function(index, item) {
    var issueCode = $(item).text();
    if (error_explanations.hasOwnProperty(issueCode)) {
      var url = error_explanations[issueCode];
      $(item).wrap('');
    }
  });

  // By default, links will open in the TextMate results window. If
  // the  tag has class "open-external" we’ll catch it and open
  // the link in the user’s browser instead.
  $('.open-external').on('click', function(e) {
    e.preventDefault();
    var href = $(this).attr('href');
    if (!href.match(/^http(?:s?)\:\/\/[^\/]/)) {
      // doesn’t look like a normal URL
      return;
    }
    TextMate.system('open "' + encodeURI(href) + '"', null);
  });
});
<commit_msg>fix freeze when closing report shown in a pane<commit_after>/* global Zepto, document, EJS, context, ejsTemplate, TextMate, window */
/* global error_explanations */

Zepto(document).ready(function($) {
  // Remove the marker flag indicating that the validation window
  // for this document is showing.
  $(document).on('visibilitychange', function() {
    window.setTimeout(function() {
      if (document.hidden && ('markerFile' in context) && context.markerFile) {
        TextMate.system('/bin/rm "' + context.markerFile + '"');
      }
    }, 1);
  });

  // close the report window when the user presses ESCape
  $(document).keydown(function(e) {
    if (e.keyCode === 27) {
      e.preventDefault();
      var cmd = '"tell application \\"System Events\\" ' +
        'to keystroke \\"w\\" using command down"';
      TextMate.system('osascript -e ' + cmd, function(){});
    }
  });

  // render the template and inject it into the page
  var html = new EJS({text: ejsTemplate}).render(context);
  $('#content').html(html);

  // add links to error/warning codes, when available
  $('.issue-code').each(function(index, item) {
    var issueCode = $(item).text();
    if (error_explanations.hasOwnProperty(issueCode)) {
      var url = error_explanations[issueCode];
      $(item).wrap('');
    }
  });

  // By default, links will open in the TextMate results window. If
  // the  tag has class "open-external" we’ll catch it and open
  // the link in the user’s browser instead.
  $('.open-external').on('click', function(e) {
    e.preventDefault();
    var href = $(this).attr('href');
    if (!href.match(/^http(?:s?)\:\/\/[^\/]/)) {
      // doesn’t look like a normal URL
      return;
    }
    TextMate.system('open "' + encodeURI(href) + '"', null);
  });
});
<|endoftext|>


<commit_before>'use strict'

angular.module('ludwigApp')
  .controller('AccountCtrl', function ($scope, $state, LoginService, RepositoryService) {
    LoginService.get()
      .then(function (user) {
        if (!user) {
          return $state.go('layout.home')
        }

        $scope.user = user
        RepositoryService.getCandidates()
          .then(function (repositories) {
            $scope.candidates = repositories.filter(function (repo) {
              return $scope.user.repositories.indexOf(repo.full_name) < 0
            })
          })
      })

    $scope.logout = function () {
      LoginService.delete()
        .then(function () {
          $state.go('layout.home')
        })
    }

    $scope.activateRepository = RepositoryService.activateRepository
  })
<commit_msg>Improve front to prevent double activation<commit_after>'use strict'

angular.module('ludwigApp')
  .controller('AccountCtrl', function ($scope, $state, LoginService, RepositoryService) {
    LoginService.get()
      .then(function (user) {
        if (!user) {
          return $state.go('layout.home')
        }

        $scope.user = user
        RepositoryService.getCandidates()
          .then(function (repositories) {
            $scope.candidates = repositories.filter(function (repo) {
              return $scope.user.repositories.indexOf(repo.full_name) < 0
            })
          })
      })

    $scope.logout = function () {
      LoginService.delete()
        .then(function () {
          $state.go('layout.home')
        })
    }

    $scope.activateRepository = function (repository) {
      RepositoryService.activateRepository(repository)
        .then(function (repository) {
          if (repository.error) {
            return
          }

          $scope.user.repositories.push(repository.id)
          var idx = $scope.candidates.findIndex(function (repo) {
            return repo.full_name === repository.id
          })
          if (idx > -1) {
            $scope.candidates.splice(idx, 1)
          }
        })
    }
  })
<|endoftext|>


<commit_before>
/**
 * AJAX: FETCH CONTENT FOR DESCRIPTION
 * @param externalSource  either "Wikipedia" or "Europeana"
 */
function wpunity_fetchDescriptionAjaxFrontEnd( externalSource, title, description_dom ){

    //document.getElementById('wpunity_fetchDescription_bt').innerHTML = "Fetching";
    //externalSource = document.getElementById("fetch_source").options[document.getElementById("fetch_source").selectedIndex].value;
    //lang document.getElementById("fetch_lang").options[document.getElementById("fetch_lang").selectedIndex].value;

    // Replace empty spaces with underscores
    var title =   title.replace(new RegExp(" ", 'g'),"_"); // document.getElementById("wpunity_titles_search").value.replace(" ","%20");

    var lang = "en";

    for (var j=0; j< title.length; j++)
        if ( title.charCodeAt(j) > 902 && title.charCodeAt(j) < 974 ){
             lang = "el";
             break;
        }

    var fulltext = '';

    var reqCompile = jQuery.ajax({
        url : my_ajax_object_fetch_content.ajax_url,
        type : 'POST',
        data : {'action': 'wpunity_fetch_description_action',
            'lang':           lang,
            'externalSource': externalSource,
            'titles':         title,
            'fulltext':       fulltext},

        success : function(response) {

//            console.log(response);

            var json_content = jQuery.parseJSON(response);

            if (json_content) {

                if (externalSource === 'Wikipedia') {

                    if (json_content.query) {
                        for (key in json_content.query.pages) {
                            if (json_content.query.pages[key].extract) {

                                description_dom['multi-line'].value = json_content.query.pages[key].extract.trim();

                                description_dom[1].style.display = 'none';
                            } else {
                                //tinymce.activeEditor.setContent(json_content.query.pages[key].extract.trim());

                                    console.log("Nothing found 151");
                                    alert("Nothing found in Wikipedia");

                                    //tinymce.activeEditor.setContent(response);

                            }
                        }
                    }
                } else if (externalSource === 'Europeana') {

                    console.log(json_content);

                    if(json_content.items.length > 0 ){

                        for (var l=0; l<json_content.items.length; l++) {

                            description_dom['multi-line'].value += '---------- ' + l +  ' -----------';
                            description_dom['multi-line'].value += '\n';

                            if (json_content.items[l].title !== '') {
                                description_dom['multi-line'].value += JSON.stringify(json_content.items[l].title[0]);

                                description_dom['multi-line'].value += '\n';
                                description_dom['multi-line'].value += '\n';
                            }

                            if (json_content.items[l].edmIsShownAt !== '') {
                                description_dom['multi-line'].value += JSON.stringify(json_content.items[l].edmIsShownAt);

                                description_dom['multi-line'].value += '\n';
                                description_dom['multi-line'].value += '\n';
                            }

                            if (json_content.items[l].dcDescription !== undefined) {
                                description_dom['multi-line'].value += " : " + JSON.stringify(json_content.items[l].dcDescription[0]);

                                description_dom['multi-line'].value += '\n';

                                description_dom['multi-line'].value += '\n';

                            }

                            description_dom[1].style.display = 'none';

                        }

                    } else {

                        console.log("Nothing found 152");
                        alert("Nothing found in Europeana.");

                    }

                    //tinymce.activeEditor.setContent(JSON.stringify(json_content.items));

                }
            }
            //document.getElementById('wpunity_fetchDescription_bt').innerHTML = "Fetch";

        },
        error : function(xhr, ajaxOptions, thrownError){
            console.log("ajaxOptions" + ajaxOptions);
            console.log("ERROR"  + thrownError);
            alert('Error 21: API problems. Fetch again? ' + thrownError);

            //document.getElementById('wpunity_fetchDescription_bt').innerHTML = 'Error 21: Fetch again?' + thrownError;
        }
    });

}

//----------------------------------------------------------------------------------
//  AJAX: FETCH CONTENT FOR DESCRIPTION
//----------------------------------------------------------------------------------
function wpunity_fetchDescriptionAjax(){

    document.getElementById('wpunity_fetchDescription_bt').innerHTML = "Fetching";

    externalSource = document.getElementById("fetch_source").options[document.getElementById("fetch_source").selectedIndex].value;

    var reqCompile = jQuery.ajax({
        url : 'admin-ajax.php',
        type : 'POST',
        data : {'action': 'wpunity_fetch_description_action',
                'lang':           document.getElementById("fetch_lang").options[document.getElementById("fetch_lang").selectedIndex].value,
                'externalSource': externalSource,
                'titles':         document.getElementById("wpunity_titles_search").value.replace(" ","%20"),
                'fulltext':       document.getElementById("wpunity_fulltext_chkbox").checked?'':'exintro=&'},

        success : function(response) {

            console.log(response);

            var json_content = jQuery.parseJSON(response);

            if (json_content) {

                if (externalSource == 'Wikipedia') {

                    if (json_content.query) {
                        for (key in json_content.query.pages) {
                            if (json_content.query.pages[key].extract)
                                tinymce.activeEditor.setContent(json_content.query.pages[key].extract.trim());
                        }
                    } else {
                        console.log("Nothing found 151");

                        tinymce.activeEditor.setContent(response);
                    }
                } else {

                    tinymce.activeEditor.setContent(JSON.stringify(json_content.items));

                }
            }
            document.getElementById('wpunity_fetchDescription_bt').innerHTML = "Fetch";

        },
        error : function(xhr, ajaxOptions, thrownError){
            console.log("ERROR");
            document.getElementById('wpunity_fetchDescription_bt').innerHTML = 'Error 21: Fetch again?' + thrownError;
        }
    });

}

//----------------------------------------------------------------------------------
//  FETCH IMAGES
//----------------------------------------------------------------------------------
function wpunity_fetchImageAjax(){

    document.getElementById('wpunity_fetchImage_bt').innerHTML = "Fetching";

    externalSourceImage = document.getElementById("fetch_source_image").options[document.getElementById("fetch_source_image").selectedIndex].value;

    document.getElementById("wpunity_titles_image_search_image").value = document.getElementById("wpunity_titles_image_search_image").value.replace(/ /g,"+");

    jQuery.ajax({
        url : 'admin-ajax.php',
        type : 'POST',
        data : {'action': 'wpunity_fetch_image_action',
            'lang_image':           document.getElementById("fetch_lang_image").options[document.getElementById("fetch_lang_image").selectedIndex].value,
            'externalSource_image': externalSourceImage,
            'titles_image':         document.getElementById("wpunity_titles_image_search_image").value
            },

        success : function(response) {

//            console.log(response);

            var json_content = jQuery.parseJSON(response);

            if (json_content) {

                document.getElementById('display_img_res').style.display ='';

                if (externalSourceImage == 'Wikipedia') {
                    if (json_content.query) {
                        var j=0;

                        for(key in json_content.query.pages) {
                            for(i=0; i<json_content.query.pages[key].imageinfo.length && j<10; i++) {

                                var fname = json_content.query.pages[key].imageinfo[0].url;
                                var whichimage ='image_res_'+j;

                                console.log(whichimage);

                                document.getElementById(whichimage).src = fname;
                                document.getElementById(whichimage + "_url").innerHTML = ''+fname+'';

                                document.getElementById(whichimage + "_title").innerHTML = 'More info';

                                document.getElementById(whichimage + "_title").href = json_content.query.pages[key].imageinfo[0].descriptionurl;

                                j++;
                            }
                        }
                    } else {
                        console.log("Nothing found 151");
                    }
                } else {

                    if (json_content.itemsCount  > 0) {

                        for(j=0; j<json_content.itemsCount; j++) {

                                var fname = json_content.items[j].edmPreview;

                                console.log(fname);

                                var whichimage ='image_res_'+(j+1);

                                document.getElementById(whichimage).src = fname;
                                document.getElementById(whichimage + "_url").innerHTML = fname;
                            document.getElementById(whichimage + "_title").innerHTML = json_content.items[j].title;

                        }
                    } else {
                        console.log("Nothing found 151");
                    }

                }
            }

            document.getElementById('wpunity_fetchImage_bt').innerHTML = "Fetch";
        },
        error : function(xhr, ajaxOptions, thrownError){
            console.log("ERROR");
            document.getElementById('wpunity_fetchImage_bt').innerHTML = 'Error 22: Fetch again?' + thrownError;
        }
    });

}

//----------------------------------------------------------------------------------
//  FETCH VIDEOS
//----------------------------------------------------------------------------------
function wpunity_fetchVideoAjax(){

    document.getElementById('wpunity_fetchVideo_bt').innerHTML = "Fetching";

    externalSourceVideo = document.getElementById("fetch_source_video").options[document.getElementById("fetch_source_video").selectedIndex].value;

    document.getElementById("wpunity_titles_video_search_video").value = document.getElementById("wpunity_titles_video_search_video").value.replace(/ /g,"_");

    jQuery.ajax({
        url : 'admin-ajax.php',
        type : 'POST',
        data : {'action': 'wpunity_fetch_video_action',
            'lang_video':           document.getElementById("fetch_lang_video").options[document.getElementById("fetch_lang_video").selectedIndex].value,
            'externalSource_video': externalSourceVideo,
            'titles_video':         document.getElementById("wpunity_titles_video_search_video").value
        },

        success : function(response) {

            console.log(response);

            var json_content = jQuery.parseJSON(response);

            if (json_content) {
                if (externalSourceVideo == 'Wikipedia') {
                    if (json_content.query) {
                        var j=0;
                        for(key in json_content.query.pages) {
                            j++;
                            console.log(json_content.query.pages[key].videoinfo[0].derivatives);
                            for(i=0; i<1; i++) {
                                var fname = json_content.query.pages[key].videoinfo[0].derivatives[0].src;

                                var whichvideo ='video_res_'+j;

                                console.log(whichvideo, document.getElementById(whichvideo));

                                document.getElementById(whichvideo).src = fname;
                                document.getElementById("videoplayer1").load();

                                document.getElementById(whichvideo + "_url").innerHTML = ''+fname+'';;

                                document.getElementById(whichvideo + "_title").innerHTML = "----";

                            }
                        }
                    } else {
                        console.log("Nothing found 151");
                    }
                } else {

                    if (json_content.itemsCount  > 0) {

                        for(j=0; j<json_content.itemsCount; j++) {

                            var fname = json_content.items[j].edmPreview;

                            console.log(fname);

                            var whichimage ='image_res_'+(j+1);

                            document.getElementById(whichimage).src = fname;
                            document.getElementById(whichimage + "_url").innerHTML = fname;
                            document.getElementById(whichimage + "_title").innerHTML = json_content.items[j].title;

                        }
                    } else {
                        console.log("Nothing found 151");
                    }

                }
            }

            document.getElementById('wpunity_fetchVideo_bt').innerHTML = "Fetch";
        },
        error : function(xhr, ajaxOptions, thrownError){
            console.log("ERROR");
            document.getElementById('wpunity_fetchVideo_bt').innerHTML = 'Error 23: Fetch again?' + thrownError;
        }
    });

}

<commit_msg>- Minors (wikipedia label)<commit_after>
/**
 * AJAX: FETCH CONTENT FOR DESCRIPTION
 * @param externalSource  either "Wikipedia" or "Europeana"
 */
function wpunity_fetchDescriptionAjaxFrontEnd( externalSource, title, description_dom ){

    //document.getElementById('wpunity_fetchDescription_bt').innerHTML = "Fetching";
    //externalSource = document.getElementById("fetch_source").options[document.getElementById("fetch_source").selectedIndex].value;
    //lang document.getElementById("fetch_lang").options[document.getElementById("fetch_lang").selectedIndex].value;

    // Replace empty spaces with underscores
    var title =   title.replace(new RegExp(" ", 'g'),"_"); // document.getElementById("wpunity_titles_search").value.replace(" ","%20");

    var lang = "en";

    for (var j=0; j< title.length; j++)
        if ( title.charCodeAt(j) > 902 && title.charCodeAt(j) < 974 ){
             lang = "el";
             break;
        }

    var fulltext = '';

    var reqCompile = jQuery.ajax({
        url : my_ajax_object_fetch_content.ajax_url,
        type : 'POST',
        data : {'action': 'wpunity_fetch_description_action',
            'lang':           lang,
            'externalSource': externalSource,
            'titles':         title,
            'fulltext':       fulltext},

        success : function(response) {

//            console.log(response);

            var json_content = jQuery.parseJSON(response);

            if (json_content) {

                if (externalSource === 'Wikipedia') {

                    if (json_content.query) {
                        for (key in json_content.query.pages) {
                            if (json_content.query.pages[key].extract) {

                                description_dom['multi-line'].value = "(Wikipedia)" + "\n" + json_content.query.pages[key].extract.trim();

                                description_dom[1].style.display = 'none';
                            } else {
                                //tinymce.activeEditor.setContent(json_content.query.pages[key].extract.trim());

                                    console.log("Nothing found 151");
                                    alert("Nothing found in Wikipedia");

                                    //tinymce.activeEditor.setContent(response);

                            }
                        }
                    }
                } else if (externalSource === 'Europeana') {

                    console.log(json_content);

                    description_dom['multi-line'].value += "(Europeana)" + "\n";

                    if(json_content.items.length > 0 ){

                        for (var l=0; l<json_content.items.length; l++) {

                            description_dom['multi-line'].value += '---------- ' + l +  ' -----------';
                            description_dom['multi-line'].value += '\n';

                            if (json_content.items[l].title !== '') {
                                description_dom['multi-line'].value += JSON.stringify(json_content.items[l].title[0]);

                                description_dom['multi-line'].value += '\n';
                                description_dom['multi-line'].value += '\n';
                            }

                            if (json_content.items[l].edmIsShownAt !== '') {
                                description_dom['multi-line'].value += JSON.stringify(json_content.items[l].edmIsShownAt);

                                description_dom['multi-line'].value += '\n';
                                description_dom['multi-line'].value += '\n';
                            }

                            if (json_content.items[l].dcDescription !== undefined) {
                                description_dom['multi-line'].value += " : " + JSON.stringify(json_content.items[l].dcDescription[0]);

                                description_dom['multi-line'].value += '\n';

                                description_dom['multi-line'].value += '\n';

                            }

                            description_dom[1].style.display = 'none';

                        }

                    } else {

                        console.log("Nothing found 152");
                        alert("Nothing found in Europeana.");

                    }

                    //tinymce.activeEditor.setContent(JSON.stringify(json_content.items));

                }
            }
            //document.getElementById('wpunity_fetchDescription_bt').innerHTML = "Fetch";

        },
        error : function(xhr, ajaxOptions, thrownError){
            console.log("ajaxOptions" + ajaxOptions);
            console.log("ERROR"  + thrownError);
            alert('Error 21: API problems. Fetch again? ' + thrownError);

            //document.getElementById('wpunity_fetchDescription_bt').innerHTML = 'Error 21: Fetch again?' + thrownError;
        }
    });

}

//----------------------------------------------------------------------------------
//  AJAX: FETCH CONTENT FOR DESCRIPTION
//----------------------------------------------------------------------------------
function wpunity_fetchDescriptionAjax(){

    document.getElementById('wpunity_fetchDescription_bt').innerHTML = "Fetching";

    externalSource = document.getElementById("fetch_source").options[document.getElementById("fetch_source").selectedIndex].value;

    var reqCompile = jQuery.ajax({
        url : 'admin-ajax.php',
        type : 'POST',
        data : {'action': 'wpunity_fetch_description_action',
                'lang':           document.getElementById("fetch_lang").options[document.getElementById("fetch_lang").selectedIndex].value,
                'externalSource': externalSource,
                'titles':         document.getElementById("wpunity_titles_search").value.replace(" ","%20"),
                'fulltext':       document.getElementById("wpunity_fulltext_chkbox").checked?'':'exintro=&'},

        success : function(response) {

            console.log(response);

            var json_content = jQuery.parseJSON(response);

            if (json_content) {

                if (externalSource == 'Wikipedia') {

                    if (json_content.query) {
                        for (key in json_content.query.pages) {
                            if (json_content.query.pages[key].extract)
                                tinymce.activeEditor.setContent(json_content.query.pages[key].extract.trim());
                        }
                    } else {
                        console.log("Nothing found 151");

                        tinymce.activeEditor.setContent(response);
                    }
                } else {

                    tinymce.activeEditor.setContent(JSON.stringify(json_content.items));

                }
            }
            document.getElementById('wpunity_fetchDescription_bt').innerHTML = "Fetch";

        },
        error : function(xhr, ajaxOptions, thrownError){
            console.log("ERROR");
            document.getElementById('wpunity_fetchDescription_bt').innerHTML = 'Error 21: Fetch again?' + thrownError;
        }
    });

}

//----------------------------------------------------------------------------------
//  FETCH IMAGES
//----------------------------------------------------------------------------------
function wpunity_fetchImageAjax(){

    document.getElementById('wpunity_fetchImage_bt').innerHTML = "Fetching";

    externalSourceImage = document.getElementById("fetch_source_image").options[document.getElementById("fetch_source_image").selectedIndex].value;

    document.getElementById("wpunity_titles_image_search_image").value = document.getElementById("wpunity_titles_image_search_image").value.replace(/ /g,"+");

    jQuery.ajax({
        url : 'admin-ajax.php',
        type : 'POST',
        data : {'action': 'wpunity_fetch_image_action',
            'lang_image':           document.getElementById("fetch_lang_image").options[document.getElementById("fetch_lang_image").selectedIndex].value,
            'externalSource_image': externalSourceImage,
            'titles_image':         document.getElementById("wpunity_titles_image_search_image").value
            },

        success : function(response) {

//            console.log(response);

            var json_content = jQuery.parseJSON(response);

            if (json_content) {

                document.getElementById('display_img_res').style.display ='';

                if (externalSourceImage == 'Wikipedia') {
                    if (json_content.query) {
                        var j=0;

                        for(key in json_content.query.pages) {
                            for(i=0; i<json_content.query.pages[key].imageinfo.length && j<10; i++) {

                                var fname = json_content.query.pages[key].imageinfo[0].url;
                                var whichimage ='image_res_'+j;

                                console.log(whichimage);

                                document.getElementById(whichimage).src = fname;
                                document.getElementById(whichimage + "_url").innerHTML = ''+fname+'';

                                document.getElementById(whichimage + "_title").innerHTML = 'More info';

                                document.getElementById(whichimage + "_title").href = json_content.query.pages[key].imageinfo[0].descriptionurl;

                                j++;
                            }
                        }
                    } else {
                        console.log("Nothing found 151");
                    }
                } else {

                    if (json_content.itemsCount  > 0) {

                        for(j=0; j<json_content.itemsCount; j++) {

                                var fname = json_content.items[j].edmPreview;

                                console.log(fname);

                                var whichimage ='image_res_'+(j+1);

                                document.getElementById(whichimage).src = fname;
                                document.getElementById(whichimage + "_url").innerHTML = fname;
                            document.getElementById(whichimage + "_title").innerHTML = json_content.items[j].title;

                        }
                    } else {
                        console.log("Nothing found 151");
                    }

                }
            }

            document.getElementById('wpunity_fetchImage_bt').innerHTML = "Fetch";
        },
        error : function(xhr, ajaxOptions, thrownError){
            console.log("ERROR");
            document.getElementById('wpunity_fetchImage_bt').innerHTML = 'Error 22: Fetch again?' + thrownError;
        }
    });

}

//----------------------------------------------------------------------------------
//  FETCH VIDEOS
//----------------------------------------------------------------------------------
function wpunity_fetchVideoAjax(){

    document.getElementById('wpunity_fetchVideo_bt').innerHTML = "Fetching";

    externalSourceVideo = document.getElementById("fetch_source_video").options[document.getElementById("fetch_source_video").selectedIndex].value;

    document.getElementById("wpunity_titles_video_search_video").value = document.getElementById("wpunity_titles_video_search_video").value.replace(/ /g,"_");

    jQuery.ajax({
        url : 'admin-ajax.php',
        type : 'POST',
        data : {'action': 'wpunity_fetch_video_action',
            'lang_video':           document.getElementById("fetch_lang_video").options[document.getElementById("fetch_lang_video").selectedIndex].value,
            'externalSource_video': externalSourceVideo,
            'titles_video':         document.getElementById("wpunity_titles_video_search_video").value
        },

        success : function(response) {

            console.log(response);

            var json_content = jQuery.parseJSON(response);

            if (json_content) {
                if (externalSourceVideo == 'Wikipedia') {
                    if (json_content.query) {
                        var j=0;
                        for(key in json_content.query.pages) {
                            j++;
                            console.log(json_content.query.pages[key].videoinfo[0].derivatives);
                            for(i=0; i<1; i++) {
                                var fname = json_content.query.pages[key].videoinfo[0].derivatives[0].src;

                                var whichvideo ='video_res_'+j;

                                console.log(whichvideo, document.getElementById(whichvideo));

                                document.getElementById(whichvideo).src = fname;
                                document.getElementById("videoplayer1").load();

                                document.getElementById(whichvideo + "_url").innerHTML = ''+fname+'';;

                                document.getElementById(whichvideo + "_title").innerHTML = "----";

                            }
                        }
                    } else {
                        console.log("Nothing found 151");
                    }
                } else {

                    if (json_content.itemsCount  > 0) {

                        for(j=0; j<json_content.itemsCount; j++) {

                            var fname = json_content.items[j].edmPreview;

                            console.log(fname);

                            var whichimage ='image_res_'+(j+1);

                            document.getElementById(whichimage).src = fname;
                            document.getElementById(whichimage + "_url").innerHTML = fname;
                            document.getElementById(whichimage + "_title").innerHTML = json_content.items[j].title;

                        }
                    } else {
                        console.log("Nothing found 151");
                    }

                }
            }

            document.getElementById('wpunity_fetchVideo_bt').innerHTML = "Fetch";
        },
        error : function(xhr, ajaxOptions, thrownError){
            console.log("ERROR");
            document.getElementById('wpunity_fetchVideo_bt').innerHTML = 'Error 23: Fetch again?' + thrownError;
        }
    });

}

<|endoftext|>


<commit_before>#!/usr/bin/env node
var Spotify = require('node-spotify');
var DweetIO = require('./DweetIO');

var SpotifyRequest = function(username, password, readyCallback) {
	var instance = this;
	this.dweetio = new DweetIO();
	this.dweetio.listenFor('jme-spotify-request', function(dweet) {
		console.log("Request received.");
		instance.request(dweet);
	});

	this.spotify = new Spotify({ appkeyFile: 'api_spotify.key' });
	this.spotify.on({
		"ready": readyCallback
	});
	this.spotify.login(username, password, false, false);

};

SpotifyRequest.prototype.request = function(dweet) {
	var instance = this;
	var callback = function(track) {
		if (track.isLoaded === true) {
			console.log("Sending Answer.");
			instance.dweetio.sendData('jme-spotify-answer', track);
		}
	};
	if (dweet.content['type'] &&
		(dweet.content['uri'] || dweet.content['search']))
	{
		console.log("Request type: " + dweet.content.type + ".");
		if (dweet.content.type == "name-track") {
			this.loadTrack(dweet.content.uri, callback);
		} else if (dweet.content.type == "search-track") {
			this.searchTrack(dweet.content.search, callback);
		}
	}
};

SpotifyRequest.prototype.loadTrack = function(trackLink, callback) {
	var track = this.spotify.createFromLink(trackLink);
	if (track.isLoaded !== false) {
		console.log("Track was loaded, serving from cache.");
		callback(track);
	} else {
		console.log("Waiting for track to load.");
		this.spotify.waitForLoaded([track], callback);
	}
};

SpotifyRequest.prototype.searchTrack = function(searchText, callback) {
	var instance = this;
	var search = new this.spotify.Search(searchText);
	search.execute(function(err, searchResult) {
		console.log("Search Executed.");
		if (!err) {
			if (search.totalTracks > 0) {
				callback(search.tracks[0]);
			}
		}
	});
};

var sq = new SpotifyRequest('joeasaurus', 'password');
<commit_msg>Added reqType to answer for better context.<commit_after>#!/usr/bin/env node
var Spotify = require('node-spotify');
var DweetIO = require('./DweetIO');

var SpotifyRequest = function(username, password, readyCallback) {
	var instance = this;
	this.dweetio = new DweetIO();
	this.dweetio.listenFor('jme-spotify-request', function(dweet) {
		console.log("Request received.");
		instance.request(dweet);
	});

	this.spotify = new Spotify({ appkeyFile: 'api_spotify.key' });
	this.spotify.on({
		"ready": readyCallback
	});
	this.spotify.login(username, password, false, false);

};

SpotifyRequest.prototype.request = function(dweet) {
	var instance = this;
	var callback = function(reqType, answer) {
		if (answer.isLoaded === true) {
			console.log("Sending Answer.");
			instance.dweetio.sendData('jme-spotify-answer', {
				"type": reqType,
				"answer": answer
			});
		}
	};
	if (dweet.content['type'] &&
		(dweet.content['uri'] || dweet.content['search']))
	{
		console.log("Request type: " + dweet.content.type + ".");
		if (dweet.content.type == "name-track") {
			this.loadTrack(dweet.content.uri, function(track) {callback(dweet.content.type, track);});
		} else if (dweet.content.type == "search-track") {
			this.searchTrack(dweet.content.search, function(track) {callback(dweet.content.type, track);});
		}
	}
};

SpotifyRequest.prototype.loadTrack = function(trackLink, callback) {
	var track = this.spotify.createFromLink(trackLink);
	if (track.isLoaded !== false) {
		console.log("Track was loaded, serving from cache.");
		callback(track);
	} else {
		console.log("Waiting for track to load.");
		this.spotify.waitForLoaded([track], callback);
	}
};

SpotifyRequest.prototype.searchTrack = function(searchText, callback) {
	var instance = this;
	var search = new this.spotify.Search(searchText);
	search.execute(function(err, searchResult) {
		console.log("Search Executed.");
		if (!err) {
			if (search.totalTracks > 0) {
				callback(search.tracks[0]);
			}
		}
	});
};

var sq = new SpotifyRequest('joeasaurus', 'password');
<|endoftext|>