<commit_before>var fs = require('fs');
var request = require('request');
var manifest = require('./manifest');
var config = require('../config');
// var wrapper = require('./wrapper');
var crypto = require('cryptofunc');
var cryptoUtils = require('cryptoUtils');
var strHexConversion = require('strHexConversion');

var TAG_VOTERS = '10';
var TAG_BALLOTS = '01';
var TAG_VERIFCODEAUTO = '02';
var TAG_VERIFCODEUSER = '03';

var NMixServers = manifest.mixServers.length;

exports.finalResult = null;	// this is where the result is stored (when ready)
exports.voters = null;		// this is where the list of voters is stored
exports.summary = null;		// the summary of the election

function splitter(msg, callback) {
    if (msg.length !== 0)  {
        var p = crypto.deconcatenate(msg);
        callback(p.first);
        splitter(p.second, callback);
    }
}

function isMalformed(voterChoices){
	if(voterChoices.length < manifest.minvoterChoicesPerVoter || voterChoices.length > manifest.maxvoterChoicesPerVoter)
		return true;

	voterChoices.sort(function(a,b){return a-b});
	for(var i=0; i < voterChoices.length; i++){
		if(voterChoices[i] < 0 || voterChoices[i] > manifest.voterChoices.length)
			return true;
		if(i>0 && voterChoices[i] === voterChoices[i-1])
			return true;
	}

	return false;
}

// expected data format:
// 		SIGN_collectinServer[electionID, receiptID, votersList]
//
exports.parseVotersList = function(signedVotersList) {
	var p = crypto.deconcatenate(signedVotersList);
	var data = p.first; // tag,elID,voters
	var signature = p.second;

    // Verify the signature
    var sig_ok = crypto.verifsig(manifest.collectingServer.verification_key, data, signature);
    if (!sig_ok) {
        console.log('ERROR: Wrong signature');
        return;
    }

    var data = crypto.splitter(data);

    // Check the tag:
    if (data.nextMessage() !== TAG_VOTERS) {
        console.log('ERROR: Wrong tag');
        return;
    }
    if (data.nextMessage().toUpperCase() !== manifest.hash.toUpperCase()) {
        console.log('ERROR: Wrong election ID');
        return;
    }

    // The rest of data is a list of voterIDs.
    var t = [];
	console.log("*** Parsing the list of voters.");
    for (var i=0; !data.empty(); ++i) {
    	var voterID = cryptoUtils.messageToString(data.nextMessage());
    	//var voterID = data.nextMessage();
    	t.push(voterID);
    	console.log("\t" + voterID);
    }
    exports.voters = t;

//    // Get the voters as a message
//    p = crypto.deconcatenate(p.second);
//    votersMsg = p.second;
//    // And collect them
//

//    splitter(votersMsg, function (item) {
//        item = (new Buffer(item, 'hex')).toString('utf8');
//        t.push(item);

//    });
//    exports.voters = t;
}

// expected data format:
//		SIGN_lastMixServer[electionID, receiptID, ballotsAsAMsg]
//
exports.parseFinalResult = function(signedFinalResult) {
    var p = crypto.deconcatenate(signedFinalResult);
    var tag_elID_ballots = p.first; 	// [tag, elID, ballotsAsAMessage]
	var signature = p.second;

    // Verify the signature
    var sig_ok = crypto.verifsig(manifest.mixServers[manifest.mixServers.length-1].verification_key, tag_elID_ballots, signature);
    if (!sig_ok) {
        console.log('ERROR: Wrong signature');
        return;
    }

    var data = crypto.splitter(tag_elID_ballots);

    // Check the tag:
    if (data.nextMessage() !== TAG_BALLOTS) {
        console.log('ERROR: Wrong tag');
        return;
    }

    // Check the election id
    if(data.nextMessage().toUpperCase() !== manifest.hash.toUpperCase()) {
    	console.log('ERROR: Wrong election ID');
        return;
    }

    var t = [];
    var ccount = manifest.choices.map(function(x) {return 0;}); // initialize the counters for choices with 0's
    console.log("*** Parsing the voters' choices.");
    var malformedExists = false;
    for (var i=0; !data.empty(); ++i) {
    	//console.log(i);
    	p = crypto.deconcatenate(data.nextMessage());
    	// Check the election id
    	if(p.first.toUpperCase() !== manifest.hash.toUpperCase()) {
        	console.log('ERROR: Wrong election ID');
            return;
        }
    	var choice_verifCode = p.second;
    	p = crypto.deconcatenate(choice_verifCode);
    	var verificationCode = p.second;
    	var voterChoices = p.first.match(/\d{1,8}/g);
    	if(voterChoices === null){
    		console.log("no choices made for this ballot");
    		continue;
    	}

    	for(var i=0; i < voterChoices.length; i++)
    		voterChoices[i] = crypto.hexStringToInt(voterChoices[i]);

    	var malformed = isMalformed(voterChoices);
    	if(malformed)
    		malformedExists = true;

    	// Verification code
    	p = crypto.deconcatenate(verificationCode);
    	var receiptID;
    	var userCode='';
    	if(p.first === TAG_VERIFCODEAUTO)
    		receiptID = p.second;
    	else if (p.first === TAG_VERIFCODEUSER){
    		p = crypto.deconcatenate(p.second)
    		receiptID = p.first;
    		userCode = strHexConversion.hexDecode(p.second);
    	}
    	else
    		console.log('ERROR: Wrong verification code format');

    	var userChoices = "";
    	for(var i=0; i < voterChoices.length && i < manifest.maxChoicesPerVoter; i++){
    		userChoices = userChoices + manifest.choices[voterChoices[i]]+" | ";
    	}
    	userChoices = userChoices.substring(0, userChoices.length-3);

    	t.push({userCode: userCode, receiptID: receiptID, vote: userChoices, malformed: malformed});
    	if(userCode !== '')
    		console.log(userCode + "\t" + receiptID + "\t" + userChoices);
    	else
    		console.log(receiptID + "\t" + userChoices);
    	// add one vote for choice
    	for(var i=0; i < voterChoices.length && manifest.maxChoicesPerVoter; i++){
    		if(!malformed)
    			++ccount[voterChoices[i]];
    	}

    }

    // format the summary (number votes for different candidates)
    var summary = [];
    for (var i=0; i<ccount.length; ++i) {
        summary.push({choice : manifest.choices[i],  votes : ccount[i] });
    }
    t.sort(function(a,b){return (a.userCode+a.receiptID).localeCompare(b.userCode+b.receiptID) });
    if(malformedExists)
    	t[0].malformedExists = true;
    summary.sort(function(a,b){return a.votes-b.votes})
    exports.summary = summary;
    summary.reverse();
    exports.finalResult = t;
}

//var fileProcessed = false;

function fetchData(url, cont) {
    request(url, function (err, response, body) {
        if (!err && response.statusCode == 200) {
            cont(null, body);
        }
        else {
        	var info = 'Cannot fetch the page: ' + url + '\t\(' + err + ')';
            cont(info);
        }
    });

}
//Save data in a file
function saveData(data, file) {
    fs.writeFile(file, data, function (err) {
        if (err)
            console.log('Problems with saving the data:\n', data);
        else {
            console.log('Result saved in: ', file);
            resultReady = true;
        }
    });
}

exports.fetchAndSaveData = function() {
	// fetch the results of the mix servers
	for(var i=NMixServers-1; i>=0; --i) {
		var mixServer_path = config.RESULTMIX_FILE.replace('%d', i);
		// console.log(mixServer_path);
		fs.exists(mixServer_path, function(j){
		      return function(exists){
		    	  if(!exists){
		    		  // fetch the results from the i-th mix server
		    		  fetchData(manifest.mixServers[j].URI + '/result.msg', function(k){
		    			  return function (err, data) {
		    				  if (!err) {
		    					  console.log('** I) \t Results of the #%sth mix server fetched', k);
		    					  // recreate the path where to save the result because the for loop could be
		    					  // in a different iteration than the callback
		    					  var mixServer_path = config.RESULTMIX_FILE.replace('%d', k);
		    					  saveData(data, mixServer_path);
		    					  if(k===NMixServers-1 && exports.finalResult === null) // shows the final results
		    						  exports.parseFinalResult(data);
		    				  }
		    				  else {
		    					//console.log("** I) \t%s  (MixServer #%s)", err, k);
		    				  }
		    			  }
		    		  }(j));
		    	  }
		      }
		}(i));
	}

	// fetch the results of the collecting server
	fs.exists(config.RESULTCS_FILE, function (exists) {
		if(!exists){
			// fetch the results form the Collecting Server
			fetchData(manifest.collectingServer.URI + '/result.msg', function (err, data) {
				if (!err) {
					console.log('** II)\tResults of the Collecting Server fetched');
					saveData(data, config.RESULTCS_FILE);
				}
				else {
					console.log("** II)\t%s  (Collecting Server: result)", err);
				}
			});
		}
	});

	if(manifest.publishListOfVoters){
		// fetch the votersList
		fs.exists(config.VOTERSLIST_FILE, function (exists) {
			if(!exists){
				// fetch the votersList from the Collecting Server
				fetchData(manifest.collectingServer.URI + '/votersList.msg', function (err, data) {
					if (!err) {
						console.log('** III)\t Voters list fetched');
						saveData(data, config.VOTERSLIST_FILE);
						if (exports.voters === null)
							exports.parseVotersList(data);
					}
					else {
						console.log("** III)\t%s  (Collecting Server: list of voters)", err);
					}
				});
			}
		});
	}
}

/////////////////////////////////////////////
//Check whether there is the file and, if so, parse it
function loadFileAndContinue(filename, cont) {
    console.log('Looking for file',  filename);
    fs.exists(filename, function(exists) {
        if(exists) {
            console.log('Processing', filename);
            fs.readFile(filename, {encoding:'ascii'}, function (err, data) {
                if (err) {
                    console.log('Error:', err);
                    return;
                }
                cont(data);
            });
        }
        else {
            console.log(filename, 'not found');
        }
    });
}

exports.loadResult = function () {

	// Load /parse the voters list from the file
    if (exports.voters === null) {
        loadFileAndContinue("" + config.FILE_FOLDER + config.VOTERSLIST + config.EXT,
        		parseVotersList);
    }

    // load / parse the final result from the file
    if (exports.finalResult === null) {
        loadFileAndContinue("" + config.FILE_FOLDER + config.RESULTMIX + (NMixServers-1) + config.EXT,
        		parseFinalResult);
    }

//    // Load /parse the voters list from the collecting server
//    if (exports.voters === null) {
//        fetchData(manifest.collectingServer.URI + '/votersList.msg', function (err, data) {
//            if (!err) {
//                console.log('VOTERS LIST FILE FETCHED');
//                parseVotersList(data);
//            }
//        });
//    }
//
//    // Load /parse the final result (from the last mix server)
//    if (exports.finalResult === null) {
//        fetchData(manifest.mixServers[manifest.mixServers.length-1].URI + '/result.msg', function (err, data) {
//            if (!err) {
//                console.log('FINAL RESULT FILE FETCHED');
//                parseFinalResult(data);
//            }
//        });
//    }

}

<commit_msg>bug fixed<commit_after>var fs = require('fs');
var request = require('request');
var manifest = require('./manifest');
var config = require('../config');
// var wrapper = require('./wrapper');
var crypto = require('cryptofunc');
var cryptoUtils = require('cryptoUtils');
var strHexConversion = require('strHexConversion');

var TAG_VOTERS = '10';
var TAG_BALLOTS = '01';
var TAG_VERIFCODEAUTO = '02';
var TAG_VERIFCODEUSER = '03';

var NMixServers = manifest.mixServers.length;

exports.finalResult = null;	// this is where the result is stored (when ready)
exports.voters = null;		// this is where the list of voters is stored
exports.summary = null;		// the summary of the election

function splitter(msg, callback) {
    if (msg.length !== 0)  {
        var p = crypto.deconcatenate(msg);
        callback(p.first);
        splitter(p.second, callback);
    }
}

function isMalformed(voterChoices){
	if(voterChoices.length < manifest.minChoicesPerVoter || voterChoices.length > manifest.maxChoicesPerVoter)
		return true;

	voterChoices.sort(function(a,b){return a-b});
	for(var i=0; i < voterChoices.length; i++){
		if(voterChoices[i] < 0 || voterChoices[i] > manifest.choices.length)
			return true;
		if(i>0 && voterChoices[i] === voterChoices[i-1])
			return true;
	}

	return false;
}

// expected data format:
// 		SIGN_collectinServer[electionID, receiptID, votersList]
//
exports.parseVotersList = function(signedVotersList) {
	var p = crypto.deconcatenate(signedVotersList);
	var data = p.first; // tag,elID,voters
	var signature = p.second;

    // Verify the signature
    var sig_ok = crypto.verifsig(manifest.collectingServer.verification_key, data, signature);
    if (!sig_ok) {
        console.log('ERROR: Wrong signature');
        return;
    }

    var data = crypto.splitter(data);

    // Check the tag:
    if (data.nextMessage() !== TAG_VOTERS) {
        console.log('ERROR: Wrong tag');
        return;
    }
    if (data.nextMessage().toUpperCase() !== manifest.hash.toUpperCase()) {
        console.log('ERROR: Wrong election ID');
        return;
    }

    // The rest of data is a list of voterIDs.
    var t = [];
	console.log("*** Parsing the list of voters.");
    for (var i=0; !data.empty(); ++i) {
    	var voterID = cryptoUtils.messageToString(data.nextMessage());
    	//var voterID = data.nextMessage();
    	t.push(voterID);
    	console.log("\t" + voterID);
    }
    exports.voters = t;

//    // Get the voters as a message
//    p = crypto.deconcatenate(p.second);
//    votersMsg = p.second;
//    // And collect them
//

//    splitter(votersMsg, function (item) {
//        item = (new Buffer(item, 'hex')).toString('utf8');
//        t.push(item);

//    });
//    exports.voters = t;
}

// expected data format:
//		SIGN_lastMixServer[electionID, receiptID, ballotsAsAMsg]
//
exports.parseFinalResult = function(signedFinalResult) {
    var p = crypto.deconcatenate(signedFinalResult);
    var tag_elID_ballots = p.first; 	// [tag, elID, ballotsAsAMessage]
	var signature = p.second;

    // Verify the signature
    var sig_ok = crypto.verifsig(manifest.mixServers[manifest.mixServers.length-1].verification_key, tag_elID_ballots, signature);
    if (!sig_ok) {
        console.log('ERROR: Wrong signature');
        return;
    }

    var data = crypto.splitter(tag_elID_ballots);

    // Check the tag:
    if (data.nextMessage() !== TAG_BALLOTS) {
        console.log('ERROR: Wrong tag');
        return;
    }

    // Check the election id
    if(data.nextMessage().toUpperCase() !== manifest.hash.toUpperCase()) {
    	console.log('ERROR: Wrong election ID');
        return;
    }

    var t = [];
    var ccount = manifest.choices.map(function(x) {return 0;}); // initialize the counters for choices with 0's
    console.log("*** Parsing the voters' choices.");
    var malformedExists = false;
    for (var i=0; !data.empty(); ++i) {
    	//console.log(i);
    	p = crypto.deconcatenate(data.nextMessage());
    	// Check the election id
    	if(p.first.toUpperCase() !== manifest.hash.toUpperCase()) {
        	console.log('ERROR: Wrong election ID');
            return;
        }
    	var choice_verifCode = p.second;
    	p = crypto.deconcatenate(choice_verifCode);
    	var verificationCode = p.second;
    	var voterChoices = p.first.match(/\d{1,8}/g);
    	if(voterChoices === null){
    		console.log("no choices made for this ballot");
    		continue;
    	}

    	for(var i=0; i < voterChoices.length; i++)
    		voterChoices[i] = crypto.hexStringToInt(voterChoices[i]);

    	var malformed = isMalformed(voterChoices);
    	if(malformed)
    		malformedExists = true;

    	// Verification code
    	p = crypto.deconcatenate(verificationCode);
    	var receiptID;
    	var userCode='';
    	if(p.first === TAG_VERIFCODEAUTO)
    		receiptID = p.second;
    	else if (p.first === TAG_VERIFCODEUSER){
    		p = crypto.deconcatenate(p.second)
    		receiptID = p.first;
    		userCode = strHexConversion.hexDecode(p.second);
    	}
    	else
    		console.log('ERROR: Wrong verification code format');

    	var userChoices = "";
    	for(var i=0; i < voterChoices.length && i < manifest.maxChoicesPerVoter; i++){
    		userChoices = userChoices + manifest.choices[voterChoices[i]]+" | ";
    	}
    	userChoices = userChoices.substring(0, userChoices.length-3);

    	t.push({userCode: userCode, receiptID: receiptID, vote: userChoices, malformed: malformed});
    	if(userCode !== '')
    		console.log(userCode + "\t" + receiptID + "\t" + userChoices);
    	else
    		console.log(receiptID + "\t" + userChoices);
    	// add one vote for choice
    	for(var i=0; i < voterChoices.length && manifest.maxChoicesPerVoter; i++){
    		if(!malformed)
    			++ccount[voterChoices[i]];
    	}

    }

    // format the summary (number votes for different candidates)
    var summary = [];
    for (var i=0; i<ccount.length; ++i) {
        summary.push({choice : manifest.choices[i],  votes : ccount[i] });
    }
    t.sort(function(a,b){return (a.userCode+a.receiptID).localeCompare(b.userCode+b.receiptID) });
    if(malformedExists)
    	t[0].malformedExists = true;
    summary.sort(function(a,b){return a.votes-b.votes})
    exports.summary = summary;
    summary.reverse();
    exports.finalResult = t;
}

//var fileProcessed = false;

function fetchData(url, cont) {
    request(url, function (err, response, body) {
        if (!err && response.statusCode == 200) {
            cont(null, body);
        }
        else {
        	var info = 'Cannot fetch the page: ' + url + '\t\(' + err + ')';
            cont(info);
        }
    });

}
//Save data in a file
function saveData(data, file) {
    fs.writeFile(file, data, function (err) {
        if (err)
            console.log('Problems with saving the data:\n', data);
        else {
            console.log('Result saved in: ', file);
            resultReady = true;
        }
    });
}

exports.fetchAndSaveData = function() {
	// fetch the results of the mix servers
	for(var i=NMixServers-1; i>=0; --i) {
		var mixServer_path = config.RESULTMIX_FILE.replace('%d', i);
		// console.log(mixServer_path);
		fs.exists(mixServer_path, function(j){
		      return function(exists){
		    	  if(!exists){
		    		  // fetch the results from the i-th mix server
		    		  fetchData(manifest.mixServers[j].URI + '/result.msg', function(k){
		    			  return function (err, data) {
		    				  if (!err) {
		    					  console.log('** I) \t Results of the #%sth mix server fetched', k);
		    					  // recreate the path where to save the result because the for loop could be
		    					  // in a different iteration than the callback
		    					  var mixServer_path = config.RESULTMIX_FILE.replace('%d', k);
		    					  saveData(data, mixServer_path);
		    					  if(k===NMixServers-1 && exports.finalResult === null) // shows the final results
		    						  exports.parseFinalResult(data);
		    				  }
		    				  else {
		    					//console.log("** I) \t%s  (MixServer #%s)", err, k);
		    				  }
		    			  }
		    		  }(j));
		    	  }
		      }
		}(i));
	}

	// fetch the results of the collecting server
	fs.exists(config.RESULTCS_FILE, function (exists) {
		if(!exists){
			// fetch the results form the Collecting Server
			fetchData(manifest.collectingServer.URI + '/result.msg', function (err, data) {
				if (!err) {
					console.log('** II)\tResults of the Collecting Server fetched');
					saveData(data, config.RESULTCS_FILE);
				}
				else {
					console.log("** II)\t%s  (Collecting Server: result)", err);
				}
			});
		}
	});

	if(manifest.publishListOfVoters){
		// fetch the votersList
		fs.exists(config.VOTERSLIST_FILE, function (exists) {
			if(!exists){
				// fetch the votersList from the Collecting Server
				fetchData(manifest.collectingServer.URI + '/votersList.msg', function (err, data) {
					if (!err) {
						console.log('** III)\t Voters list fetched');
						saveData(data, config.VOTERSLIST_FILE);
						if (exports.voters === null)
							exports.parseVotersList(data);
					}
					else {
						console.log("** III)\t%s  (Collecting Server: list of voters)", err);
					}
				});
			}
		});
	}
}

/////////////////////////////////////////////
//Check whether there is the file and, if so, parse it
function loadFileAndContinue(filename, cont) {
    console.log('Looking for file',  filename);
    fs.exists(filename, function(exists) {
        if(exists) {
            console.log('Processing', filename);
            fs.readFile(filename, {encoding:'ascii'}, function (err, data) {
                if (err) {
                    console.log('Error:', err);
                    return;
                }
                cont(data);
            });
        }
        else {
            console.log(filename, 'not found');
        }
    });
}

exports.loadResult = function () {

	// Load /parse the voters list from the file
    if (exports.voters === null) {
        loadFileAndContinue("" + config.FILE_FOLDER + config.VOTERSLIST + config.EXT,
        		parseVotersList);
    }

    // load / parse the final result from the file
    if (exports.finalResult === null) {
        loadFileAndContinue("" + config.FILE_FOLDER + config.RESULTMIX + (NMixServers-1) + config.EXT,
        		parseFinalResult);
    }

//    // Load /parse the voters list from the collecting server
//    if (exports.voters === null) {
//        fetchData(manifest.collectingServer.URI + '/votersList.msg', function (err, data) {
//            if (!err) {
//                console.log('VOTERS LIST FILE FETCHED');
//                parseVotersList(data);
//            }
//        });
//    }
//
//    // Load /parse the final result (from the last mix server)
//    if (exports.finalResult === null) {
//        fetchData(manifest.mixServers[manifest.mixServers.length-1].URI + '/result.msg', function (err, data) {
//            if (!err) {
//                console.log('FINAL RESULT FILE FETCHED');
//                parseFinalResult(data);
//            }
//        });
//    }

}

<|endoftext|>


<commit_before>//GDBase client tool
//Usage: node gdbase-build.js command --dataset <DATASET> --specie <SPECIE> --assembly <ASSEMBLY>

//Import dependencies
var getArgs = require('get-args');

//Get the command line args
var args = getArgs();

//Check the command
if(args.command === ''){ return console.error('No command provided...'); }

//Check the specie
if(typeof args.options.specie === 'undefined'){ return console.error('No specie provided...'); }

//Check the assembly
if(typeof args.options.assembly === 'undefined'){ return console.error('No assembly provided...'); }

//Check the dataset option
if(typeof args.options.dataset === 'undefined'){ return console.error('No dataset provided...'); }

//Get the action file
var action = './commands/{dataset}-{command}.js';

//Replace the dataset
action = action.replace('{dataset}', args.options.dataset);

//Replace the command
action = action.replace('{command}', args.command);

//Show in console
console.log('Running ' + action);

//Import
require(action)(args.options);
<commit_msg>Create main<commit_after>//GDBase build tool
//Usage: node gdbase-build.js command --dataset <DATASET> --specie <SPECIE> --assembly <ASSEMBLY>

//Import dependencies
var getArgs = require('get-args');

//Get the command line args
var args = getArgs();

//Check the command
if(args.command === ''){ return console.error('No command provided...'); }

//Check the specie
if(typeof args.options.specie === 'undefined'){ return console.error('No specie provided...'); }

//Check the assembly
if(typeof args.options.assembly === 'undefined'){ return console.error('No assembly provided...'); }

//Check the dataset option
if(typeof args.options.dataset === 'undefined'){ return console.error('No dataset provided...'); }

//Get the action file
var action = './commands/{dataset}-{command}.js';

//Replace the dataset
action = action.replace('{dataset}', args.options.dataset);

//Replace the command
action = action.replace('{command}', args.command);

//Show in console
console.log('Running ' + action);

//Import
require(action)(args.options);
<|endoftext|>


<commit_before>/*global config*/
import React from 'react';
import { Route, IndexRoute } from 'react-router';

// Pages
import App from './pages/app.jsx';
import Dashboard from './pages/dashboard.jsx';
import Org from './pages/org.jsx';
import Repo from './pages/repo.jsx';
import Branch from './pages/branch.jsx';
import Build from './pages/build.jsx';
import RepoBuild from './pages/repoBuild.jsx';
import NotFound from './pages/notFound.jsx';

function pagePath(path) {
  return config.appRoot + path;
}

const routes = (
  <Route name='app' path='/' component={ App }>
    <IndexRoute name='index' component={ Dashboard } />
    <Route name='dashboard' path={pagePath('/')} component={ Dashboard } />
    <Route name='org' path={pagePath('/builds/:host/:org')} component={Org} />
    <Route name='repo' path={pagePath('/builds/:host/:org/:repo')} component={Repo} />
    <Route name='branch' path={pagePath('/builds/:host/:org/:repo/:branch')} component={Branch} />
    <Route name='repoBuild' path={pagePath('/builds/:host/:org/:repo/:branch/:buildNumber')} component={RepoBuild} />
    <Route name='build' path={pagePath('/builds/:host/:org/:repo/:branch/:buildNumber/:moduleName')} component={Build} />
    <Route name='notFound' path="*" component={ NotFound } />
  </Route>
);

export default routes;
<commit_msg>last try<commit_after>/*global config*/
import React from 'react';
import { Route, IndexRoute } from 'react-router';

// Pages
import App from './pages/app.jsx';
import Dashboard from './pages/dashboard.jsx';
import Org from './pages/org.jsx';
import Repo from './pages/repo.jsx';
import Branch from './pages/branch.jsx';
import Build from './pages/build.jsx';
import RepoBuild from './pages/repoBuild.jsx';
import NotFound from './pages/notFound.jsx';

function pagePath(path) {
  return config.appRoot + path;
}

const routes = (
  <Route name='app' path='/' component={ App }>
    <IndexRoute name='dashboard' component={ Dashboard } />
    <Route name='index' path={pagePath('/')} component={ Dashboard } />
    <Route name='org' path={pagePath('/builds/:host/:org')} component={Org} />
    <Route name='repo' path={pagePath('/builds/:host/:org/:repo')} component={Repo} />
    <Route name='branch' path={pagePath('/builds/:host/:org/:repo/:branch')} component={Branch} />
    <Route name='repoBuild' path={pagePath('/builds/:host/:org/:repo/:branch/:buildNumber')} component={RepoBuild} />
    <Route name='build' path={pagePath('/builds/:host/:org/:repo/:branch/:buildNumber/:moduleName')} component={Build} />
    <Route name='notFound' path="*" component={ NotFound } />
  </Route>
);

export default routes;
<|endoftext|>


<commit_before>/**
 * Stack.js - JavaScript OO Implementation of Stack Data Structure
 */

 /**
 * A stack is essentially a list of data elements which may be accessed at only one end.
 * Stacks are last-in, first-out (LIFO) data structures. Elements may be added to a stack
 * with the 'push' operation and removed from a stack with the 'pop' operation. The element
 * at the top of the stack may be viewed with the 'peek' operation; this operation returns
 * the element without removing it from the stack. The 'clear' operation 'deletes' the contents
 * of the stack. The 'getLength' operation returns the length (number of elements contained)
 * in the stack. The 'toString' operation returns a string representation of the stack.
 * @class
 *
 */

var Stack = (function() {

	/**
	 * Constructor function declares and/or intialises stack properties
	 * @constructor
	 */
	function Stack() {
		this.datastore = []; // An array is the underlying data structure
		this.top = 0;// The top of the stack
	}

	/**
	 * Push new element onto stack. When the caller pushes a new element
	 * onto the stack it is stored in the top position identified by the top
	 * variable and the latter is incremented so that the new top is the next
	 * vacant position in the array.
	 * @param element Element to be added to stack
	 */
	Stack.prototype.push = function(element) {
		this.datastore[this.top++] = element;
	}

	/**
	 * Pop element off the stack. This method is essentially the reverse of the push() function
	 * returning the element in the top position of the stack and decrementing the top variable
	 * @return {*} Return the element at the top of the stack.
	 */
	Stack.prototype.pop = function() {
		this.datastore.pop(); // use Array.prototype.pop to remove last element of datastore
		return this.datastore[--this.top];
	}

	/**
	 * Return the top element of the stack by accessing the element at the top-1 position of the
	 * underlying datastore (array).
	 * @return {*} Return the top element of the stack or undefined if the stack is empty
	 */
	Stack.prototype.peek = function() {
		return this.datastore[this.top-1];
	}

	/**
	 * Reset the stack and reinitialise the underlying datastore.
	 */
	Stack.prototype.clear = function() {
		this.datastore = [];
		this.top = 0;
	}

	/**
	 * Get the number of elements in the stack.
	 * @return {number} Return the number of elements in the stack.
	 */
	Stack.prototype.getLength = function() {
		return this.listSize;
	};

	/**
	 * Get a string representation of the stack.
	 * @return {string} Return a string representation of the stack.
	 */
	Stack.prototype.toString = function() {
		return this.datastore.toString();
	}

	return Stack;
}());<commit_msg>Fix Bug in getLength() Method<commit_after>/**
 * Stack.js - JavaScript OO Implementation of Stack Data Structure
 */

 /**
 * A stack is essentially a list of data elements which may be accessed at only one end.
 * Stacks are last-in, first-out (LIFO) data structures. Elements may be added to a stack
 * with the 'push' operation and removed from a stack with the 'pop' operation. The element
 * at the top of the stack may be viewed with the 'peek' operation; this operation returns
 * the element without removing it from the stack. The 'clear' operation 'deletes' the contents
 * of the stack. The 'getLength' operation returns the length (number of elements contained)
 * in the stack. The 'toString' operation returns a string representation of the stack.
 * @class
 *
 */

var Stack = (function() {

	/**
	 * Constructor function declares and/or intialises stack properties
	 * @constructor
	 */
	function Stack() {
		this.datastore = []; // An array is the underlying data structure
		this.top = 0;// The top of the stack
	}

	/**
	 * Push new element onto stack. When the caller pushes a new element
	 * onto the stack it is stored in the top position identified by the top
	 * variable and the latter is incremented so that the new top is the next
	 * vacant position in the array.
	 * @param element Element to be added to stack
	 */
	Stack.prototype.push = function(element) {
		this.datastore[this.top++] = element;
	}

	/**
	 * Pop element off the stack. This method is essentially the reverse of the push() function
	 * returning the element in the top position of the stack and decrementing the top variable
	 * @return {*} Return the element at the top of the stack.
	 */
	Stack.prototype.pop = function() {
		this.datastore.pop(); // use Array.prototype.pop to remove last element of datastore
		return this.datastore[--this.top];
	}

	/**
	 * Return the top element of the stack by accessing the element at the top-1 position of the
	 * underlying datastore (array).
	 * @return {*} Return the top element of the stack or undefined if the stack is empty
	 */
	Stack.prototype.peek = function() {
		return this.datastore[this.top-1];
	}

	/**
	 * Reset the stack and reinitialise the underlying datastore.
	 */
	Stack.prototype.clear = function() {
		this.datastore = [];
		this.top = 0;
	}

	/**
	 * Get the number of elements in the stack.
	 * @return {number} Return the number of elements in the stack.
	 */
	Stack.prototype.getLength = function() {
		return this.top;
	};

	/**
	 * Get a string representation of the stack.
	 * @return {string} Return a string representation of the stack.
	 */
	Stack.prototype.toString = function() {
		return this.datastore.toString();
	}

	return Stack;
}());<|endoftext|>


<commit_before>const pi = 3.14159265359;
const bohr2ang = 0.529177249;

//default folder
var folder = "graphene";

class PhononWebpage {

    constructor(visualizer, dispersion) {
        this.k = 0;
        this.n = 0;
        this.nx = 1;
        this.ny = 1;
        this.nz = 1;
        this.amplitude = 0.5;

        //select visualization
        this.visualizer = visualizer;

        //select dispersion
        this.dispersion = dispersion;

        //bind some functions (TODO: improve this)
        this.exportXSF    = exportXSF.bind(this);
        this.exportPOSCAR = exportPOSCAR.bind(this);
    }

    getRepetitions() {
        /*
        read the number of repetitions in each direction and update it
        */
        this.nx = $('#nx').val();
        this.ny = $('#ny').val();
        this.nz = $('#nz').val();
    }

    setRepetitions(repetitions) {
        /*
        set the number of repetitions on the interface
        */

        if (repetitions) {
            this.nx = repetitions[0];
            this.ny = repetitions[1];
            this.nz = repetitions[2];
        }

        $('#nx').val(this.nx);
        $('#ny').val(this.ny);
        $('#nz').val(this.nz);
    }

    loadCustomFile(event) {
        /*
        find the type of file and call the corresponding function to read it

        two formats available:
            phonopy files (band.yaml)
            internal .json format (*.json) description available in ./phononweb/phononweb.py
        */

        let yaml = null;
        let json = null;

        for (let i=0; i<event.target.files.length; i++) {
            let file = event.target.files[i];
            if (file.name.indexOf(".yaml") > -1) { yaml = file; }
            if (file.name.indexOf(".json") > -1) { json = file; }
        }

        this.name = "Custom file"
        if      (json) {
            this.phonon = new PhononJson();
            this.phonon.getFromFile(json, this.loadCallback.bind(this) );
        }
        else if (yaml) {
            this.phonon = new PhononYaml();
            this.phonon.getFromFile(yaml, this.loadCallback.bind(this) );
        }
        else {
            alert("Ivalid file");
        }
    }

    loadURL(url_vars) {
        /*
        load file from post request in the url

        two formats available:
            phonopy files (band.yaml)
            internal .json format (*.json) description available in ./phononweb/phononweb.py
        */

        let yaml = null;
        let json = null;

        for (let key in url_vars) {
            if ( key == "yaml" ) { yaml = $.get(url_vars[key]).responseText; }
            if ( key == "json" ) { json = $.get(url_vars[key]).responseText; }
            if ( key == "name" ) { $('#t1').html(url_vars[key]);     }
        }

        this.name = "Custom file"
        if      (json) {
            this.phonon = new PhononJson();
            this.phonon.getFromString(json, this.loadCallback.bind(this) );
        }
        else if (yaml) {
            this.phonon = new PhononYaml();
            this.phonon.getFromString(yaml, this.loadCallback.bind(this) );
        }
        else {
            alert("Ivalid url");
        }
    }

    loadId(id) {
        /*
        load a material from phonodb
        http://phonondb.mtl.kyoto-u.ac.jp
        */

        this.loadURL( { yaml: this.materials[id]['url'] } );
        this.name = this.materials[id]['name'] +  " mp-"+id+"";
        this.update();
    }

    loadLocal() {
        /*
        read structure from a local file distributed with the repository
        */

        let readJson = function(string) {
            this.phonon = new PhononJson();
            this.phonon.getFromString(string, this.loadCallback.bind(this) );
        }

        $.get(folder+'/data.json', readJson.bind(this), "html" );
    }

    loadCallback() {
        /*
        Fuunction to be called once the file is loaded
        */
        this.setRepetitions(this.phonon.repetitions);
        this.update()
    }

    getStructure(nx,ny,nz) {
        let lat = this.phonon.lat;
        let apc = this.phonon.atom_pos_car;
        let atoms = [];

	    for (let ix=0;ix<nx;ix++) {
            for (let iy=0;iy<ny;iy++) {
                for (let iz=0;iz<nz;iz++) {
                    for (let i=0;i<this.phonon.natoms;i++) {

                        //postions of the atoms
                        let x = apc[i][0] + ix*lat[0][0] + iy*lat[1][0] + iz*lat[2][0];
                        let y = apc[i][1] + ix*lat[0][1] + iy*lat[1][1] + iz*lat[2][1];
                        let z = apc[i][2] + ix*lat[0][2] + iy*lat[1][2] + iz*lat[2][2];

                        atoms.push( [i,x,y,z] );
                    }
                }
            }
        }

        return atoms;
    }

    getBondingDistance() {
        /*
        replicate the atoms two times in each direction
        */
        let atoms = this.getStructure(2,2,2);

        let combinations = getCombinations( atoms );
        let min = 1e9;
        for (let i=0; i<combinations.length; i++ ) {
            let a = combinations[i][0];
            let b = combinations[i][1];

            let distance = dist(a.slice(1),b.slice(1));
            if (min > distance) {
                min = distance;
            }
        }
        return min;
    }

    getVibrations(nx,ny,nz) {
        /*
        Calculate the vibration patterns for all the atoms
        */
        let phonon = this.phonon;
        let veckn = phonon.vec[this.k][this.n];
        let vibrations = [];
        let kpt = phonon.kpoints[this.k];

        //additional phase if necessary
        let atom_phase = []
        if (phonon.addatomphase) {
            for (let i=0; i<phonon.natoms; i++) {
                let phase = kpt[0]*phonon.atom_pos_red[i][0] +
                        kpt[1]*phonon.atom_pos_red[i][1] +
                        kpt[2]*phonon.atom_pos_red[i][2];
                atom_phase.push(phase);
            }
        }
        else {
            for (let i=0; i<phonon.natoms; i++) {
                atom_phase.push(0);
            }
        }

        for (var ix=0; ix<nx; ix++) {
            for (var iy=0; iy<ny; iy++) {
                for (var iz=0; iz<nz; iz++) {

                    for (let i=0; i<phonon.natoms; i++) {
                        let sprod = kpt[0]*ix + kpt[1]*iy + kpt[2]*iz + atom_phase[i];
                        let phase = Complex.Polar(1.0,sprod*2.0*pi);

                        //Displacements of the atoms
                        let x = Complex(veckn[i][0][0],veckn[i][0][1]).mult(phase);
                        let y = Complex(veckn[i][1][0],veckn[i][1][1]).mult(phase);
                        let z = Complex(veckn[i][2][0],veckn[i][2][1]).mult(phase);

                        vibrations.push( [x,y,z] );
                    }
                }
            }
        }

        return vibrations;
    }

    setVibrations() {
        this.vibrations = this.getVibrations(this.nx,this.ny,this.nz);
    }

    updatePage() {
        /*
        lattice vectors table
        */

        for (let i=0; i<3; i++) {
            for (let j=0; j<3; j++) {
                //round lattice values
                $('#uc_'+i+j).html( this.phonon.lat[i][j].toPrecision(5) );
            }
        }

        //unit cell table
        $('#uc_natoms').html( this.phonon.natoms );
        $('#uc_atypes').html( this.phonon.formula );

        //atomic positions table
        let pos = this.phonon.atom_pos_red;
        $('#atompos').empty() //clean the atomic positions table
        for (let i=0; i<this.phonon.natoms; i++) {
            $('#atompos').append('

');
            $('#atompos tr:last').append(''+this.phonon.atom_types[i]+'	');
            for (let j=0; j<3; j++) {
                $('#atompos tr:last').append(''+pos[i][j].toFixed(4)+'	');
            }
        }

        //update title
        $('#t1').html(this.name);
    }

    update(dispersion=true) {
        /*
        Update all the aspects fo the webpage
        */

        //update structure
        this.getRepetitions();
        this.atoms = this.getStructure(this.nx,this.ny,this.nz);
        this.vibrations = this.getVibrations(this.nx,this.ny,this.nz);
        this.phonon.nndist = this.getBondingDistance();

        //update page
        this.updatePage();

        //update dispersion
        if (dispersion) { this.dispersion.update(this.phonon); }

        //update visualizer
        this.visualizer.update(this);
    }

    createPhonodbMenu(phonodb) {
        /*
        Create the phonondb menu
        */

        $("#div-phonodb").css('display', 'inline');
        let materials = jsyaml.load(phonodb);
        let materials_ref = {};
        $('#phonodb').empty();
        for (let i=0;i<materials.length;i++) {
            let material = materials[i];
            materials_ref[material['id']] = material;
            $('#phonodb').append('

');
            $('#phonodb li:last').append(""+material['name']+"");
        }
        this.materials = materials_ref;
    }

    updateMenu() {
        /*
        create menu with:
            local files (files distributed with the website)
            files from the phonodb database
        */

        //get a list of local materials
        $.getJSON('models.json', function(data) {
            let nmodels = data["nmodels"];
            let models  = data["models"];
            $('#mat').empty() //clean the atomic positions table

            for (let i=0; i<nmodels; i++) {
                $('#mat').append('

');
                $('#mat li:last').append(""+models[i]["name"]+"");
            }
        });

        //get a list of materials from phonodb
        $.get('phonondb.yaml', this.createPhonodbMenu);
    }

    static getUrlVars() {
        /*
        get variables from the url
        from http://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url

        currently the possible options are:
            json : load a json file from location
            yaml : load a yaml file from location
            name : change the display name of the material
        */
        let vars = {};
        let hash;

        if (location.search) {
            let hashes = location.search.slice(1).split('&');
            for(let i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars[hash[0]] = hash[1];
            }
            return vars;
        }
        else {
            return null;
        }
    }

}

$(document).ready(function() {

    //visualizer
    v = new VibCrystal($('#vibcrystal'));
    //dispersion
    d = new PhononHighcharts($('#highcharts'));
    //phonon class
    p = new PhononWebpage(v,d);

    /*
    check if its Chrome 1+ taken from
    http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
    only show webm button for chrome
    */
    let isChrome = !!window.chrome && !!window.chrome.webstore;
    if (!isChrome) {
        $('#webmbutton')[0].style.visibility = 'hidden';
    }

    //get if the draw vectors option is activated
    v.arrows = $('#drawvectors')[0].checked;
    $('#file-input')[0].addEventListener('change', p.loadCustomFile.bind(p), false);
    $('#file-input')[0].addEventListener('click', function() { this.value = '';}, false);
    p.updateMenu();

    let url_vars = PhononWebpage.getUrlVars();
    if (url_vars) { p.loadURL(url_vars); }
    else          { p.loadLocal();       }

    // check if webgl is available
    if ( ! Detector.webgl ) {
        Detector.addGetWebGLMessage();
    }

    //jquery to make an action once you change the number of repetitions
    $(".input-rep").keyup(function(event){
        if(event.keyCode == 13) p.update(dispersion=false);
    });

});
<commit_msg>Fixed broken links for phonondb<commit_after>const pi = 3.14159265359;
const bohr2ang = 0.529177249;

//default folder
var folder = "graphene";

class PhononWebpage {

    constructor(visualizer, dispersion) {
        this.k = 0;
        this.n = 0;
        this.nx = 1;
        this.ny = 1;
        this.nz = 1;
        this.amplitude = 0.5;

        //select visualization
        this.visualizer = visualizer;

        //select dispersion
        this.dispersion = dispersion;

        //bind some functions (TODO: improve this)
        this.exportXSF    = exportXSF.bind(this);
        this.exportPOSCAR = exportPOSCAR.bind(this);
    }

    getRepetitions() {
        /*
        read the number of repetitions in each direction and update it
        */
        this.nx = $('#nx').val();
        this.ny = $('#ny').val();
        this.nz = $('#nz').val();
    }

    setRepetitions(repetitions) {
        /*
        set the number of repetitions on the interface
        */

        if (repetitions) {
            this.nx = repetitions[0];
            this.ny = repetitions[1];
            this.nz = repetitions[2];
        }

        $('#nx').val(this.nx);
        $('#ny').val(this.ny);
        $('#nz').val(this.nz);
    }

    loadCustomFile(event) {
        /*
        find the type of file and call the corresponding function to read it

        two formats available:
            phonopy files (band.yaml)
            internal .json format (*.json) description available in ./phononweb/phononweb.py
        */

        let yaml = null;
        let json = null;

        for (let i=0; i<event.target.files.length; i++) {
            let file = event.target.files[i];
            if (file.name.indexOf(".yaml") > -1) { yaml = file; }
            if (file.name.indexOf(".json") > -1) { json = file; }
        }

        this.name = "Custom file"
        if      (json) {
            this.phonon = new PhononJson();
            this.phonon.getFromFile(json, this.loadCallback.bind(this) );
        }
        else if (yaml) {
            this.phonon = new PhononYaml();
            this.phonon.getFromFile(yaml, this.loadCallback.bind(this) );
        }
        else {
            alert("Ivalid file");
        }
    }

    loadURL(url_vars) {
        /*
        load file from post request in the url

        two formats available:
            phonopy files (band.yaml)
            internal .json format (*.json) description available in ./phononweb/phononweb.py
        */

        let yaml = null;
        let json = null;

        for (let key in url_vars) {
            if ( key == "yaml" ) { yaml = $.get(url_vars[key]).responseText; }
            if ( key == "json" ) { json = $.get(url_vars[key]).responseText; }
            if ( key == "name" ) { $('#t1').html(url_vars[key]);     }
        }

        this.name = "Custom file"
        if      (json) {
            this.phonon = new PhononJson();
            this.phonon.getFromString(json, this.loadCallback.bind(this) );
        }
        else if (yaml) {
            this.phonon = new PhononYaml();
            this.phonon.getFromString(yaml, this.loadCallback.bind(this) );
        }
        else {
            alert("Ivalid url");
        }
    }

    loadId(id) {
        /*
        load a material from phonodb
        http://phonondb.mtl.kyoto-u.ac.jp
        */

        this.loadURL( { yaml: this.materials[id]['url'] } );
        this.name = this.materials[id]['name'] +  " mp-"+id+"";
        this.update();
    }

    loadLocal() {
        /*
        read structure from a local file distributed with the repository
        */

        let readJson = function(string) {
            this.phonon = new PhononJson();
            this.phonon.getFromString(string, this.loadCallback.bind(this) );
        }

        $.get(folder+'/data.json', readJson.bind(this), "html" );
    }

    loadCallback() {
        /*
        Fuunction to be called once the file is loaded
        */
        this.setRepetitions(this.phonon.repetitions);
        this.update()
    }

    getStructure(nx,ny,nz) {
        let lat = this.phonon.lat;
        let apc = this.phonon.atom_pos_car;
        let atoms = [];

	    for (let ix=0;ix<nx;ix++) {
            for (let iy=0;iy<ny;iy++) {
                for (let iz=0;iz<nz;iz++) {
                    for (let i=0;i<this.phonon.natoms;i++) {

                        //postions of the atoms
                        let x = apc[i][0] + ix*lat[0][0] + iy*lat[1][0] + iz*lat[2][0];
                        let y = apc[i][1] + ix*lat[0][1] + iy*lat[1][1] + iz*lat[2][1];
                        let z = apc[i][2] + ix*lat[0][2] + iy*lat[1][2] + iz*lat[2][2];

                        atoms.push( [i,x,y,z] );
                    }
                }
            }
        }

        return atoms;
    }

    getBondingDistance() {
        /*
        replicate the atoms two times in each direction
        */
        let atoms = this.getStructure(2,2,2);

        let combinations = getCombinations( atoms );
        let min = 1e9;
        for (let i=0; i<combinations.length; i++ ) {
            let a = combinations[i][0];
            let b = combinations[i][1];

            let distance = dist(a.slice(1),b.slice(1));
            if (min > distance) {
                min = distance;
            }
        }
        return min;
    }

    getVibrations(nx,ny,nz) {
        /*
        Calculate the vibration patterns for all the atoms
        */
        let phonon = this.phonon;
        let veckn = phonon.vec[this.k][this.n];
        let vibrations = [];
        let kpt = phonon.kpoints[this.k];

        //additional phase if necessary
        let atom_phase = []
        if (phonon.addatomphase) {
            for (let i=0; i<phonon.natoms; i++) {
                let phase = kpt[0]*phonon.atom_pos_red[i][0] +
                        kpt[1]*phonon.atom_pos_red[i][1] +
                        kpt[2]*phonon.atom_pos_red[i][2];
                atom_phase.push(phase);
            }
        }
        else {
            for (let i=0; i<phonon.natoms; i++) {
                atom_phase.push(0);
            }
        }

        for (var ix=0; ix<nx; ix++) {
            for (var iy=0; iy<ny; iy++) {
                for (var iz=0; iz<nz; iz++) {

                    for (let i=0; i<phonon.natoms; i++) {
                        let sprod = kpt[0]*ix + kpt[1]*iy + kpt[2]*iz + atom_phase[i];
                        let phase = Complex.Polar(1.0,sprod*2.0*pi);

                        //Displacements of the atoms
                        let x = Complex(veckn[i][0][0],veckn[i][0][1]).mult(phase);
                        let y = Complex(veckn[i][1][0],veckn[i][1][1]).mult(phase);
                        let z = Complex(veckn[i][2][0],veckn[i][2][1]).mult(phase);

                        vibrations.push( [x,y,z] );
                    }
                }
            }
        }

        return vibrations;
    }

    setVibrations() {
        this.vibrations = this.getVibrations(this.nx,this.ny,this.nz);
    }

    updatePage() {
        /*
        lattice vectors table
        */

        for (let i=0; i<3; i++) {
            for (let j=0; j<3; j++) {
                //round lattice values
                $('#uc_'+i+j).html( this.phonon.lat[i][j].toPrecision(5) );
            }
        }

        //unit cell table
        $('#uc_natoms').html( this.phonon.natoms );
        $('#uc_atypes').html( this.phonon.formula );

        //atomic positions table
        let pos = this.phonon.atom_pos_red;
        $('#atompos').empty() //clean the atomic positions table
        for (let i=0; i<this.phonon.natoms; i++) {
            $('#atompos').append('

');
            $('#atompos tr:last').append(''+this.phonon.atom_types[i]+'	');
            for (let j=0; j<3; j++) {
                $('#atompos tr:last').append(''+pos[i][j].toFixed(4)+'	');
            }
        }

        //update title
        $('#t1').html(this.name);
    }

    update(dispersion=true) {
        /*
        Update all the aspects fo the webpage
        */

        //update structure
        this.getRepetitions();
        this.atoms = this.getStructure(this.nx,this.ny,this.nz);
        this.vibrations = this.getVibrations(this.nx,this.ny,this.nz);
        this.phonon.nndist = this.getBondingDistance();

        //update page
        this.updatePage();

        //update dispersion
        if (dispersion) { this.dispersion.update(this.phonon); }

        //update visualizer
        this.visualizer.update(this);
    }

    createPhonodbMenu(phonodb) {
        /*
        Create the phonondb menu
        */

        $("#div-phonodb").css('display', 'inline');
        let materials = jsyaml.load(phonodb);
        let materials_ref = {};
        $('#phonodb').empty();
        for (let i=0;i<materials.length;i++) {
            let material = materials[i];
            materials_ref[material['id']] = material;
            $('#phonodb').append('

');
            $('#phonodb li:last').append(""+material['name']+"");
        }

        this.materials = materials_ref;
    }

    updateMenu() {
        /*
        create menu with:
            local files (files distributed with the website)
            files from the phonodb database
        */

        //get a list of local materials
        $.getJSON('models.json', function(data) {
            let nmodels = data["nmodels"];
            let models  = data["models"];
            $('#mat').empty() //clean the atomic positions table

            for (let i=0; i<nmodels; i++) {
                $('#mat').append('

');
                $('#mat li:last').append(""+models[i]["name"]+"");
            }
        });

        //get a list of materials from phonodb
        $.get('phonondb.yaml', this.createPhonodbMenu.bind(this));
    }

    static getUrlVars() {
        /*
        get variables from the url
        from http://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url

        currently the possible options are:
            json : load a json file from location
            yaml : load a yaml file from location
            name : change the display name of the material
        */
        let vars = {};
        let hash;

        if (location.search) {
            let hashes = location.search.slice(1).split('&');
            for(let i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars[hash[0]] = hash[1];
            }
            return vars;
        }
        else {
            return null;
        }
    }

}

$(document).ready(function() {

    //visualizer
    v = new VibCrystal($('#vibcrystal'));
    //dispersion
    d = new PhononHighcharts($('#highcharts'));
    //phonon class
    p = new PhononWebpage(v,d);

    /*
    check if its Chrome 1+ taken from
    http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
    only show webm button for chrome
    */
    let isChrome = !!window.chrome && !!window.chrome.webstore;
    if (!isChrome) {
        $('#webmbutton')[0].style.visibility = 'hidden';
    }

    //get if the draw vectors option is activated
    v.arrows = $('#drawvectors')[0].checked;
    $('#file-input')[0].addEventListener('change', p.loadCustomFile.bind(p), false);
    $('#file-input')[0].addEventListener('click', function() { this.value = '';}, false);
    p.updateMenu();

    let url_vars = PhononWebpage.getUrlVars();
    if (url_vars) { p.loadURL(url_vars); }
    else          { p.loadLocal();       }

    // check if webgl is available
    if ( ! Detector.webgl ) {
        Detector.addGetWebGLMessage();
    }

    //jquery to make an action once you change the number of repetitions
    $(".input-rep").keyup(function(event){
        if(event.keyCode == 13) p.update(dispersion=false);
    });

});
<|endoftext|>


<commit_before>import Promise from 'bluebird';
import Discordie from 'discordie';
import nconf from 'nconf';
import R from 'ramda';

import './init-config';
import './express';
import './phantom';

import commands from './commands';
import datadog from './datadog';
import logger from './logger';
import sentry from './sentry';

import { startPortalIntervals, startPortalTimeouts } from './portals';
import { createDuplicateClient, getMessageTTL, setMessageTTL, getUserLang } from './redis';

// Init
const discordie_options = {};
if (nconf.get('SHARDING')) {
  discordie_options.shardCount = Number(nconf.get('SHARD_COUNT'));
  discordie_options.shardId = Number(nconf.get('SHARD_NUMBER'));
}

const client = new Discordie(discordie_options);
let initialized = false;

function callCmd(cmd, name, client, evt, suffix) {
  logger.cmd(name, suffix);
  datadog(`cmd.${name}`, 1);

  function processEntry(entry) {
    // If string or number, send as a message
    if (R.is(String, entry) || R.is(Number, entry)) evt.message.channel.sendMessage(entry)
      .catch((err, res) => {
        err.res = res;
        sentry(err, 'discordie.sendMessage');
      });
    // If buffer, send as a file, with a default name
    if (Buffer.isBuffer(entry)) evt.message.channel.uploadFile(entry, 'file.png')
      .catch((err, res) => {
        err.res = res;
        sentry(err, 'discordie.uploadFile');
      });
    // If it's an object that contains key 'upload', send file with an optional file name
    // This works for both uploading local files and buffers
    if (R.is(Object, entry) && entry.upload) evt.message.channel.uploadFile(entry.upload, entry.filename)
      .catch((err, res) => {
        err.res = res;
        sentry(err, 'discordie.uploadFile');
      });
  }

  const user_id = evt.message.author.id;
  const start_time = new Date().getTime();
  getMessageTTL(user_id).then(exists => {
    // If a user is trying to spam messages above the set TTL time, then skip.
    if (exists) return;
    setMessageTTL(user_id);

    return getUserLang(user_id).then(lang => {
      const cmd_return = cmd(client, evt, suffix, lang);

      // All command returns must be a bluebird promise.
      if (cmd_return instanceof Promise) {
        return cmd_return.then(res => {
          const execution_time = new Date().getTime() - start_time;
          datadog(`cmd_execution_time.${name}`, execution_time);
          // If null, don't do anything.
          if (!res) return logger.warn(`Command ${name} didn't return anything. Suffix: ${suffix}`);
          // If it's an array, process each entry.
          if (R.is(Array, res)) return R.forEach(processEntry, res);
          // Process single entry
          processEntry(res);
        })
        .catch(err => {
          sentry(err, name);
          evt.message.channel.sendMessage(`Error: ${err.message}`);
        });
      }
    });
  })
  .catch(err => {
    sentry(err, name);
  });
}

function onMessage(evt) {
  if (!evt.message) return;
  if (client.User.id === evt.message.author.id) return;

  // Checks for PREFIX
  if (evt.message.content[0] === nconf.get('PREFIX')) {
    const command = evt.message.content.toLowerCase().split(' ')[0].substring(1);
    const suffix = evt.message.content.substring(command.length + 2);
    const cmd = commands[command];

    if (cmd) callCmd(cmd, command, client, evt, suffix);
    return;
  }

  // Checks if bot was mentioned
  if (client.User.isMentioned(evt.message)) {
    const msg_split = evt.message.content.split(' ');

    // If bot was mentioned without a command, then skip.
    if (!msg_split[1]) return;

    const suffix = R.join(' ', R.slice(2, msg_split.length, msg_split));
    let cmd_name = msg_split[1].toLowerCase();
    if (cmd_name[0] === nconf.get('PREFIX')) cmd_name = cmd_name.slice(1);
    const cmd = commands[cmd_name];

    if (cmd) callCmd(cmd, cmd_name, client, evt, suffix);
    return;
  }

  // Check personal messages
  if (evt.message.channel.isPrivate()) {
    // Handle invite links
    if (evt.message.content.indexOf('https://discord.gg/') > -1 || evt.message.content.indexOf('https://discordapp.com/invite/') > -1) {
      return commands.join(client, evt, evt.message.content);
    }

    const msg_split = evt.message.content.split(' ');
    const suffix = R.join(' ', R.slice(1, msg_split.length, msg_split));
    const cmd_name = msg_split[0].toLowerCase();
    const cmd = commands[cmd_name];

    if (cmd) callCmd(cmd, cmd_name, client, evt, suffix);
    return;
  }
}

if (nconf.get('SHARDING')) {
  const pubClient = createDuplicateClient('cmd processor pub');
  const subClient = createDuplicateClient('cmd processor sub');
  subClient.on('message', (channel, message) => {
    const { channel_name, instance, request: { cmd, suffix, lang } } = JSON.parse(message);
    if (instance === nconf.get('SHARD_NUMBER')) return;

    commands[cmd](client, {}, suffix, lang, true)
      .then(results => {
        pubClient.publish(channel_name, JSON.stringify({instance: nconf.get('SHARD_NUMBER'), results}));
      });
  });
  subClient.subscribe('cmd');
}

function connect() {
  if (!nconf.get('TOKEN') || !nconf.get('CLIENT_ID')) {
    logger.error('Please setup TOKEN and CLIENT_ID in config.js to use Gravebot');
    process.exit(1);
  }

  client.connect({token: nconf.get('TOKEN')});
}

function forceFetchUsers() {
  logger.info('Force fetching users');
  client.Users.fetchMembers();
}

// Listen for events on Discord
client.Dispatcher.on('GATEWAY_READY', () => {
  logger.info(`Started successfully. Connected to ${client.Guilds.length} servers.`);
  setTimeout(forceFetchUsers, 45000);

  if (!initialized) {
    initialized = true;
    startPortalTimeouts(client);

    client.Dispatcher.on('MESSAGE_CREATE', onMessage);
    client.Dispatcher.on('MESSAGE_UPDATE', onMessage);
  }
});

client.Dispatcher.on('DISCONNECTED', err => {
  logger.warn('Disconnected. Attempting to reconnect...');
  sentry(err, 'discord');
  setTimeout(connect, 2000);
});

startPortalIntervals(client);
connect();
<commit_msg>check evt isPrivate method<commit_after>import Promise from 'bluebird';
import Discordie from 'discordie';
import nconf from 'nconf';
import R from 'ramda';

import './init-config';
import './express';
import './phantom';

import commands from './commands';
import datadog from './datadog';
import logger from './logger';
import sentry from './sentry';

import { startPortalIntervals, startPortalTimeouts } from './portals';
import { createDuplicateClient, getMessageTTL, setMessageTTL, getUserLang } from './redis';

// Init
const discordie_options = {};
if (nconf.get('SHARDING')) {
  discordie_options.shardCount = Number(nconf.get('SHARD_COUNT'));
  discordie_options.shardId = Number(nconf.get('SHARD_NUMBER'));
}

const client = new Discordie(discordie_options);
let initialized = false;

function callCmd(cmd, name, client, evt, suffix) {
  logger.cmd(name, suffix);
  datadog(`cmd.${name}`, 1);

  function processEntry(entry) {
    // If string or number, send as a message
    if (R.is(String, entry) || R.is(Number, entry)) evt.message.channel.sendMessage(entry)
      .catch((err, res) => {
        err.res = res;
        sentry(err, 'discordie.sendMessage');
      });
    // If buffer, send as a file, with a default name
    if (Buffer.isBuffer(entry)) evt.message.channel.uploadFile(entry, 'file.png')
      .catch((err, res) => {
        err.res = res;
        sentry(err, 'discordie.uploadFile');
      });
    // If it's an object that contains key 'upload', send file with an optional file name
    // This works for both uploading local files and buffers
    if (R.is(Object, entry) && entry.upload) evt.message.channel.uploadFile(entry.upload, entry.filename)
      .catch((err, res) => {
        err.res = res;
        sentry(err, 'discordie.uploadFile');
      });
  }

  const user_id = evt.message.author.id;
  const start_time = new Date().getTime();
  getMessageTTL(user_id).then(exists => {
    // If a user is trying to spam messages above the set TTL time, then skip.
    if (exists) return;
    setMessageTTL(user_id);

    return getUserLang(user_id).then(lang => {
      const cmd_return = cmd(client, evt, suffix, lang);

      // All command returns must be a bluebird promise.
      if (cmd_return instanceof Promise) {
        return cmd_return.then(res => {
          const execution_time = new Date().getTime() - start_time;
          datadog(`cmd_execution_time.${name}`, execution_time);
          // If null, don't do anything.
          if (!res) return logger.warn(`Command ${name} didn't return anything. Suffix: ${suffix}`);
          // If it's an array, process each entry.
          if (R.is(Array, res)) return R.forEach(processEntry, res);
          // Process single entry
          processEntry(res);
        })
        .catch(err => {
          sentry(err, name);
          evt.message.channel.sendMessage(`Error: ${err.message}`);
        });
      }
    });
  })
  .catch(err => {
    sentry(err, name);
  });
}

function onMessage(evt) {
  if (!evt.message) return;
  if (client.User.id === evt.message.author.id) return;

  // Checks for PREFIX
  if (evt.message.content[0] === nconf.get('PREFIX')) {
    const command = evt.message.content.toLowerCase().split(' ')[0].substring(1);
    const suffix = evt.message.content.substring(command.length + 2);
    const cmd = commands[command];

    if (cmd) callCmd(cmd, command, client, evt, suffix);
    return;
  }

  // Checks if bot was mentioned
  if (client.User.isMentioned(evt.message)) {
    const msg_split = evt.message.content.split(' ');

    // If bot was mentioned without a command, then skip.
    if (!msg_split[1]) return;

    const suffix = R.join(' ', R.slice(2, msg_split.length, msg_split));
    let cmd_name = msg_split[1].toLowerCase();
    if (cmd_name[0] === nconf.get('PREFIX')) cmd_name = cmd_name.slice(1);
    const cmd = commands[cmd_name];

    if (cmd) callCmd(cmd, cmd_name, client, evt, suffix);
    return;
  }

  // Check personal messages
  if (evt.message.channel.isPrivate && evt.message.channel.isPrivate()) {
    // Handle invite links
    if (evt.message.content.indexOf('https://discord.gg/') > -1 || evt.message.content.indexOf('https://discordapp.com/invite/') > -1) {
      return commands.join(client, evt, evt.message.content);
    }

    const msg_split = evt.message.content.split(' ');
    const suffix = R.join(' ', R.slice(1, msg_split.length, msg_split));
    const cmd_name = msg_split[0].toLowerCase();
    const cmd = commands[cmd_name];

    if (cmd) callCmd(cmd, cmd_name, client, evt, suffix);
    return;
  }
}

if (nconf.get('SHARDING')) {
  const pubClient = createDuplicateClient('cmd processor pub');
  const subClient = createDuplicateClient('cmd processor sub');
  subClient.on('message', (channel, message) => {
    const { channel_name, instance, request: { cmd, suffix, lang } } = JSON.parse(message);
    if (instance === nconf.get('SHARD_NUMBER')) return;

    commands[cmd](client, {}, suffix, lang, true)
      .then(results => {
        pubClient.publish(channel_name, JSON.stringify({instance: nconf.get('SHARD_NUMBER'), results}));
      });
  });
  subClient.subscribe('cmd');
}

function connect() {
  if (!nconf.get('TOKEN') || !nconf.get('CLIENT_ID')) {
    logger.error('Please setup TOKEN and CLIENT_ID in config.js to use Gravebot');
    process.exit(1);
  }

  client.connect({token: nconf.get('TOKEN')});
}

function forceFetchUsers() {
  logger.info('Force fetching users');
  client.Users.fetchMembers();
}

// Listen for events on Discord
client.Dispatcher.on('GATEWAY_READY', () => {
  logger.info(`Started successfully. Connected to ${client.Guilds.length} servers.`);
  setTimeout(forceFetchUsers, 45000);

  if (!initialized) {
    initialized = true;
    startPortalTimeouts(client);

    client.Dispatcher.on('MESSAGE_CREATE', onMessage);
    client.Dispatcher.on('MESSAGE_UPDATE', onMessage);
  }
});

client.Dispatcher.on('DISCONNECTED', err => {
  logger.warn('Disconnected. Attempting to reconnect...');
  sentry(err, 'discord');
  setTimeout(connect, 2000);
});

startPortalIntervals(client);
connect();
<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

var Stats = function () {

	var mode = 0;

	var container = document.createElement( 'div' );
	container.style.cssText = 'opacity:0.9;cursor:pointer';
	container.addEventListener( 'click', function ( event ) {

		event.preventDefault();

		showPanel( ++ mode % container.children.length );

	}, false );

	//

	function addPanel( panel ) {

		container.appendChild( panel.dom );
		return panel;

	}

	function showPanel( id ) {

		for ( var i = 0; i < container.children.length; i ++ ) {

			container.children[ i ].style.display = i === id ? 'block' : 'none';

		}

	}

	//

	var beginTime = ( performance || Date ).now(), prevTime = beginTime, frames = 0;

	var fpsPanel = addPanel( new Stats.Panel( 'FPS', '#0ff', '#002' ) );
	var msPanel = addPanel( new Stats.Panel( 'MS', '#0f0', '#020' ) );

	if ( self.performance && self.performance.memory ) {

		var memPanel = addPanel( new Stats.Panel( 'MB', '#f08', '#201' ) );

	}

	showPanel( 0 );

	return {

		REVISION: 15,

		domElement: container,

		addPanel: addPanel,
		showPanel: showPanel,

		setMode: showPanel, // backwards compatibility

		begin: function () {

			beginTime = ( performance || Date ).now();

		},

		end: function () {

			frames ++;

			var time = ( performance || Date ).now();

			msPanel.update( time - beginTime, 200 );

			if ( time > prevTime + 1000 ) {

				fpsPanel.update( ( frames * 1000 ) / ( time - prevTime ), 100 );

				prevTime = time;
				frames = 0;

				if ( memPanel !== undefined ) {

					var memory = performance.memory;
					memPanel.update( memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576 );

				}

			}

			return time;

		},

		update: function () {

			beginTime = this.end();

		}

	};

};

Stats.Panel = function ( name, fg, bg ) {

	var canvas = document.createElement( 'canvas' );
	canvas.width = 80;
	canvas.height = 48;

	var context = canvas.getContext( '2d' );

	context.fillStyle = bg;
	context.fillRect( 0, 0, 80, 48 );

	context.font = 'bold 9px Helvetica,Arial,sans-serif';
	context.fillStyle = fg;
	context.fillText( name, 3, 10 );
	context.fillRect( 3, 15, 74, 30 );

	context.fillStyle = bg;
	context.globalAlpha = 0.9;
	context.fillRect( 3, 15, 74, 30 );

	var min = Infinity, max = 0;

	return {

		dom: canvas,

		update: function ( value, maxValue ) {

			min = Math.min( min, value );
			max = Math.max( max, value );

			context.fillStyle = bg;
			context.fillRect( 0, 0, 80, 15 );
			context.fillStyle = fg;
			context.fillText( ( value | 0 ) + ' ' + name + ' (' + ( min | 0 ) + '-' + ( max | 0 ) + ')', 3, 10 );

			context.drawImage( canvas, 4, 15, 74, 30, 3, 15, 74, 30 );

			context.fillRect( 76, 15, 1, 30 );

			context.fillStyle = bg;
			context.globalAlpha = 0.9;
			context.fillRect( 76, 15, 1, 30 - ( ( value / maxValue ) * 30 ) | 0 );
			context.globalAlpha = 1;

		}

	};

};

if ( typeof module === 'object' ) {

	module.exports = Stats;

}
<commit_msg>Fixed alpha glitch.<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

var Stats = function () {

	var mode = 0;

	var container = document.createElement( 'div' );
	container.style.cssText = 'opacity:0.9;cursor:pointer';
	container.addEventListener( 'click', function ( event ) {

		event.preventDefault();

		showPanel( ++ mode % container.children.length );

	}, false );

	//

	function addPanel( panel ) {

		container.appendChild( panel.dom );
		return panel;

	}

	function showPanel( id ) {

		for ( var i = 0; i < container.children.length; i ++ ) {

			container.children[ i ].style.display = i === id ? 'block' : 'none';

		}

	}

	//

	var beginTime = ( performance || Date ).now(), prevTime = beginTime, frames = 0;

	var fpsPanel = addPanel( new Stats.Panel( 'FPS', '#0ff', '#002' ) );
	var msPanel = addPanel( new Stats.Panel( 'MS', '#0f0', '#020' ) );

	if ( self.performance && self.performance.memory ) {

		var memPanel = addPanel( new Stats.Panel( 'MB', '#f08', '#201' ) );

	}

	showPanel( 0 );

	return {

		REVISION: 15,

		domElement: container,

		addPanel: addPanel,
		showPanel: showPanel,

		setMode: showPanel, // backwards compatibility

		begin: function () {

			beginTime = ( performance || Date ).now();

		},

		end: function () {

			frames ++;

			var time = ( performance || Date ).now();

			msPanel.update( time - beginTime, 200 );

			if ( time > prevTime + 1000 ) {

				fpsPanel.update( ( frames * 1000 ) / ( time - prevTime ), 100 );

				prevTime = time;
				frames = 0;

				if ( memPanel !== undefined ) {

					var memory = performance.memory;
					memPanel.update( memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576 );

				}

			}

			return time;

		},

		update: function () {

			beginTime = this.end();

		}

	};

};

Stats.Panel = function ( name, fg, bg ) {

	var canvas = document.createElement( 'canvas' );
	canvas.width = 80;
	canvas.height = 48;

	var context = canvas.getContext( '2d' );

	context.fillStyle = bg;
	context.fillRect( 0, 0, 80, 48 );

	context.font = 'bold 9px Helvetica,Arial,sans-serif';
	context.fillStyle = fg;
	context.fillText( name, 3, 10 );
	context.fillRect( 3, 15, 74, 30 );

	context.fillStyle = bg;
	context.globalAlpha = 0.9;
	context.fillRect( 3, 15, 74, 30 );

	var min = Infinity, max = 0;

	return {

		dom: canvas,

		update: function ( value, maxValue ) {

			min = Math.min( min, value );
			max = Math.max( max, value );

			context.globalAlpha = 1;
			context.fillStyle = bg;
			context.fillRect( 0, 0, 80, 15 );
			context.fillStyle = fg;
			context.fillText( ( value | 0 ) + ' ' + name + ' (' + ( min | 0 ) + '-' + ( max | 0 ) + ')', 3, 10 );

			context.drawImage( canvas, 4, 15, 74, 30, 3, 15, 74, 30 );

			context.fillRect( 76, 15, 1, 30 );

			context.fillStyle = bg;
			context.globalAlpha = 0.9;
			context.fillRect( 76, 15, 1, 30 - ( ( value / maxValue ) * 30 ) | 0 );

		}

	};

};

if ( typeof module === 'object' ) {

	module.exports = Stats;

}
<|endoftext|>


<commit_before>// Copyright (c) 2011, Centrum Cyfrowe
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Centrum Cyfrowe nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var _download = (function () {

    var that = {};

    // ids = { '0': [{ id: 2, scope: 'full' }, { id: 3, scope: 'sheet' }], '4': [{ id: 1, scope: 'sheet' }] }
    that.selected = function ( ids ) {
        var i, columns;
        var group, sheet;
        var csv_string = '';

        for( group_id in ids ) {
            ids[group_id].forEach( function ( e ) {
                if( e['scope'] === 'full' ) {
                    group = _store.get_group( group_id );
                    csv_string += group['dataset'] + '-';
                    csv_string += group['perspective'] + '-';
                    csv_string += group['issue'] + '.csv';
                }
                else {
                    sheet = _store.get_sheet( group_id, e['id'] );
                    columns = sheet['columns'];

                    csv_string += 'ID;Rodzic;Poziom;';

                    for( i = 0; i < columns.length; i += 1 ) {
                        csv_string += columns[i]['label'];
                        csv_string += ';';
                    }
                    csv_string += '|';

                    if( sheet['filtered'] ) {
                        csv_string += add_filtered( sheet );
                    }
                    else {
                        csv_string += add_children( sheet );
                    }
                }
                // end of file string
                csv_string += '--file--';
            });
        }

        // send it to server for further processing!!
        $('#download-form')
            .find('input')
            .val( csv_string )
            .end()
            .submit();
    };

    return that;

//  P R I V A T E   I N T E R F A C E

    function add_filtered( sheet ) {
        var result = '';
        var hashed = _utils.hash_list( sheet['rows'] );
        var sorted_keys = (function () {
            var key;
            var result = [];

            for( key in hashed ) {
                result.push( key );
            }

            return result.sort();
        })();
        var top_level = sorted_keys.shift();

        // top level first
        hashed[ top_level ].sort( function ( a, b ) {
                               return a['data']['idef'] > b['data']['idef'];
                           })
                           .forEach( function ( e ) {
                               result += add_row( e, sheet['columns'] );
                           });

        // children levels
        sorted_keys.forEach( function ( level ) {
            hashed[ level ].sort( function( a, b ) {
                                return a['data']['idef'] < b['data']['idef'];
                           })
                           .forEach( function ( e ) {
                                result += add_child( e, sheet['columns'] );
                           });
        });

        return result;
    }

    function add_row( node, columns ) {
        var result = '';

        result += node['idef'] + ';';
        if( !!node['parent'] === false ) {
            result += ';';
        }
        else {
            result += node['parent'] + ';';
        }
        result += node['level'] + ';';

        columns.forEach( function ( e ) {
            result += node[ columns[j]['key'] ];
            result += ';';
        });

        result += '|';

        return result;
    }

    function add_child( node, columns ) {
        // TODO code here
        return '';
    }

    function add_children( sheet, parent, result ) {
        var parent = parent || null;
        var result = result || '';
        var i, node, open;
        var columns = sheet['columns'];
        var children = sheet['rows'].filter( function ( e ) {
            return e['data']['parent'] === parent;
        });

        if( children.length === 0 ) {
            return result;
        }

        for( i = 0; i < children.length; i += 1 ) {
            node = children[i]['data'];
            open = children[i]['state']['open'];

            result += node['idef'] + ';';
            if( !!node['parent'] === false ) {
                result += ';';
            }
            else {
                result += node['parent'] + ';';
            }
            result += node['level'] + ';';

            for( j = 0; j < columns.length; j += 1 ) {
                result += node[ columns[j]['key'] ];
                result += ';';
            }
            result += '|';

            if( open === false ) {
                continue;
            }
            else {
                result = add_children( sheet, node['idef'], result );
            }
        }
        return result;
    }

})();
<commit_msg>typo fixed<commit_after>// Copyright (c) 2011, Centrum Cyfrowe
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of the Centrum Cyfrowe nor the names of its contributors
//     may be used to endorse or promote products derived from this software
//     without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
// GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

var _download = (function () {

    var that = {};

    // ids = { '0': [{ id: 2, scope: 'full' }, { id: 3, scope: 'sheet' }], '4': [{ id: 1, scope: 'sheet' }] }
    that.selected = function ( ids ) {
        var i, columns;
        var group, sheet;
        var csv_string = '';

        for( group_id in ids ) {
            ids[group_id].forEach( function ( e ) {
                if( e['scope'] === 'full' ) {
                    group = _store.get_group( group_id );
                    csv_string += group['dataset'] + '-';
                    csv_string += group['perspective'] + '-';
                    csv_string += group['issue'] + '.csv';
                }
                else {
                    sheet = _store.get_sheet( group_id, e['id'] );
                    columns = sheet['columns'];

                    csv_string += 'ID;Rodzic;Poziom;';

                    for( i = 0; i < columns.length; i += 1 ) {
                        csv_string += columns[i]['label'];
                        csv_string += ';';
                    }
                    csv_string += '|';

                    if( sheet['filtered'] ) {
                        csv_string += add_filtered( sheet );
                    }
                    else {
                        csv_string += add_children( sheet );
                    }
                }
                // end of file string
                csv_string += '--file--';
            });
        }

        // send it to server for further processing!!
        $('#download-form')
            .find('input')
            .val( csv_string )
            .end()
            .submit();
    };

    return that;

//  P R I V A T E   I N T E R F A C E

    function add_filtered( sheet ) {
        var result = '';
        var hashed = _utils.hash_list( sheet['rows'] );
        var sorted_keys = (function () {
            var key;
            var result = [];

            for( key in hashed ) {
                result.push( key );
            }

            return result.sort();
        })();
        var top_level = sorted_keys.shift();

        // top level first
        hashed[ top_level ].sort( function ( a, b ) {
                               return a['data']['idef'] > b['data']['idef'];
                           })
                           .forEach( function ( e ) {
                               result += add_row( e, sheet['columns'] );
                           });

        // children levels
        sorted_keys.forEach( function ( level ) {
            hashed[ level ].sort( function( a, b ) {
                                return a['data']['idef'] < b['data']['idef'];
                           })
                           .forEach( function ( e ) {
                                result += add_child( e, sheet['columns'] );
                           });
        });

        return result;
    }

    function add_row( node, columns ) {
        var result = '';

        result += node['idef'] + ';';
        if( !!node['parent'] === false ) {
            result += ';';
        }
        else {
            result += node['parent'] + ';';
        }
        result += node['level'] + ';';

        columns.forEach( function ( e ) {
            result += node[ e['key'] ];
            result += ';';
        });

        result += '|';

        return result;
    }

    function add_child( node, columns ) {
        // TODO code here
        return '';
    }

    function add_children( sheet, parent, result ) {
        var parent = parent || null;
        var result = result || '';
        var i, node, open;
        var columns = sheet['columns'];
        var children = sheet['rows'].filter( function ( e ) {
            return e['data']['parent'] === parent;
        });

        if( children.length === 0 ) {
            return result;
        }

        for( i = 0; i < children.length; i += 1 ) {
            node = children[i]['data'];
            open = children[i]['state']['open'];

            result += node['idef'] + ';';
            if( !!node['parent'] === false ) {
                result += ';';
            }
            else {
                result += node['parent'] + ';';
            }
            result += node['level'] + ';';

            for( j = 0; j < columns.length; j += 1 ) {
                result += node[ columns[j]['key'] ];
                result += ';';
            }
            result += '|';

            if( open === false ) {
                continue;
            }
            else {
                result = add_children( sheet, node['idef'], result );
            }
        }
        return result;
    }

})();
<|endoftext|>


<commit_before>/**
 * Player Object
 */
const Player = {

    YTPlayer: undefined,
    update: undefined,

    GUI: {
        title: document.getElementById("title"),
        time: document.getElementById("time"),
        duration: document.getElementById("duration"),
        controls: {
            play: document.getElementById("play")
        },
        searchField: document.getElementById("search")
    },

    /**
     * Gets fired when the YT Player is Loaded
     */
    onReady: function(event) {
        console.log("PLAYER IS LOADED");
        //let player = event.target;
        //let videoUrl = Player.loadByUrl(Player.GUI.searchField.value);
        //Check if URL is a playlist

        //Player.YTPlayer.loadVideoByUrl("https://www.youtube.com/v/blpl4swRxgQ?version=3");

        Player.GUI.title.innerText = Player.YTPlayer.getVideoData().title;

        //Display time
        let duration = Player.formatTime(Player.YTPlayer.getDuration());
        Player.GUI.duration.innerText = duration;
        Player.GUI.time.innerText = "00:00";

        //Add event listeners for the GUI
        Player.GUI.controls.play.addEventListener("click", Player.changeVideoState);

        //Initialise updateTime function
        Player.update = setInterval(Player.updateTime, 1000);

        //Start the video
        Player.play();
    },

    /**
     * Gets called when the state of the player gets changed
     */
    onStateChange: function(event) {
        const player = event.target;
        console.log("State changed to: ", player.getPlayerState());
    },

    /**
     * Switches between playing and pausing
     */
    changeVideoState: function() {
        if(Player.YTPlayer.getPlayerState() == YT.PlayerState.PLAYING) {
            clearInterval(Player.update);
            Player.pause();
        } else {
            Player.update = setInterval(Player.updateTime, 1000);
            Player.play();
        }
    },

    /**
     * Formats the seconds in the style mm:ss
     * @param {number} seconds
     * @return {string} The formatted time as string
     */
    formatTime: function(seconds) {
        seconds = Math.round(seconds);
        let minutes = Math.floor(seconds / 60);
        seconds = seconds - minutes * 60;
        let time = Player.str_pad_left(minutes, "0", 2) + ':' + Player.str_pad_left(seconds, "0", 2);
        return time;
    },

    /**
     * This function is used to update the time correctly
     * @return {[type]} [description]
     */
    updateTime: function() {
        console.log("Updating Time");
        let currentTime = Player.formatTime(Player.YTPlayer.getCurrentTime());
        Player.GUI.time.innerText = currentTime;
    },

    /**
     * Start/continue playback of video
     */
    play: function() {
        $("#play .icon").removeClass("fa-play");
        $("#play .icon").addClass("fa-pause");
        Player.YTPlayer.playVideo();
    },

    /**
     * Pause the playback of the video
     */
    pause: function() {
        $("#play .icon").removeClass("fa-pause");
        $("#play .icon").addClass("fa-play");
        Player.YTPlayer.pauseVideo();
    },

    loadVideoById: function(id) {
        Player.YTPlayer.loadVideoByid(id);
    },

    /**
     * Used the pad the time correctly
     */
    str_pad_left: function(string,pad,length) {
        return (new Array(length+1).join(pad)+string).slice(-length);
    },

    loadByUrl: function(url) {
        console.log("Load Video By Url: ", url);
        Player.YTPlayer.loadVideoByUrl(url);
        Player.play();
    },

    loadVideo: function() {
        console.log("LOADING VIDEO");
        Player.clearPlayer();
        Player.YTPlayer = new YT.Player('player', {
            //height: 1,
            //width: 1,
           // videoId: "dQw4w9WgXcQ",
            events: {
                'onReady': Player.onReady,
                'onStateChange': Player.onStateChange
            }
        });

        console.log("object created");
    },

    clearPlayer: function() {
        console.log("CLEARING VIDEO");
        if(Player.YTPlayer !== undefined && Player.YTPlayer !== null) {
            Player.YTPlayer.stopVideo();
            Player.YTPlayer.clearVideo();
            Player.YTPlayer.destroy();
        }

        //Remove Event Listener
        Player.GUI.controls.play.removeEventListener("click", Player.changeVideoState);

        //Clear intervals and the YT.Player object
        clearInterval(Player.update);
        Player.update = undefined;
        Player.YTPlayer = undefined;
    }
};<commit_msg>Found out how to enable Playlist Play<commit_after>/**
 * Player Object
 */
const Player = {

    YTPlayer: undefined,
    update: undefined,

    GUI: {
        title: document.getElementById("title"),
        time: document.getElementById("time"),
        duration: document.getElementById("duration"),
        controls: {
            play: document.getElementById("play")
        },
        searchField: document.getElementById("search")
    },

    /**
     * Gets fired when the YT Player is Loaded
     */
    onReady: function(event) {
        console.log("PLAYER IS LOADED");
        //let player = event.target;
        //let videoUrl = Player.loadByUrl(Player.GUI.searchField.value);
        //Check if URL is a playlist

        //Player.YTPlayer.loadVideoByUrl("https://www.youtube.com/v/blpl4swRxgQ?version=3");

        Player.displayMeta();

        //Start the video
        Player.play();
    },

    /**
     * Gets called when the state of the player gets changed
     */
    onStateChange: function(event) {
        const player = event.target;
        console.log("State changed to: ", player.getPlayerState());
    },

    /**
     * Switches between playing and pausing
     */
    changeVideoState: function() {
        if(Player.YTPlayer.getPlayerState() == YT.PlayerState.PLAYING) {
            clearInterval(Player.update);
            Player.pause();
        } else {
            Player.update = setInterval(Player.updateTime, 1000);
            Player.play();
        }
    },

    displayMeta: function() {
        Player.GUI.title.innerText = Player.YTPlayer.getVideoData().title;

        //Display time
        let duration = Player.formatTime(Player.YTPlayer.getDuration());
        Player.GUI.duration.innerText = duration;
        Player.GUI.time.innerText = "00:00";

        //Add event listeners for the GUI
        Player.GUI.controls.play.addEventListener("click", Player.changeVideoState);

        //Initialise updateTime function
        Player.update = setInterval(Player.updateTime, 1000);
    },

    playNext: function() {
        Player.YTPlayer.playNext();
        Player.YTPlayer.displayMeta();
    },

    playPrevious: function() {
        Player.YTPlayer.playPrevious();
        Player.YTPlayer.displayMeta();
    },

    /**
     * Formats the seconds in the style mm:ss
     * @param {number} seconds
     * @return {string} The formatted time as string
     */
    formatTime: function(seconds) {
        seconds = Math.round(seconds);
        let minutes = Math.floor(seconds / 60);
        seconds = seconds - minutes * 60;
        let time = Player.str_pad_left(minutes, "0", 2) + ':' + Player.str_pad_left(seconds, "0", 2);
        return time;
    },

    /**
     * This function is used to update the time correctly
     * @return {[type]} [description]
     */
    updateTime: function() {
        console.log("Updating Time");
        let currentTime = Player.formatTime(Player.YTPlayer.getCurrentTime());
        Player.GUI.time.innerText = currentTime;
    },

    /**
     * Start/continue playback of video
     */
    play: function() {
        $("#play .icon").removeClass("fa-play");
        $("#play .icon").addClass("fa-pause");
        Player.YTPlayer.playVideo();
    },

    /**
     * Pause the playback of the video
     */
    pause: function() {
        $("#play .icon").removeClass("fa-pause");
        $("#play .icon").addClass("fa-play");
        Player.YTPlayer.pauseVideo();
    },

    loadVideoById: function(id) {
        Player.YTPlayer.loadVideoByid(id);
    },

    /**
     * Used the pad the time correctly
     */
    str_pad_left: function(string,pad,length) {
        return (new Array(length+1).join(pad)+string).slice(-length);
    },

    loadByUrl: function(url) {
        console.log("Load Video By Url: ", url);
        Player.YTPlayer.loadVideoByUrl(url);
        Player.play();
    },

    loadVideo: function() {
        console.log("LOADING VIDEO");
        Player.clearPlayer();
        Player.YTPlayer = new YT.Player('player', {
            //height: 1,
            //width: 1,
           // videoId: "dQw4w9WgXcQ",
            events: {
                'onReady': Player.onReady,
                'onStateChange': Player.onStateChange
            }
        });

        console.log("object created");
    },

    clearPlayer: function() {
        console.log("CLEARING VIDEO");
        if(Player.YTPlayer !== undefined && Player.YTPlayer !== null) {
            Player.YTPlayer.stopVideo();
            Player.YTPlayer.clearVideo();
            Player.YTPlayer.destroy();
        }

        //Remove Event Listener
        Player.GUI.controls.play.removeEventListener("click", Player.changeVideoState);

        //Clear intervals and the YT.Player object
        clearInterval(Player.update);
        Player.update = undefined;
        Player.YTPlayer = undefined;
    }
};<|endoftext|>


<commit_before>export default
  (receivers, passthrough = true) =>
  (emitter, e1, e2) => {
    const event = (e2 === undefined) ? e1 : e2;
    const { valueType, ...rest } = (e2 === undefined) ? e1.value : e1;
    for (let key in receivers) {
      if (!receivers.hasOwnProperty(key)) { continue; }
      if (key !== valueType) { continue; }
      receivers[key](emitter, rest, event);
      return;
    }
    if (passthrough) { emitter.event(event); }
  };

<commit_msg>bad decomposition<commit_after>export default
  (receivers, passthrough = true) =>
  (emitter, e1, e2) => {
    const event = (e2 === undefined) ? e1 : e2;
    const { type, ...rest } = (e2 === undefined) ? e1.value : e1;
    for (let key in receivers) {
      if (!receivers.hasOwnProperty(key)) { continue; }
      if (key !== type) { continue; }
      receivers[key](emitter, rest, event);
      return;
    }
    if (passthrough) { emitter.event(event); }
  };

<|endoftext|>