<commit_before>import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';

const Bookmarks = new Mongo.Collection('bookmarks');
export default Bookmarks;

const createThumb = (fileObj, readStream, writeStream) => {
  gm(readStream, fileObj.name()).resize('160', '128').quality(40).stream().pipe(writeStream);
};

const imageStore = new FS.Store.GridFS("images", {
  // transformWrite: createThumb
});

export const Images = new FS.Collection("images", {
  stores: [imageStore]
});

Images.allow({
  download: () => {
    return true
  }
});

BookmarksSchema = new SimpleSchema({
  "title": {
    type: String,
    label: "Bookmark Name"
  },
  "url": {
    type: String,
    label: "Bookmark description",
  },
  "favicon": {
    type: String,
    label: "Bookmark icon",
    optional: true
  },
  "image": {
    type: String,
    label: "Bookmark icon",
    optional: true
  },
  "webshotId": {
    type: String,
    label: "Id of Webshot image",
    optional: true
  },
  "views": {
    type: Number,
    label: "Number of views",
    defaultValue: 0
  },
  "folderId": {
    type: String,
    label: "Parent folder"
  },
  "createdAt": {
    type: Date,
    label: "Date of creation",
    autoValue: function() {
      if ( this.isInsert ) {
        return new Date();
      }
    }
  }
});

Bookmarks.attachSchema(BookmarksSchema);
<commit_msg>Reenable graphicsmagick<commit_after>import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';

const Bookmarks = new Mongo.Collection('bookmarks');
export default Bookmarks;

const createThumb = (fileObj, readStream, writeStream) => {
  gm(readStream, fileObj.name()).resize('160', '128').quality(40).stream().pipe(writeStream);
};

const imageStore = new FS.Store.GridFS("images", {
  transformWrite: createThumb
});

export const Images = new FS.Collection("images", {
  stores: [imageStore]
});

Images.allow({
  download: () => {
    return true
  }
});

BookmarksSchema = new SimpleSchema({
  "title": {
    type: String,
    label: "Bookmark Name"
  },
  "url": {
    type: String,
    label: "Bookmark description",
  },
  "favicon": {
    type: String,
    label: "Bookmark icon",
    optional: true
  },
  "image": {
    type: String,
    label: "Bookmark icon",
    optional: true
  },
  "webshotId": {
    type: String,
    label: "Id of Webshot image",
    optional: true
  },
  "views": {
    type: Number,
    label: "Number of views",
    defaultValue: 0
  },
  "folderId": {
    type: String,
    label: "Parent folder"
  },
  "createdAt": {
    type: Date,
    label: "Date of creation",
    autoValue: function() {
      if ( this.isInsert ) {
        return new Date();
      }
    }
  }
});

Bookmarks.attachSchema(BookmarksSchema);
<|endoftext|>


<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.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: ' + p.first);
            return;
        }

    	var choices_verifcode = p.second;
    	p = crypto.deconcatenate(p.second);
    	var voterChoices = [];
    	// parsing from the last choice to the first one ("ffffffff" at the beginning is the delimiter)
    	while(p.first !== "ffffffff" && p.first !== ""){
    		p = crypto.deconcatenate(p.first);
    		voterChoices.push(crypto.hexStringToInt(p.second));
    	}

    	if(voterChoices === null){
    		console.log("no choices made for this ballot");
    		continue;
    	}

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

    	// Verification code
    	var verificationCode = crypto.deconcatenate(choices_verifcode).second;
    	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>slightly cleaned up redundancy<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: ' + p.first);
            return;
        }

    	var choices_verifcode = p.second;
    	p = crypto.deconcatenate(choices_verifcode);
    	console.log(p.first);
    	var verificationCode = p.second
    	var voterChoices = [];
    	// parsing from the last choice to the first one ("ffffffff" at the beginning is the delimiter)
    	while(p.first !== "ffffffff" && p.second !== ""){
    		p = crypto.deconcatenate(p.first);
    		voterChoices.push(crypto.hexStringToInt(p.second));
    		console.log(p.second);
    	}

    	if(voterChoices === null){
    		console.log("no choices made for this ballot");
    		continue;
    	}

    	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>const handleError = (err, res) => {
  switch (err.code) {
    case 401:
      return res.status(401).send(err.message);
    case 404:
      return res.status(404).send(err.message);
    default:
      return res.status(400).send(err);
  }
};
const handleSuccess = (code, body, res) => {
  switch (code) {
    case 201:
      return res.status(201).send(body);
    default:
      return res.status(200).send(body);
  }
};
module.exports = { handleError, handleSuccess };
<commit_msg>Refactor the helper methods to use json method instead of send method<commit_after>const handleError = (err, res) => {
  switch (err.code) {
    case 401:
      return res.status(401).json(err.message);
    case 404:
      return res.status(404).json(err.message);
    default:
      return res.status(400).json(err);
  }
};
const handleSuccess = (code, body, res) => {
  switch (code) {
    case 201:
      return res.status(201).json(body);
    default:
      return res.status(200).json(body);
  }
};
module.exports = { handleError, handleSuccess };
<|endoftext|>


<commit_before>// for Google Publisher Tag ads
//
// required props:
//    - adId: eg, '/6355419/Travel/Europe/France/Paris'
//    - height: a css size in pixels
//    - width: ditto
//
// optional props:
//    - placement: only useful if the same `adId` is used more than once on a
//      page, use this to distinguish between them: call one "1" and the other
//      "2", or call them "top-left" and "bottom-right", etc
//    - refresh: number of seconds between refreshes
//    - shouldWatchViewport: turn off checks for ad in view
//    - tracing: verbose messages in console.log via Ember.Logger.log

import Ember from 'ember';
import {task, timeout} from 'ember-concurrency';
import InViewportMixin from 'ember-in-viewport';
import getViewportTolerance from '../utils/get-viewport-tolerance';

const {
    Component,
    assert,
    get, set, getProperties, setProperties,
    String: { htmlSafe },
    Logger: { log },
    inject: { service },
    run,
    run: { scheduleOnce }
} = Ember;

export default Component.extend(InViewportMixin, {
    classNames: ['google-publisher-tag'],
    attributeBindings: ['style'],

    adQueue: service(),

    placement: 0,
    refresh: 0,
    refreshCount: 0,
    refreshLimit: 0,
    tracing: false,
    shouldWatchViewport: true,

    didReceiveAttrs() {
        this._super(...arguments);

        let {adId, width, height, placement} = getProperties(this, 'adId', 'width', 'height', 'placement');

        // width and height are also passed into .defineSlot(), which will
        // silently fail unless they are actually numbers
        assert(`google-publisher-tag "${adId} (${placement})": width and height must be numbers`, typeof width === 'number' && typeof height === 'number');

        let style = `width:${width}px; height:${height}px;`;
        set(this, 'style', htmlSafe(style));
    },
    didInsertElement() {
        this._super(...arguments);

        let {
          shouldWatchViewport,
          viewportEntered,
          width,
          height
        } = getProperties(this,
          'shouldWatchViewport',
          'viewportEntered',
          'width',
          'height'
        );

        setProperties(this, {
          viewportEnabled: shouldWatchViewport,
          viewportSpy: true,
          viewportTolerance: getViewportTolerance(width, height, 0.5)
        });

        scheduleOnce('afterRender', () => {
          if (!shouldWatchViewport || viewportEntered) {
            this.initAd();
          } else {
            this.trace('ad hidden on load, not initialized');
          }
        });
    },

    initAd() {
      if (!get(this, 'isAdInitialized')) {
        this.trace('initializing');
        get(this, 'adQueue').push(this);
        set(this, 'isAdInitialized', true);
      }
      this.waitForRefresh();
    },

    addTargeting(slot) { // jshint ignore:line
        // override this in child components, if needed, but an example is:
        // slot.setTargeting('placement', get(this, 'placement'));
        // slot.setTargeting('refresh_count', get(this, 'refreshCount'));
        // slot.setTargeting('planet', 'Earth');
    },
    waitForRefresh() {
        let duration = get(this, 'refresh');
        if (duration > 0) {
            this.trace(`will refresh in ${duration} seconds`);

            // give the tests a moment to release wait handlers
            setTimeout(() => {
              run(() => {
                get(this, 'refreshWaitTask').perform(duration);
              });
            });
        }
    },
    trace() {
        if (get(this, 'tracing')) {
            let {adId, placement} = getProperties(this, 'adId', 'placement');
            log(`${adId} (${placement}): `, ...arguments);
        }
    },

    refreshWaitTask: task(function * (duration) {
        yield timeout(duration * 1000);

        let {
          shouldWatchViewport,
          viewportEntered
        } = getProperties(this,
          'shouldWatchViewport',
          'viewportEntered'
        );

        if (shouldWatchViewport && !viewportEntered) {
          this.trace('ad not in view, skipped refresh');

          return set(this, 'isRefreshOverdue', true);
        }

        this.doRefresh();
    }).restartable(),

    doRefresh() {

        let refreshLimit   = get(this, 'refreshLimit');
        let refreshCount   = get(this, 'refreshCount');
        let isWithinLimits = refreshLimit >= get(this, 'refreshCount');
        let canRefresh     = this.isRefreshLimited() && isWithinLimits;
        let debugMsg       = `refresh called ${refreshCount} of ${refreshLimit} times`;

        if (!canRefresh) {
          return this.trace('Could not refresh :: ', debugMsg);
        }

        if (this.isRefreshLimited()) {
          this.trace(debugMsg);
        }

        let googletag = window.googletag;
        googletag.cmd.push( () => {
          let slot = get(this, 'slot');
          this.trace('refreshing now');
          this.addTargeting(slot);
          googletag.pubads().refresh([slot]);
          this.incrementProperty('refreshCount');
          this.waitForRefresh();
        });
    },

    isRefreshLimited() {
      return get(this, 'refreshLimit') !== false;
    },

    didEnterViewport() {
      this.trace('entered viewport');

      this.initAd();
      if (get(this, 'isRefreshOverdue')) {
        this.doRefresh();
        set(this, 'isRefreshOverdue', false);
      }
    }
});
<commit_msg>clean up extra let statements, unneeded function<commit_after>// for Google Publisher Tag ads
//
// required props:
//    - adId: eg, '/6355419/Travel/Europe/France/Paris'
//    - height: a css size in pixels
//    - width: ditto
//
// optional props:
//    - placement: only useful if the same `adId` is used more than once on a
//      page, use this to distinguish between them: call one "1" and the other
//      "2", or call them "top-left" and "bottom-right", etc
//    - refresh: number of seconds between refreshes
//    - shouldWatchViewport: turn off checks for ad in view
//    - tracing: verbose messages in console.log via Ember.Logger.log

import Ember from 'ember';
import {task, timeout} from 'ember-concurrency';
import InViewportMixin from 'ember-in-viewport';
import getViewportTolerance from '../utils/get-viewport-tolerance';

const {
    Component,
    assert,
    get, set, getProperties, setProperties,
    String: { htmlSafe },
    Logger: { log },
    inject: { service },
    run,
    run: { scheduleOnce }
} = Ember;

export default Component.extend(InViewportMixin, {
    classNames: ['google-publisher-tag'],
    attributeBindings: ['style'],

    adQueue: service(),

    placement: 0,
    refresh: 0,
    refreshCount: 0,
    refreshLimit: 0,
    tracing: false,
    shouldWatchViewport: true,

    didReceiveAttrs() {
        this._super(...arguments);

        let {adId, width, height, placement} = getProperties(this, 'adId', 'width', 'height', 'placement');

        // width and height are also passed into .defineSlot(), which will
        // silently fail unless they are actually numbers
        assert(`google-publisher-tag "${adId} (${placement})": width and height must be numbers`, typeof width === 'number' && typeof height === 'number');

        let style = `width:${width}px; height:${height}px;`;
        set(this, 'style', htmlSafe(style));
    },
    didInsertElement() {
        this._super(...arguments);

        let {
          shouldWatchViewport,
          viewportEntered,
          width,
          height
        } = getProperties(this,
          'shouldWatchViewport',
          'viewportEntered',
          'width',
          'height'
        );

        setProperties(this, {
          viewportEnabled: shouldWatchViewport,
          viewportSpy: true,
          viewportTolerance: getViewportTolerance(width, height, 0.5)
        });

        scheduleOnce('afterRender', () => {
          if (!shouldWatchViewport || viewportEntered) {
            this.initAd();
          } else {
            this.trace('ad hidden on load, not initialized');
          }
        });
    },

    initAd() {
      if (!get(this, 'isAdInitialized')) {
        this.trace('initializing');
        get(this, 'adQueue').push(this);
        set(this, 'isAdInitialized', true);
      }
      this.waitForRefresh();
    },

    addTargeting(slot) { // jshint ignore:line
        // override this in child components, if needed, but an example is:
        // slot.setTargeting('placement', get(this, 'placement'));
        // slot.setTargeting('refresh_count', get(this, 'refreshCount'));
        // slot.setTargeting('planet', 'Earth');
    },
    waitForRefresh() {
        let duration = get(this, 'refresh');
        if (duration > 0) {
            this.trace(`will refresh in ${duration} seconds`);

            // give the tests a moment to release wait handlers
            setTimeout(() => {
              run(() => {
                get(this, 'refreshWaitTask').perform(duration);
              });
            });
        }
    },
    trace() {
        if (get(this, 'tracing')) {
            let {adId, placement} = getProperties(this, 'adId', 'placement');
            log(`${adId} (${placement}): `, ...arguments);
        }
    },

    refreshWaitTask: task(function * (duration) {
        yield timeout(duration * 1000);

        let {
          shouldWatchViewport,
          viewportEntered
        } = getProperties(this,
          'shouldWatchViewport',
          'viewportEntered'
        );

        if (shouldWatchViewport && !viewportEntered) {
          this.trace('ad not in view, skipped refresh');

          return set(this, 'isRefreshOverdue', true);
        }

        this.doRefresh();
    }).restartable(),

    doRefresh() {
        let {refreshLimit, refreshCount} = getProperties(this, 'refreshLimit', 'refreshCount');
        if (refreshLimit > 0 && refreshCount >= refreshLimit) {
          this.trace(`refreshCount has exceeded refreshLimit: ${refreshLimit}`);
          return;
        }

        this.trace(`queuing a refresh: ${refreshCount}`);
        let googletag = window.googletag;
        googletag.cmd.push( () => {
          let slot = get(this, 'slot');
          this.trace('refreshing now');
          this.addTargeting(slot);
          googletag.pubads().refresh([slot]);
          this.incrementProperty('refreshCount');
          this.waitForRefresh();
        });
    },

    didEnterViewport() {
      this.trace('entered viewport');

      this.initAd();
      if (get(this, 'isRefreshOverdue')) {
        this.doRefresh();
        set(this, 'isRefreshOverdue', false);
      }
    }
});
<|endoftext|>


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

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
 <commit_msg>Cleaned out the intertubes<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  <|endoftext|>


<commit_before>'use strict';

// Chai is a BDD / TDD assertion library
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
var config = require('./protractor.conf.js').config;

var helperForms = require('./utils/forms');
var helperBrowser = require('./utils/browser');

chai.use(chaiAsPromised);
var expect = chai.expect;

describe('public account', function() {

  before(function(){
    helperForms.login(config.user.username,config.user.password);
  });

  function pressRenameSubmit() {
    return $("form[name='renameForm'] button[type='submit']").click().then( helperBrowser.waitForElementToDisplay.bind(this, $("div.showPublic div.alert-success")) );
  }

  function waitForRenameSubmitButtonBecameAvailable() {
    return helperBrowser.waitForElementToBecameAvailable($("form[name='renameForm'] button[type='submit']"));
  }

  it('should show public account page', function(done) {
    browser.get('#/account/public');

    // Wait for the page to render
    helperBrowser.waitForElementToDisplay($('#address'));

    expect($('.username').getText()).to.eventually.equal('~' + config.user.username)
      .and.notify(done);
  });

  it('should show rename user controls', function(done) {
    $('div.edit-account-btn-wrapper a').click();

    expect($('#renameForm').isDisplayed())
      .to.eventually.be.true;

    expect($('#address').isDisplayed())
      .to.eventually.be.true
      .and.notify(done);
  });

  it('should allow to rename user', function(done) {
    $('#username').sendKeys(config.user.username + '-E2E');
    $('#password').sendKeys(config.user.password);

    waitForRenameSubmitButtonBecameAvailable();

    expect($("form[name='renameForm'] button[type='submit']").getAttribute('disabled'))
      .to.eventually.be.null
      .and.notify(done);
  });

  it('should rename user', function(done) {
    protractor.getInstance().ignoreSynchronization = true;

    pressRenameSubmit();

    expect($('.username').getText()).to.eventually.equal('~' + config.user.username + '-E2E')
        .and.notify(done);
  });

  it('should rename user back', function(done) {
    $('div.edit-account-btn-wrapper a').click();

    $('#username').sendKeys(config.user.username);
    $('#password').sendKeys(config.user.password);

    waitForRenameSubmitButtonBecameAvailable();

    pressRenameSubmit();

    expect($('.username').getText()).to.eventually.equal('~' + config.user.username)
      .and.notify(done);
  });

});
<commit_msg>[FIX] more readable code (RT-2525)<commit_after>'use strict';

// Chai is a BDD / TDD assertion library
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
var config = require('./protractor.conf.js').config;

var helperForms = require('./utils/forms');
var helperBrowser = require('./utils/browser');

chai.use(chaiAsPromised);
var expect = chai.expect;

describe('public account', function() {

  before(function(){
    helperForms.login(config.user.username,config.user.password);
  });

  function pressRenameSubmit() {
    return $("form[name='renameForm'] button[type='submit']")
      .click().then(
        helperBrowser.waitForElementToDisplay.bind(this, $("div.showPublic div.alert-success"))
      );
  }

  function waitForRenameSubmitButtonBecameAvailable() {
    return helperBrowser.waitForElementToBecameAvailable($("form[name='renameForm'] button[type='submit']"));
  }

  it('should show public account page', function(done) {
    browser.get('#/account/public');

    // Wait for the page to render
    helperBrowser.waitForElementToDisplay($('#address'));

    expect($('.username').getText()).to.eventually.equal('~' + config.user.username)
      .and.notify(done);
  });

  it('should show rename user controls', function(done) {
    $('div.edit-account-btn-wrapper a').click();

    expect($('#renameForm').isDisplayed())
      .to.eventually.be.true;

    expect($('#address').isDisplayed())
      .to.eventually.be.true
      .and.notify(done);
  });

  it('should allow to rename user', function(done) {
    $('#username').sendKeys(config.user.username + '-E2E');
    $('#password').sendKeys(config.user.password);

    waitForRenameSubmitButtonBecameAvailable();

    expect($("form[name='renameForm'] button[type='submit']").getAttribute('disabled'))
      .to.eventually.be.null
      .and.notify(done);
  });

  it('should rename user', function(done) {
    protractor.getInstance().ignoreSynchronization = true;

    pressRenameSubmit();

    expect($('.username').getText()).to.eventually.equal('~' + config.user.username + '-E2E')
        .and.notify(done);
  });

  it('should rename user back', function(done) {
    $('div.edit-account-btn-wrapper a').click();

    $('#username').sendKeys(config.user.username);
    $('#password').sendKeys(config.user.password);

    waitForRenameSubmitButtonBecameAvailable();

    pressRenameSubmit();

    expect($('.username').getText()).to.eventually.equal('~' + config.user.username)
      .and.notify(done);
  });

});
<|endoftext|>


<commit_before>import Ember from "ember";
import layout from "../templates/components/resizable-table-cell";
import { formatStyle } from "../utils/format-style";

const { computed, get, Component } = Ember;
const { htmlSafe } = Ember.String;

export default Component.extend({
  layout,
  classNames: ["resizable-table-cell"],
  attributeBindings: ["colSpan:colspan", "rowSpan:rowspan", "htmlStyle:style"],
  tagName: "td",
  colSpan: 1,
  rowSpan: 1,
  coordX: undefined /* set by resizable-table */,
  coordY: undefined /* set by resizable-table */,
  numColumns: computed.alias("row.table.numColumns"),
  numRows: computed.alias("row.table.numRows"),

  columnSizes: computed.alias("row.table.columnSizes"),
  rowSizes: computed.alias("row.table.rowSizes"),
  sashWidth: computed.alias("row.table.sashWidth"),
  sashDistance: 0,

  init() {
    this._super();
    this.get("myWidth");
    this.get("myHeight");
    this.get("style");
  },

  myWidth: computed(
    "coordX",
    "coordY",
    "columnSizes",
    "columnSizes.@each.size",
    function() {
      if (
        this.get("coordX") === undefined ||
        this.get("coordY") === undefined ||
        this.get("columnSizes") === undefined
      ) {
        return undefined;
      }

      const x = this.get("coordX");
      let ret = 0.0;
      for (let w = 0; w < this.get("colSpan"); w++) {
        const cur = this.get("columnSizes")[x + w];
        if (cur === undefined) {
          return undefined;
        }
        ret += get(cur, "size");
      }
      return ret;
    }
  ),

  myHeight: computed(
    "coordX",
    "coordY",
    "rowSizes",
    "rowSizes.@each.size",
    function() {
      if (
        this.get("coordY") === undefined ||
        this.get("coordY") === undefined ||
        this.get("rowSizes") === undefined
      ) {
        return undefined;
      }

      const y = this.get("coordY");
      let ret = 0.0;
      for (let h = 0; h < this.get("rowSpan"); h++) {
        const cur = this.get("rowSizes")[y + h];
        if (cur === undefined) {
          return undefined;
        }
        ret += get(cur, "size");
      }
      return ret;
    }
  ),

  style: computed("myWidth", "myHeight", function() {
    return {
      position: "relative",
      width: `${this.get("myWidth") * 100.0}%`,
      height: `${this.get("myHeight") * 100.0}%`
    };
  }),

  htmlStyle: computed("style", function() {
    return htmlSafe(formatStyle(this.get('style')));
  }),

  sashBaseStyle: computed(function() {
    return {
      position: "absolute",
      "user-select": "none",
      "z-index": "1000000"
    };
  }),

  sashTopStyle: computed(
    "sashWidth",
    "sashDistance",
    "baseSashStyle",
    function() {
      return formatStyle(
        Object.assign({}, this.get("sashBaseStyle"), {
          top: "-1px",
          left: `${this.get("sashDistance")}px`,
          right: `${this.get("sashDistance")}px`,
          height: `${this.get("sashWidth")}px`,
          cursor: "row-resize"
        })
      );
    }
  ),

  sashRightStyle: computed(
    "sashWidth",
    "sashDistance",
    "baseSashStyle",
    function() {
      return formatStyle(
        Object.assign({}, this.get("sashBaseStyle"), {
          right: "-1px",
          top: `${this.get("sashDistance")}px`,
          bottom: `${this.get("sashDistance")}px`,
          width: `${this.get("sashWidth")}px`,
          cursor: "col-resize"
        })
      );
    }
  ),

  sashBottomStyle: computed(
    "sashWidth",
    "sashDistance",
    "baseSashStyle",
    function() {
      return formatStyle(
        Object.assign({}, this.get("sashBaseStyle"), {
          bottom: "-1px",
          left: `${this.get("sashDistance")}px`,
          right: `${this.get("sashDistance")}px`,
          height: `${this.get("sashWidth")}px`,
          cursor: "row-resize"
        })
      );
    }
  ),

  sashLeftStyle: computed(
    "sashWidth",
    "sashDistance",
    "baseSashStyle",
    function() {
      return formatStyle(
        Object.assign({}, this.get("sashBaseStyle"), {
          left: "-1px",
          top: `${this.get("sashDistance")}px`,
          bottom: `${this.get("sashDistance")}px`,
          width: `${this.get("sashWidth")}px`,
          cursor: "col-resize"
        })
      );
    }
  ),

  /**
   * Helpers
   */

  reLayout() {
    this.get("row").reLayout();
  },

  /**
   * Life cycle
   */

  didInsertElement() {
    this._super(...arguments);
    this.get("row.cells").pushObject(this);
    this.reLayout();
  },

  willDestroyElement() {
    this._super(...arguments);
    this.get("row.cells").removeObject(this);
    this.reLayout();
  },

  /**
   * Actions
   */

  sashClicked(sashType) {
    let columnOrRow, index;
    switch (sashType) {
      case "top":
        columnOrRow = "row";
        index = this.get("coordY");
        break;
      case "right":
        columnOrRow = "column";
        index = this.get("coordX") + this.get("colSpan");
        break;
      case "bottom":
        columnOrRow = "row";
        index = this.get("coordY") + this.get("rowSpan");
        break;
      case "left":
        columnOrRow = "column";
        index = this.get("coordX");
        break;
    }

    this.get("row.table.startResize")(columnOrRow, index);
  }
});
<commit_msg>removed double use of htmlSafe on htmlStyle variable<commit_after>import Ember from "ember";
import layout from "../templates/components/resizable-table-cell";
import { formatStyle } from "../utils/format-style";

const { computed, get, Component } = Ember;
const { htmlSafe } = Ember.String;

export default Component.extend({
  layout,
  classNames: ["resizable-table-cell"],
  attributeBindings: ["colSpan:colspan", "rowSpan:rowspan", "htmlStyle:style"],
  tagName: "td",
  colSpan: 1,
  rowSpan: 1,
  coordX: undefined /* set by resizable-table */,
  coordY: undefined /* set by resizable-table */,
  numColumns: computed.alias("row.table.numColumns"),
  numRows: computed.alias("row.table.numRows"),

  columnSizes: computed.alias("row.table.columnSizes"),
  rowSizes: computed.alias("row.table.rowSizes"),
  sashWidth: computed.alias("row.table.sashWidth"),
  sashDistance: 0,

  init() {
    this._super();
    this.get("myWidth");
    this.get("myHeight");
    this.get("style");
  },

  myWidth: computed(
    "coordX",
    "coordY",
    "columnSizes",
    "columnSizes.@each.size",
    function() {
      if (
        this.get("coordX") === undefined ||
        this.get("coordY") === undefined ||
        this.get("columnSizes") === undefined
      ) {
        return undefined;
      }

      const x = this.get("coordX");
      let ret = 0.0;
      for (let w = 0; w < this.get("colSpan"); w++) {
        const cur = this.get("columnSizes")[x + w];
        if (cur === undefined) {
          return undefined;
        }
        ret += get(cur, "size");
      }
      return ret;
    }
  ),

  myHeight: computed(
    "coordX",
    "coordY",
    "rowSizes",
    "rowSizes.@each.size",
    function() {
      if (
        this.get("coordY") === undefined ||
        this.get("coordY") === undefined ||
        this.get("rowSizes") === undefined
      ) {
        return undefined;
      }

      const y = this.get("coordY");
      let ret = 0.0;
      for (let h = 0; h < this.get("rowSpan"); h++) {
        const cur = this.get("rowSizes")[y + h];
        if (cur === undefined) {
          return undefined;
        }
        ret += get(cur, "size");
      }
      return ret;
    }
  ),

  style: computed("myWidth", "myHeight", function() {
    return {
      position: "relative",
      width: `${this.get("myWidth") * 100.0}%`,
      height: `${this.get("myHeight") * 100.0}%`
    };
  }),

  htmlStyle: computed("style", function() {
    return formatStyle(this.get('style'));
  }),

  sashBaseStyle: computed(function() {
    return {
      position: "absolute",
      "user-select": "none",
      "z-index": "1000000"
    };
  }),

  sashTopStyle: computed(
    "sashWidth",
    "sashDistance",
    "baseSashStyle",
    function() {
      return formatStyle(
        Object.assign({}, this.get("sashBaseStyle"), {
          top: "-1px",
          left: `${this.get("sashDistance")}px`,
          right: `${this.get("sashDistance")}px`,
          height: `${this.get("sashWidth")}px`,
          cursor: "row-resize"
        })
      );
    }
  ),

  sashRightStyle: computed(
    "sashWidth",
    "sashDistance",
    "baseSashStyle",
    function() {
      return formatStyle(
        Object.assign({}, this.get("sashBaseStyle"), {
          right: "-1px",
          top: `${this.get("sashDistance")}px`,
          bottom: `${this.get("sashDistance")}px`,
          width: `${this.get("sashWidth")}px`,
          cursor: "col-resize"
        })
      );
    }
  ),

  sashBottomStyle: computed(
    "sashWidth",
    "sashDistance",
    "baseSashStyle",
    function() {
      return formatStyle(
        Object.assign({}, this.get("sashBaseStyle"), {
          bottom: "-1px",
          left: `${this.get("sashDistance")}px`,
          right: `${this.get("sashDistance")}px`,
          height: `${this.get("sashWidth")}px`,
          cursor: "row-resize"
        })
      );
    }
  ),

  sashLeftStyle: computed(
    "sashWidth",
    "sashDistance",
    "baseSashStyle",
    function() {
      return formatStyle(
        Object.assign({}, this.get("sashBaseStyle"), {
          left: "-1px",
          top: `${this.get("sashDistance")}px`,
          bottom: `${this.get("sashDistance")}px`,
          width: `${this.get("sashWidth")}px`,
          cursor: "col-resize"
        })
      );
    }
  ),

  /**
   * Helpers
   */

  reLayout() {
    this.get("row").reLayout();
  },

  /**
   * Life cycle
   */

  didInsertElement() {
    this._super(...arguments);
    this.get("row.cells").pushObject(this);
    this.reLayout();
  },

  willDestroyElement() {
    this._super(...arguments);
    this.get("row.cells").removeObject(this);
    this.reLayout();
  },

  /**
   * Actions
   */

  sashClicked(sashType) {
    let columnOrRow, index;
    switch (sashType) {
      case "top":
        columnOrRow = "row";
        index = this.get("coordY");
        break;
      case "right":
        columnOrRow = "column";
        index = this.get("coordX") + this.get("colSpan");
        break;
      case "bottom":
        columnOrRow = "row";
        index = this.get("coordY") + this.get("rowSpan");
        break;
      case "left":
        columnOrRow = "column";
        index = this.get("coordX");
        break;
    }

    this.get("row.table.startResize")(columnOrRow, index);
  }
});
<|endoftext|>


<commit_before>const hlpr = require('../shared/helpers');

//////////////////////////
// Send Descriptions
//////////////////////////

function GetWhy() {
    const sendMsg = `why the hell not mate?!`;
    return Promise.resolve(sendMsg);
}

function GetHow() {
    const sendMsg = `
Here's how I work!
https://github.com/benwinding/Messenger-Meme-Bot

(Ben Winding 2017)
`;
    return Promise.resolve(sendMsg);
}

function GetHelp() {
    const apiDesc = `( ͡° ͜ʖ ͡°) Below are my commands:
👍 or meme => random meme ;)
dank => dank meme
...
help => this...
why => ??
how => source code link
random => mildly interesting pic
help me => donations!!

Careful, you could get anything with memebot...

(Ben Winding 2017)
  `;
    return Promise.resolve(apiDesc);
}

function GetWelcome() {
    const greetings = ["Hey", "Howdy", "Hello", "G'day", "Bonjur", "Good Evening", "Good Morning", "Yo", "What's up"];
    const randomGreeting = hlpr.getRandomItemFromArray(greetings);
    const welcomeMsg = `${randomGreeting},
I'm your personal Memebot™!
Try my buttons below!
¯\\_(ツ)_/¯
  `;
    return Promise.resolve(welcomeMsg);
}

function GetQuickReplies() {
    return [
        {
            "content_type":"text",
            "title":":)",
            "payload":"MEME",
            "image_url":"http://i.imgur.com/vTstaG7.png"
        },
        {
            "content_type":"text",
            "title":"Hot",
            "payload":"HOT",
            "image_url":"http://i.imgur.com/5jtndzY.png"
        },
        {
            "content_type":"text",
            "title":"Dank",
            "payload":"DANK",
            "image_url":"http://i.imgur.com/nE9A8zX.png"
        },
        {
            "content_type":"text",
            "title":"donate",
            "payload":"PAY ME",
            "image_url":"https://i.imgur.com/SGEnvkE.jpg"
        },
        {
            "content_type":"text",
            "title":"Help",
            "payload":"HELP",
            "image_url":"http://i.imgur.com/mV7Diob.png"
        },
        {
            "content_type":"text",
            "title":"mild",
            "payload":"MILD",
            "image_url":"http://i.imgur.com/HrdBnhZ.png"
        },
        {
            "content_type":"text",
            "title":"wild",
            "payload":"WILD",
            "image_url":"http://i.imgur.com/M1k4gZi.png"
        },
        {
            "content_type":"text",
            "title":"MemEcon",
            "payload":"MEMECON",
            "image_url":"http://i.imgur.com/hNVgPhM.png"
        },
        {
            "content_type":"text",
            "title":"share me",
            "payload":"SHARE ME",
            "image_url":"https://i.imgur.com/rs0VIuC.png"
        },
    ]
}

module.exports = {
    GetWhy: GetWhy,
    GetHow: GetHow,
    GetHelp: GetHelp,
    GetWelcome: GetWelcome,
    GetQuickReplies: GetQuickReplies
};<commit_msg>🌅🐁 Updated with Glitch<commit_after>const hlpr = require('../shared/helpers');

//////////////////////////
// Send Descriptions
//////////////////////////

function GetWhy() {
    const sendMsg = `why the hell not mate?!`;
    return Promise.resolve(sendMsg);
}

function GetHow() {
    const sendMsg = `
Here's how I work!
https://github.com/benwinding/Messenger-Meme-Bot

(Ben Winding 2017)
`;
    return Promise.resolve(sendMsg);
}

function GetHelp() {
    const apiDesc = `( ͡° ͜ʖ ͡°) Below are my commands:
👍 or meme => random meme ;)
dank => dank meme
...
help => this...
why => ??
how => source code link
random => mildly interesting pic
help me => donations!!

Careful, you could get anything with memebot...

(Ben Winding 2017)
  `;
    return Promise.resolve(apiDesc);
}

function GetWelcome() {
    const greetings = ["Hey", "Howdy", "Hello", "G'day", "Bonjur", "Good Evening", "Good Morning", "Yo", "What's up"];
    const randomGreeting = hlpr.getRandomItemFromArray(greetings);
    const welcomeMsg = `${randomGreeting},
I'm your personal Memebot™!
Try my buttons below!
¯\\_(ツ)_/¯
  `;
    return Promise.resolve(welcomeMsg);
}

function GetQuickReplies() {
    return [
        {
            "content_type":"text",
            "title":":)",
            "payload":"MEME",
            "image_url":"http://i.imgur.com/vTstaG7.png"
        },
        {
            "content_type":"text",
            "title":"Hot",
            "payload":"HOT",
            "image_url":"http://i.imgur.com/5jtndzY.png"
        },
        {
            "content_type":"text",
            "title":"Dank",
            "payload":"DANK",
            "image_url":"http://i.imgur.com/nE9A8zX.png"
        },
        {
            "content_type":"text",
            "title":"MemEcon",
            "payload":"MEMECON",
            "image_url":"http://i.imgur.com/hNVgPhM.png"
        },
        {
            "content_type":"text",
            "title":"share me",
            "payload":"SHARE ME",
            "image_url":"https://i.imgur.com/rs0VIuC.png"
        },
        {
            "content_type":"text",
            "title":"Help",
            "payload":"HELP",
            "image_url":"http://i.imgur.com/mV7Diob.png"
        },
        {
            "content_type":"text",
            "title":"donate",
            "payload":"PAY ME",
            "image_url":"https://i.imgur.com/SGEnvkE.jpg"
        },
        {
            "content_type":"text",
            "title":"mild",
            "payload":"MILD",
            "image_url":"http://i.imgur.com/HrdBnhZ.png"
        },
        // {
        //     "content_type":"text",
        //     "title":"wild",
        //     "payload":"WILD",
        //     "image_url":"http://i.imgur.com/M1k4gZi.png"
        // },
    ]
}

module.exports = {
    GetWhy: GetWhy,
    GetHow: GetHow,
    GetHelp: GetHelp,
    GetWelcome: GetWelcome,
    GetQuickReplies: GetQuickReplies
};<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Com<commit_msg>Back out the last commit<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Comm<|endoftext|>


<commit_before>/*
 * In order to prevent errors caused by e2e tests running too fast you can slow them down by calling the following
 * function. Use higher values for slower tests.
 *
 * utils.delayPromises(30);
 *
 */
var promisesDelay = 0;

function delayPromises(milliseconds) {
    var executeFunction = browser.driver.controlFlow().execute;

    browser.driver.controlFlow().execute = function() {
        var args = arguments;

        executeFunction.call(browser.driver.controlFlow(), function() {
            return protractor.promise.delayed(milliseconds);
        });

        return executeFunction.apply(browser.driver.controlFlow(), args);
    };
}

console.log("Set promises delay to " + promisesDelay + " ms.");
delayPromises(promisesDelay);

var ECWaitTime = 2000;
var shortRest = 200;

module.exports = {
    ECWaitTime: ECWaitTime,
    shortRest: shortRest
};
<commit_msg>Relax promise delay.<commit_after>/*
 * In order to prevent errors caused by e2e tests running too fast you can slow them down by calling the following
 * function. Use higher values for slower tests.
 *
 * utils.delayPromises(30);
 *
 */
var promisesDelay = 12;

function delayPromises(milliseconds) {
    var executeFunction = browser.driver.controlFlow().execute;

    browser.driver.controlFlow().execute = function() {
        var args = arguments;

        executeFunction.call(browser.driver.controlFlow(), function() {
            return protractor.promise.delayed(milliseconds);
        });

        return executeFunction.apply(browser.driver.controlFlow(), args);
    };
}

console.log("Set promises delay to " + promisesDelay + " ms.");
delayPromises(promisesDelay);

var ECWaitTime = 2000;
var shortRest = 200;

module.exports = {
    ECWaitTime: ECWaitTime,
    shortRest: shortRest
};
<|endoftext|>


<commit_before>import { isArrayLike } from 'mobx';

export const getDisplayText = (list, value) => {
    const findInArray = (arr_list) => (arr_list.find(item => item.value === value) || {}).text;
    let text = '';
    if (isArrayLike(list)) {
        text = findInArray(list);
    } else {
        Object.keys(list).some(key => {
            text = findInArray(list[key]);
            return text;
        });
    }
    return text;
};

export const getItemFromValue = (list, value) => {
    const findInArray = (arr_list) => arr_list.findIndex(item => item.value === value);
    let item = {};
    if (isArrayLike(list)) {
        item = { number: findInArray(list), length: list.length };
    } else {
        const keys = Object.keys(list);
        keys(list).some(key => {
            item = { number: findInArray(list[key]), length: list[key].length };
            return item;
        });
    }
    return item;
};

export const getValueFromIndex = (list, index) => {
    const findInArray = (arr_list) => arr_list[index];
    let result;
    if (isArrayLike(list)) {
        result = findInArray(list);
    } else {
        const keys = Object.keys(list);
        keys(list).some(key => {
            result = findInArray(list[key]);
            return result.value;
        });
    }
    return result.value;
};

export const getPrevIndex = (index, length) => {
    const prev_index = (index - 1) < 0 ? (length - 1) : index - 1;
    return prev_index;
};

export const getNextIndex = (index, length) => {
    const next_index = (index + 1) === length ? 0 : index + 1;
    return next_index;
};

export const updateItemClass = (element, value) => {
    const list = element.nextSibling.nextSibling.children[0].children || [];
    Array.from(list).map(item => item.classList.remove('highlighted'));
    Array.from(list).find(item => item.getAttribute('value') === value).classList.add('highlighted');
};
<commit_msg>fixed error with keypress returning undefined object<commit_after>import { isArrayLike } from 'mobx';

export const getDisplayText = (list, value) => {
    const findInArray = (arr_list) => (arr_list.find(item => item.value === value) || {}).text;
    let text = '';
    if (isArrayLike(list)) {
        text = findInArray(list);
    } else {
        Object.keys(list).some(key => {
            text = findInArray(list[key]);
            return text;
        });
    }
    return text;
};

export const getItemFromValue = (list, value) => {
    const findInArray = (arr_list) => arr_list.findIndex(item => item.value === value);
    let item = {};
    if (isArrayLike(list)) {
        item = { number: findInArray(list), length: list.length };
    } else {
        Object.keys(list).some(key => {
            item = { number: findInArray(list[key]), length: list[key].length };
            return item;
        });
    }
    return item;
};

export const getValueFromIndex = (list, index) => {
    const findInArray = (arr_list) => arr_list[index];
    let result;
    if (isArrayLike(list)) {
        result = findInArray(list);
    } else {
        Object.keys(list).some(key => {
            result = findInArray(list[key]);
            return result.value;
        });
    }
    return result.value;
};

export const getPrevIndex = (index, length) => {
    const prev_index = (index - 1) < 0 ? (length - 1) : index - 1;
    return prev_index;
};

export const getNextIndex = (index, length) => {
    const next_index = (index + 1) === length ? 0 : index + 1;
    return next_index;
};

export const updateItemClass = (element, value) => {
    const list = element.nextSibling.nextSibling.children[0].children || [];
    Array.from(list).map(item => item.classList.remove('highlighted'));
    Array.from(list).find(item => item.getAttribute('value') === value).classList.add('highlighted');
};
<|endoftext|>


<commit_before>import { CANCELLED_STATUS } from 'discourse/lib/autocomplete';

var cache = {},
    cacheTopicId,
    cacheTime,
    currentTerm,
    oldSearch;

function performSearch(term, topicId, includeGroups, includeMentionableGroups, allowedUsers, resultsFn) {
  var cached = cache[term];
  if (cached) {
    resultsFn(cached);
    return;
  }

  // need to be able to cancel this
  oldSearch = $.ajax(Discourse.getURL('/users/search/users'), {
    data: { term: term,
            topic_id: topicId,
            include_groups: includeGroups,
            include_mentionable_groups: includeMentionableGroups,
            topic_allowed_users: allowedUsers }
  });

  var returnVal = CANCELLED_STATUS;

  oldSearch.then(function (r) {
    cache[term] = r;
    cacheTime = new Date();
    // If there is a newer search term, return null
    if (term === currentTerm) { returnVal = r; }

  }).always(function(){
    oldSearch = null;
    resultsFn(returnVal);
  });
}

var debouncedSearch = _.debounce(performSearch, 300);

function organizeResults(r, options) {
  if (r === CANCELLED_STATUS) { return r; }

  var exclude = options.exclude || [],
      limit = options.limit || 5,
      users = [],
      groups = [],
      results = [];

  if (r.users) {
    r.users.every(function(u) {
      if (exclude.indexOf(u.username) === -1) {
        users.push(u);
        results.push(u);
      }
      return results.length <= limit;
    });
  }

  if (r.groups) {
    r.groups.every(function(g) {
      if (results.length > limit) return false;
      if (exclude.indexOf(g.name) === -1) {
        groups.push(g);
        results.push(g);
      }
      return true;
    });
  }

  results.users = users;
  results.groups = groups;
  return results;
}

export default function userSearch(options) {
  var term = options.term || "",
      includeGroups = options.includeGroups,
      includeMentionableGroups = options.includeMentionableGroups,
      allowedUsers = options.allowedUsers,
      topicId = options.topicId;

  if (oldSearch) {
    oldSearch.abort();
    oldSearch = null;
  }

  currentTerm = term;

  return new Ember.RSVP.Promise(function(resolve) {
    // TODO site setting for allowed regex in username
    if (term.match(/[^a-zA-Z0-9_\.\-]/)) {
      resolve([]);
      return;
    }
    if (((new Date() - cacheTime) > 30000) || (cacheTopicId !== topicId)) {
      cache = {};
    }

    cacheTopicId = topicId;

    var clearPromise = setTimeout(function(){
      resolve(CANCELLED_STATUS);
    }, 5000);

    debouncedSearch(term, topicId, includeGroups, includeMentionableGroups, allowedUsers, function(r) {
      clearTimeout(clearPromise);
      resolve(organizeResults(r, options));
    });

  });
}
<commit_msg>Allow any username character in user search<commit_after>import { CANCELLED_STATUS } from 'discourse/lib/autocomplete';

var cache = {},
    cacheTopicId,
    cacheTime,
    currentTerm,
    oldSearch;

function performSearch(term, topicId, includeGroups, includeMentionableGroups, allowedUsers, resultsFn) {
  var cached = cache[term];
  if (cached) {
    resultsFn(cached);
    return;
  }

  // need to be able to cancel this
  oldSearch = $.ajax(Discourse.getURL('/users/search/users'), {
    data: { term: term,
            topic_id: topicId,
            include_groups: includeGroups,
            include_mentionable_groups: includeMentionableGroups,
            topic_allowed_users: allowedUsers }
  });

  var returnVal = CANCELLED_STATUS;

  oldSearch.then(function (r) {
    cache[term] = r;
    cacheTime = new Date();
    // If there is a newer search term, return null
    if (term === currentTerm) { returnVal = r; }

  }).always(function(){
    oldSearch = null;
    resultsFn(returnVal);
  });
}

var debouncedSearch = _.debounce(performSearch, 300);

function organizeResults(r, options) {
  if (r === CANCELLED_STATUS) { return r; }

  var exclude = options.exclude || [],
      limit = options.limit || 5,
      users = [],
      groups = [],
      results = [];

  if (r.users) {
    r.users.every(function(u) {
      if (exclude.indexOf(u.username) === -1) {
        users.push(u);
        results.push(u);
      }
      return results.length <= limit;
    });
  }

  if (r.groups) {
    r.groups.every(function(g) {
      if (results.length > limit) return false;
      if (exclude.indexOf(g.name) === -1) {
        groups.push(g);
        results.push(g);
      }
      return true;
    });
  }

  results.users = users;
  results.groups = groups;
  return results;
}

export default function userSearch(options) {
  var term = options.term || "",
      includeGroups = options.includeGroups,
      includeMentionableGroups = options.includeMentionableGroups,
      allowedUsers = options.allowedUsers,
      topicId = options.topicId;

  if (oldSearch) {
    oldSearch.abort();
    oldSearch = null;
  }

  currentTerm = term;

  return new Ember.RSVP.Promise(function(resolve) {
    // TODO site setting for allowed regex in username
    if (term.match(/[^\w\.\-]/)) {
      resolve([]);
      return;
    }
    if (((new Date() - cacheTime) > 30000) || (cacheTopicId !== topicId)) {
      cache = {};
    }

    cacheTopicId = topicId;

    var clearPromise = setTimeout(function(){
      resolve(CANCELLED_STATUS);
    }, 5000);

    debouncedSearch(term, topicId, includeGroups, includeMentionableGroups, allowedUsers, function(r) {
      clearTimeout(clearPromise);
      resolve(organizeResults(r, options));
    });

  });
}
<|endoftext|>


<commit_before>(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.angularCreditCards = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/object/define-property"), __esModule: true };
},{"core-js/library/fn/object/define-property":3}],2:[function(_dereq_,module,exports){
"use strict";

exports["default"] = function (obj) {
  return obj && obj.__esModule ? obj : {
    "default": obj
  };
};

exports.__esModule = true;
},{}],3:[function(_dereq_,module,exports){
var $ = _dereq_('../../modules/$');
module.exports = function defineProperty(it, key, desc){
  return $.setDesc(it, key, desc);
};
},{"../../modules/$":5}],4:[function(_dereq_,module,exports){
module.exports = function($){
  $.FW   = false;
  $.path = $.core;
  return $;
};
},{}],5:[function(_dereq_,module,exports){
'use strict';
var global = typeof self != 'undefined' ? self : Function('return this')()
  , core   = {}
  , defineProperty = Object.defineProperty
  , hasOwnProperty = {}.hasOwnProperty
  , ceil  = Math.ceil
  , floor = Math.floor
  , max   = Math.max
  , min   = Math.min;
// The engine works fine with descriptors? Thank's IE8 for his funny defineProperty.
var DESC = !!function(){
  try {
    return defineProperty({}, 'a', {get: function(){ return 2; }}).a == 2;
  } catch(e){ /* empty */ }
}();
var hide = createDefiner(1);
// 7.1.4 ToInteger
function toInteger(it){
  return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
}
function desc(bitmap, value){
  return {
    enumerable  : !(bitmap & 1),
    configurable: !(bitmap & 2),
    writable    : !(bitmap & 4),
    value       : value
  };
}
function simpleSet(object, key, value){
  object[key] = value;
  return object;
}
function createDefiner(bitmap){
  return DESC ? function(object, key, value){
    return $.setDesc(object, key, desc(bitmap, value));
  } : simpleSet;
}

function isObject(it){
  return it !== null && (typeof it == 'object' || typeof it == 'function');
}
function isFunction(it){
  return typeof it == 'function';
}
function assertDefined(it){
  if(it == undefined)throw TypeError("Can't call method on  " + it);
  return it;
}

var $ = module.exports = _dereq_('./$.fw')({
  g: global,
  core: core,
  html: global.document && document.documentElement,
  // http://jsperf.com/core-js-isobject
  isObject:   isObject,
  isFunction: isFunction,
  that: function(){
    return this;
  },
  // 7.1.4 ToInteger
  toInteger: toInteger,
  // 7.1.15 ToLength
  toLength: function(it){
    return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
  },
  toIndex: function(index, length){
    index = toInteger(index);
    return index < 0 ? max(index + length, 0) : min(index, length);
  },
  has: function(it, key){
    return hasOwnProperty.call(it, key);
  },
  create:     Object.create,
  getProto:   Object.getPrototypeOf,
  DESC:       DESC,
  desc:       desc,
  getDesc:    Object.getOwnPropertyDescriptor,
  setDesc:    defineProperty,
  setDescs:   Object.defineProperties,
  getKeys:    Object.keys,
  getNames:   Object.getOwnPropertyNames,
  getSymbols: Object.getOwnPropertySymbols,
  assertDefined: assertDefined,
  // Dummy, fix for not array-like ES3 string in es5 module
  ES5Object: Object,
  toObject: function(it){
    return $.ES5Object(assertDefined(it));
  },
  hide: hide,
  def: createDefiner(0),
  set: global.Symbol ? simpleSet : hide,
  each: [].forEach
});
/* eslint-disable no-undef */
if(typeof __e != 'undefined')__e = core;
if(typeof __g != 'undefined')__g = global;
},{"./$.fw":4}],6:[function(_dereq_,module,exports){
'use strict';

var _Object$defineProperty = _dereq_('babel-runtime/core-js/object/define-property')['default'];

var _interopRequireDefault = _dereq_('babel-runtime/helpers/interop-require-default')['default'];

_Object$defineProperty(exports, '__esModule', {
  value: true
});

var _angular = (window.angular);

var _angular2 = _interopRequireDefault(_angular);

exports['default'] = _angular2['default'].module('assert-q-constructor', []).factory('assertQConstructor', main).name;

main.$inject = ['$q'];
function main($q) {
  return function assertQConstructor(message) {
    if (typeof $q !== 'function') {
      throw new Error(message || '$q is not a function');
    }
  };
}
module.exports = exports['default'];

},{"babel-runtime/core-js/object/define-property":1,"babel-runtime/helpers/interop-require-default":2}],7:[function(_dereq_,module,exports){

/*
 * Fetches the value of a deeply nested property.
 *
 * Arguments:
 *
 *     obj     Object to fetch property from.
 *
 *     path    [string] Dot-separated path specifier to nested
 *             property to fetch.  Array indexes are not supported.
 *             Example: "contact.name.first".
 *
 * Returns:    [mixed] Value of nested property if it exists,
 *             `undefined` otherwise.
 */
module.exports.get = function (obj, path) {
  var tokens = parse(path);
  if (tokens.length == 0) {
    return undefined;
  }
  for (var i = 0, len = tokens.length; i < len; i++) {
    if (! obj || ! obj.hasOwnProperty(tokens[i])) {
      return undefined;
    } else {
      obj = obj[tokens[i]];
    }
  }
  return obj;
};

/*
 * Sets the value of a deeply nested property.
 *
 * If an intermediate property of the specified path doesn't exist,
 * it will be created as an object.
 *
 * Arguments:
 *
 *     obj     Object to set property on.
 *
 *     path    [string] Dot-separated path specifier to nested
 *             property to set.  Array indexes are not supported.
 *             Example: "contact.name.first".
 *
 *     value   [mixed] Value to set on the object's nested property.
 *
 * Returns:    undefined
 */
module.exports.set = function (obj, path, value) {
  if (typeof obj === 'undefined' || typeof path === 'undefined') {
    return;
  }
  var tokens = parse(path);
  for (var i = 0, len = tokens.length; i < len; i++) {
    if (! obj || ! obj.hasOwnProperty(tokens[i])) {
      obj[tokens[i]] = { };
    }
    if (i == (len - 1)) {
      obj[tokens[i]] = value;
    } else {
      obj = obj[tokens[i]];
    }
  }
};

/*
 * Removes a deeply nested property.
 *
 * If an intermediate property of the specified path doesn't exist,
 * we bail early.
 *
 * Arguments:
 *
 *     obj     Object to remove property from.
 *
 *     path    [string] Dot-separated path specifier to nested
 *             property to remove.  Array indexes are not supported.
 *             Example: "contact.name.first".
 *
 * Returns:    [boolean] TRUE if property was removed, otherwise FALSE.
 */
module.exports.remove = function (obj, path) {
  if (typeof obj === 'undefined' || typeof path === 'undefined') {
    return false;
  }
  var tokens = parse(path);
  for (var i = 0, len = tokens.length; i < len; i++) {
    if (! obj || ! obj.hasOwnProperty(tokens[i])) {
      return false;
    }
    if (i == (len - 1)) {
      delete obj[tokens[i]];
      return true;
    } else {
      obj = obj[tokens[i]];
    }
  }

  return false
};

/*
 * Detects whether a given object has a specified nested property.
 *
 * Normal checks for deeply nested properties will throw an
 * exception if an intermediate property doesn't exist.  This
 * function will do the same without but without the exception.
 *
 * Arguments:
 *
 *     obj      Object to check properties for.
 *
 *     path     [string] Dot-separated path specifier to nested
 *              property.  Array indexes are not supported.
 *              Example: "contact.name.first"
 *
 * Returns:     [boolean] TRUE if property is defined at the
 *              given path, otherwise FALSE.  If a non-string
 *              is passed as `path`, FALSE is returned.
 */
module.exports.has = function (obj, path) {
  return (typeof module.exports.get(obj, path) !== 'undefined');
};

function parse (path) {
  if (typeof path !== 'string') {
    path = '';
  }
  var tokens = path.split('.');
  for (var i = 0, len = tokens.length; i < len; i++) {
    if (tokens[i] === '') {
      return [ ];
    }
  }
  return tokens;
}

},{}],8:[function(_dereq_,module,exports){
module.exports = extend

function extend(target) {
    for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i]

        for (var key in source) {
            if (source.hasOwnProperty(key)) {
                target[key] = source[key]
            }
        }
    }

    return target
}

},{}],9:[function(_dereq_,module,exports){
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _slicedToArray(arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }

var _deepProperty = _dereq_('deep-property');

var _deepProperty2 = _interopRequireDefault(_deepProperty);

var _xtendMutable = _dereq_('xtend/mutable');

var _xtendMutable2 = _interopRequireDefault(_xtendMutable);

var asyncMethods = ['card.createToken', 'bankAccount.createToken', 'bitcoinReceiver.createReceiver', 'bitcoinReceiver.pollReceiver', 'bitcoinReceiver.getReceiver'];

var helperMethods = ['setPublishableKey', 'card.validateCardNumber', 'card.validateExpiry', 'card.validateCVC', 'card.cardType', 'bankAccount.validateRoutingNumber', 'bankAccount.validateAccountNumber', 'bitcoinReceiver.cancelReceiverPoll'];

exports['default'] = function (Stripe, Promise) {
  if (!Promise) throw new Error('Promise constructor must be provided');
  var stripe = {};
  asyncMethods.forEach(function (method) {
    var _method$split = method.split('.');

    var _method$split2 = _slicedToArray(_method$split, 2);

    var receiver = _method$split2[0];
    var methodName = _method$split2[1];

    _deepProperty2['default'].set(stripe, method, promisify(Promise, methodName, Stripe[receiver], stripeResponseHandler));
  });
  helperMethods.forEach(function (method) {
    _deepProperty2['default'].set(stripe, method, _deepProperty2['default'].get(Stripe, method));
  });
  return stripe;
};

function promisify(Promise, method, receiver, resolver) {
  return function promisified() {
    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return new Promise(function (resolve, reject) {
      receiver[method].apply(receiver, args.concat(function () {
        resolver.apply({ resolve: resolve, reject: reject }, arguments);
      }));
    });
  };
}

function stripeResponseHandler(status, response) {
  if (response.error) {
    this.reject((0, _xtendMutable2['default'])(new Error(), response.error));
  } else {
    this.resolve(response);
  }
}
module.exports = exports['default'];

},{"deep-property":7,"xtend/mutable":8}],10:[function(_dereq_,module,exports){
'use strict'

var service = _dereq_('./service')

module.exports = stripeProvider

stripeProvider.$inject = ['Stripe']
function stripeProvider (Stripe) {
  if (!Stripe) throw new Error('Stripe must be available as window.Stripe')
  this.setPublishableKey = Stripe.setPublishableKey
  this.$get = service
}

},{"./service":11}],11:[function(_dereq_,module,exports){
'use strict'

var stripeAsPromised = _dereq_('stripe-as-promised')

module.exports = factory

factory.$inject = ['Stripe', '$q']
function factory (Stripe, $q) {
  return stripeAsPromised(Stripe, $q)
}

},{"stripe-as-promised":9}],12:[function(_dereq_,module,exports){
(function (global){
'use strict'

var angular = (window.angular)
var provider = _dereq_('./provider')
var Stripe = typeof window !== 'undefined' ? window.Stripe : typeof global !== 'undefined' ? global.Stripe : null

module.exports = angular.module('angular-stripe', [
  _dereq_('angular-assert-q-constructor')
])
.constant('Stripe', Stripe)
.provider('stripe', provider)
.run(verifyQ)
.name

verifyQ.$inject = ['assertQConstructor']
function verifyQ (assertQConstructor) {
  assertQConstructor('angular-stripe: For Angular <= 1.2 support, first load https://github.com/bendrucker/angular-q-constructor')
}

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./provider":10,"angular-assert-q-constructor":6}]},{},[12])(12)
});<commit_msg>Remove acc from release folder<commit_after><|endoftext|>


<commit_before>'use strict';

var Webpack = require('webpack'),
  NgAnnotatePlugin = require('ng-annotate-webpack-plugin'),
  CopyWebpackPlugin = require('copy-webpack-plugin'),
  CleanWebpackPlugin = require('clean-webpack-plugin'),
  ExtractTextPlugin = require('extract-text-webpack-plugin'),
  path = require('path'),
  glob = require('glob');

var DIST = path.resolve(__dirname, 'target/dist');
var ROOT = __dirname;
var isDevServer = path.basename(require.main.filename) === 'webpack-dev-server.js';

var allModules = glob.sync(ROOT + '/modules/*/module.js').map(function (file) {
  var name = /modules\/([^\/]+)\/module\.js/.exec(file)[1];
  return {
    name: name,
    bundle: name + '/module',
    entry: './' + path.relative(ROOT, file),
    outputPath: name + '/'
  };
});

var getEntries = function (modules) {
  var entries = {
    'core': './core/core.js',
    'dependencies.js': ['es5-shim/es5-shim', 'es5-shim/es5-sham', 'jquery', 'bootstrap', 'angular', 'angular-resource', 'angular-ui-router']
  };
  modules.forEach(function (module) {
    entries[module.bundle] = module.entry;
  });
  return entries;
};

var ConcatSource = require('webpack-sources').ConcatSource;
var ModuleConcatPlugin = function (files) {
  this.files = files;
};
ModuleConcatPlugin.prototype.apply = function (compiler) {
  var self = this;
  compiler.plugin('emit', function (compilation, done) {
    self.files.forEach(function (file) {
      var newSource = new ConcatSource();
      Object.keys(compilation.assets).forEach(function (asset) {
        if (file.test.test(asset)) {
          newSource.add(compilation.assets[asset]);
          newSource.add(file.delimiter);
        }
      });
      if (newSource.children.length > 0) {
        compilation.assets[file.filename] = newSource;
      }
    });
    done();
  });
};

module.exports = {
  context: ROOT,
  entry: getEntries(allModules),
  output: {
    path: DIST,
    filename: '[name].js'
  },
  resolve: {
    alias: {
      bootstrap: path.resolve(ROOT, 'third-party/bootstrap/js/bootstrap.js'),
      'bootstrap.css': path.resolve(ROOT, 'third-party/bootstrap/css/bootstrap.css'),
      'bootstrap-responsive.css': path.resolve(ROOT, 'third-party/bootstrap/css/bootstrap-responsive.css'),
      'googlefonts.css': path.resolve(ROOT, 'third-party/googlefonts/googlefonts.css'),
      jolokia: path.resolve(ROOT, 'modules/applications-jmx/third-party/jolokia.js')
    }
  },
  module: {
    preLoaders: [{
      test: /\.js$/,
      loader: 'eslint',
      exclude: [/node_modules/, /third-party/],
        }],
    loaders: [{
      test: /\.js$/,
      exclude: [/node_modules/, /third-party/],
      loader: 'ng-annotate'
        }, {
      test: /\.tpl\.html$/,
      loader: 'raw'
        }, {
      test: /\.css(\?.*)?$/,
      loader: ExtractTextPlugin.extract('style', 'css?-minimize')
      }, {
      test: /\.(jpg|png|gif|eot|svg|ttf|woff(2)?)(\?.*)?$/,
      include: /\/(third-party|node_modules)\//,
      loader: 'file',
      query: {
        name: 'third-party/[2]',
        regExp: '(third-party|node_modules)/(.+)'
      }
      }, {
      test: /\.(jpg|png|gif)$/,
      include: /\/(core|modules)\//,
      loader: 'file',
      query: {
        name: '[2]',
        regExp: '(core|modules)/(.+)$'
      }
      }]
  },
  plugins: [
    new CleanWebpackPlugin([DIST]),
    new ExtractTextPlugin('[name].css'),
    new Webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery'
    }),
    new NgAnnotatePlugin({
      add: true
    }),
    new Webpack.optimize.CommonsChunkPlugin({
      name: 'dependencies.js',
      filename: 'dependencies.js'
    }),
    new CopyWebpackPlugin([{
      from: '**/*.html',
      context: 'core/'
      }, {
      from: '**/*.html',
      context: 'modules/'
      }], {
      ignore: ['*.tpl.html']
    })
    ].concat(!isDevServer ? [] : new ModuleConcatPlugin([{
      filename: 'all-modules.js',
      test: /module\.js/,
      delimiter: ';\n'
    }, {
      filename: 'all-modules.css',
      test: /module\.css/,
      delimiter: '\n'
      }
    ])),
  devServer: {
    proxy: {
      '/api*': {
        target: 'http://localhost:8080',
        secure: false
      }
    }
  },
  node: {
    fs: 'empty'
  }
};
<commit_msg>Less global provides<commit_after>'use strict';

var Webpack = require('webpack'),
  NgAnnotatePlugin = require('ng-annotate-webpack-plugin'),
  CopyWebpackPlugin = require('copy-webpack-plugin'),
  CleanWebpackPlugin = require('clean-webpack-plugin'),
  ExtractTextPlugin = require('extract-text-webpack-plugin'),
  path = require('path'),
  glob = require('glob');

var DIST = path.resolve(__dirname, 'target/dist');
var ROOT = __dirname;
var isDevServer = path.basename(require.main.filename) === 'webpack-dev-server.js';

var allModules = glob.sync(ROOT + '/modules/*/module.js').map(function (file) {
  var name = /modules\/([^\/]+)\/module\.js/.exec(file)[1];
  return {
    name: name,
    bundle: name + '/module',
    entry: './' + path.relative(ROOT, file),
    outputPath: name + '/'
  };
});

var getEntries = function (modules) {
  var entries = {
    'core': './core/core.js',
    'dependencies.js': ['es5-shim/es5-shim', 'es5-shim/es5-sham', 'jquery', 'bootstrap', 'angular', 'angular-resource', 'angular-ui-router']
  };
  modules.forEach(function (module) {
    entries[module.bundle] = module.entry;
  });
  return entries;
};

var ConcatSource = require('webpack-sources').ConcatSource;
var ModuleConcatPlugin = function (files) {
  this.files = files;
};
ModuleConcatPlugin.prototype.apply = function (compiler) {
  var self = this;
  compiler.plugin('emit', function (compilation, done) {
    self.files.forEach(function (file) {
      var newSource = new ConcatSource();
      Object.keys(compilation.assets).forEach(function (asset) {
        if (file.test.test(asset)) {
          newSource.add(compilation.assets[asset]);
          newSource.add(file.delimiter);
        }
      });
      if (newSource.children.length > 0) {
        compilation.assets[file.filename] = newSource;
      }
    });
    done();
  });
};

module.exports = {
  context: ROOT,
  entry: getEntries(allModules),
  output: {
    path: DIST,
    filename: '[name].js'
  },
  resolve: {
    alias: {
      bootstrap: path.resolve(ROOT, 'third-party/bootstrap/js/bootstrap.js'),
      'bootstrap.css': path.resolve(ROOT, 'third-party/bootstrap/css/bootstrap.css'),
      'bootstrap-responsive.css': path.resolve(ROOT, 'third-party/bootstrap/css/bootstrap-responsive.css'),
      'googlefonts.css': path.resolve(ROOT, 'third-party/googlefonts/googlefonts.css'),
      jolokia: path.resolve(ROOT, 'modules/applications-jmx/third-party/jolokia.js')
    }
  },
  module: {
    preLoaders: [{
      test: /\.js$/,
      loader: 'eslint',
      exclude: [/node_modules/, /third-party/],
    }],
    loaders: [
      {
        test: /^jolokia$/,
        loader: "imports?$=jquery"
      }, {
        test: /\.js$/,
        exclude: [/node_modules/, /third-party/],
        loader: 'ng-annotate'
      }, {
        test: /\.tpl\.html$/,
        loader: 'raw'
      }, {
        test: /\.css(\?.*)?$/,
        loader: ExtractTextPlugin.extract('style', 'css?-minimize')
      }, {
        test: /\.(jpg|png|gif|eot|svg|ttf|woff(2)?)(\?.*)?$/,
        include: /\/(third-party|node_modules)\//,
        loader: 'file',
        query: {
          name: 'third-party/[2]',
          regExp: '(third-party|node_modules)/(.+)'
        }
      }, {
        test: /\.(jpg|png|gif)$/,
        include: /\/(core|modules)\//,
        loader: 'file',
        query: {
          name: '[2]',
          regExp: '(core|modules)/(.+)$'
        }
      }]
  },
  plugins: [
    new CleanWebpackPlugin([DIST]),
    new ExtractTextPlugin('[name].css'),
    new Webpack.ProvidePlugin({
      'window.jQuery': 'jquery'
    }),
    new NgAnnotatePlugin({
      add: true
    }),
    new Webpack.optimize.CommonsChunkPlugin({
      name: 'dependencies.js',
      filename: 'dependencies.js'
    }),
    new CopyWebpackPlugin([{
      from: '**/*.html',
      context: 'core/'
    }, {
        from: '**/*.html',
        context: 'modules/'
      }], {
        ignore: ['*.tpl.html']
      })
  ].concat(!isDevServer ? [] : new ModuleConcatPlugin([
    {
      filename: 'all-modules.js',
      test: /module\.js/,
      delimiter: ';\n'
    }, {
      filename: 'all-modules.css',
      test: /module\.css/,
      delimiter: '\n'
    }
  ])),
  devServer: {
    proxy: {
      '/api*': {
        target: 'http://localhost:8080',
        secure: false
      }
    }
  },
  node: {
    fs: 'empty'
  }
};
<|endoftext|>


<commit_before>/*
    This file is part of rhizi, a collaborative knowledge graph editor.
    Copyright (C) 2014-2015  Rhizi

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/* globals $ */

function submit_login_form() {

    "use strict";

    var data = {
        email_address : $('#login_email_address').val(),
        password : $('#login_password').val()
    };

    // TODO: validate

    $.ajax({
        type : "POST",
        url: '/login',
        async : false,
        cache : false,
        data : JSON.stringify(data),
        dataType : 'json',
        contentType : "application/json; charset=utf-8",
        success : function () {
            // to force chrome autocomplete to remember our form
            // contents, submit the form successfully
            document.forms['name'].submit();
        },
        error : function (xhr, status, err_thrown) {
            $('#login-view_failed-login').show();
        }
    });
    return false;
}
<commit_msg>client/user_login: bug fix<commit_after>/*
    This file is part of rhizi, a collaborative knowledge graph editor.
    Copyright (C) 2014-2015  Rhizi

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/* globals $ */

function submit_login_form() {

    "use strict";

    var data = {
        email_address : $('#login_email_address').val(),
        password : $('#login_password').val()
    };

    // TODO: validate

    $.ajax({
        type : "POST",
        url: '/login',
        async : false,
        cache : false,
        data : JSON.stringify(data),
        dataType : 'json',
        contentType : "application/json; charset=utf-8",
        success : function () {
            // to force chrome autocomplete to remember our form
            // contents, submit the form successfully
            document.forms['login'].submit();
        },
        error : function (xhr, status, err_thrown) {
            $('#login-view_failed-login').show();
        }
    });
    return false;
}
<|endoftext|>