<commit_before>// ============================================================================================================================
// 													Connection Profile Parsing Library
//
// This file is to help safely parse the Connection Profile JSON data
// The connection profile is either in a file ("../../config/" folder) OR it was provided in the environmental variable "CONNECTION_PROFILE"
//
// - every file in this library's folder is getting rolled into the `cp` object. ie any function defined in those files is accessible to this one.
// - if you need something from the connection profile, chance are its defined somewhere in this folder
// ============================================================================================================================
var fs = require('fs');
var path = require('path');

module.exports = function (config_filename, logger) {
	var cp = {};
	var detect_env = require('./parts/detect_env.js')(logger);
	var misc = require('../misc.js')(logger);

	if (!config_filename) {
		config_filename = 'marbles_tls.json';										// default config file name
	}
	cp.config_path = path.join(__dirname, '../../config/' + config_filename);
	cp.config = require(cp.config_path);											// load the config file
	logger.info('Loaded config file', cp.config_path);								// path to config file

	// --------------------------------------------------------------------------------
	// Detect if connection profile data is in an environmental variable instead of a file
	// --------------------------------------------------------------------------------
	let use_env = detect_env.getConnectionProfileFromEnv();
	if (use_env) {																	// to use env or not to use env
		cp.using_env = true;
		cp.cp_path = 'there-is-no-file-using-env';
		cp.creds = use_env;
		logger.info('Loaded connection profile from an environmental variable');
	} else {																		// not in env, look for the files
		cp.using_env = false;
		cp.cp_path = path.join(__dirname, '../../config/' + cp.config.cred_filename);
		cp.creds = require(cp.cp_path);												// load the credential file
		logger.info('Loaded connection profile file', cp.cp_path);					// path to the blockchain connection profile
	}
	cp.config_filename = config_filename;

	// --------------------------------------------------------------------------------
	// Parse connection profile data to get various things:
	// --------------------------------------------------------------------------------
	// get network id
	cp.getNetworkName = function () {
		return cp.creds.name;
	};

	// get cred file name
	cp.getNetworkCredFileName = function () {
		return cp.config.cred_filename;
	};

	// build the tls options for the sdk
	cp.buildTlsOpts = function (node_obj) {
		let ret = {
			'ssl-target-name-override': null,
			pem: null,
			'grpc.http2.keepalive_time': 300,					//grpc 1.2.4
			'grpc.keepalive_time_ms': 300000,					//grpc 1.3.7
			'grpc.http2.keepalive_timeout': 35,					//grpc 1.2.4
			'grpc.keepalive_timeout_ms': 3500,					//grpc 1.3.7
		};
		if (node_obj) {
			if (node_obj.tlsCACerts) {
				ret.pem = cp.loadPem(node_obj.tlsCACerts);
			}
			if (node_obj.grpcOptions) {
				for (var field in ret) {
					if (node_obj.grpcOptions[field]) {
						ret[field] = node_obj.grpcOptions[field];
					}
				}
			}
		}
		return ret;
	};

	// get the very first channel name from creds
	cp.getFirstChannelId = function () {
		if (cp.creds && cp.creds.channels) {
			var channels = Object.keys(cp.creds.channels);
			if (channels[0]) {
				return channels[0];
			}
		}
		throw Error('No channels found in connection profile... this is problematic. A channel needs to be created before marbles can execute.');
	};

	// get the very first channel name from creds
	cp.getChannelId = function () {
		if (process.env.CHANNEL_ID) {							// if env version is set, use it
			return process.env.CHANNEL_ID;
		} else {
			return cp.getFirstChannelId();						// else just grab the first one we got
		}
	};

	// load cert from file path OR just pass cert back
	cp.loadPem = function (obj) {
		if (obj && obj.path) {											// looks like field is a path to a file
			var path2cert = path.join(__dirname, '../../config/' + obj.path);
			if (obj.path.indexOf('/') === 0) {
				path2cert = obj.path;									//its an absolute path
			}
			return fs.readFileSync(path2cert, 'utf8') + '\r\n'; 		//read from file, LOOKING IN config FOLDER
		} else {
			return obj.pem;												//can be null if network is not using TLS
		}
		return null;
	};

	// safely retrieve marbles config file fields
	cp.getMarblesField = function (marbles_field) {
		try {
			if (cp.config[marbles_field]) {
				return cp.config[marbles_field];
			} else {
				logger.warn('"' + marbles_field + '" not found in config json: ' + cp.config_path);
				return null;
			}
		} catch (e) {
			logger.warn('"' + marbles_field + '" not found in config json: ' + cp.config_path);
			return null;
		}
	};

	// --------------------------------------------------------------------------------
	// Absorb all the functions into the cp object
	// --------------------------------------------------------------------------------
	const chaincode = require('./parts/chaincode.js')(cp, logger);
	const ca = require('./parts/ca.js')(cp, logger);
	const peer = require('./parts/peer.js')(cp, logger);
	const helper = require('./parts/helper.js')(cp, logger);
	const orderer = require('./parts/orderer.js')(cp, logger);
	const other = require('./parts/other.js')(cp, logger);
	for (const func in chaincode) cp[func] = chaincode[func];
	for (const func in ca) cp[func] = ca[func];
	for (const func in peer) cp[func] = peer[func];
	for (const func in helper) cp[func] = helper[func];
	for (const func in orderer) cp[func] = orderer[func];
	for (const func in other) cp[func] = other[func];
	const org = require('./parts/org.js')(cp, logger);
	for (const func in org) cp[func] = org[func];

	console.log('\n\n\nConnection Profile Lib Functions:()');
	for (let i in cp) {
		if (typeof cp[i] === 'function') console.log('  ' + i + '()');
	}
	const verification = require('./parts/verification.js')(cp, logger);			// do this one last, it needs the others roll in first
	for (const func in verification) cp[func] = verification[func];
	// --------------------------------------------------------------------------------

	// --------------------------------------------------------------------------------
	// Build CP Options
	// --------------------------------------------------------------------------------
	// make a unique id for the sample & channel & org & peer
	cp.makeUniqueId = function () {
		const net_name = cp.getNetworkName();
		const channel = cp.getChannelId();
		const org = cp.getClientOrg();
		const first_peer = cp.getFirstPeerName(channel);
		return misc.saferString('marbles-' + net_name + channel + org + first_peer);
	};

	// build the marbles lib module options
	cp.makeMarblesLibOptions = function () {
		const channel = cp.getChannelId();
		const org_2_use = cp.getClientOrg();
		const first_ca = cp.getFirstCaName(org_2_use);
		const first_peer = cp.getFirstPeerName(channel);
		const first_orderer = cp.getFirstOrdererName(channel);
		return {
			block_delay: cp.getBlockDelay(),
			channel_id: cp.getChannelId(),
			chaincode_id: cp.getChaincodeId(),
			event_urls: (cp.getEventsSetting()) ? cp.getAllPeerUrls(channel).eventUrls : null,	//null is important
			chaincode_version: cp.getChaincodeVersion(),
			ca_tls_opts: cp.getCaTlsCertOpts(first_ca),
			orderer_tls_opts: cp.getOrdererTlsCertOpts(first_orderer),
			peer_tls_opts: cp.getPeerTlsCertOpts(first_peer),
			peer_urls: cp.getAllPeerUrls(channel).urls,
		};
	};

	// build the enrollment options for using an enroll ID
	cp.makeEnrollmentOptions = function (userIndex) {
		if (userIndex === undefined || userIndex == null) {
			throw new Error('User index not passed');
		} else {
			const channel = cp.getChannelId();
			const org_2_use = cp.getClientOrg();
			const first_ca = cp.getFirstCaName(org_2_use);
			const first_peer = cp.getFirstPeerName(channel);
			const first_orderer = cp.getFirstOrdererName(channel);
			const org_name = cp.getClientOrg();
			const user_obj = cp.getEnrollObj(first_ca, userIndex);		//there may be multiple users
			return {
				channel_id: channel,
				uuid: cp.makeUniqueId(),
				ca_urls: cp.getAllCaUrls(),
				ca_name: cp.getCaName(first_ca),
				orderer_url: cp.getOrderersUrl(first_orderer),
				peer_urls: [cp.getPeersUrl(first_peer)],
				enroll_id: user_obj.enrollId,
				enroll_secret: user_obj.enrollSecret,
				msp_id: org_name,
				ca_tls_opts: cp.getCaTlsCertOpts(first_ca),
				orderer_tls_opts: cp.getOrdererTlsCertOpts(first_orderer),
				peer_tls_opts: cp.getPeerTlsCertOpts(first_peer),
				kvs_path: cp.getKvsPath()
			};
		}
	};

	// build the enrollment options using an admin cert
	cp.makeEnrollmentOptionsUsingCert = function () {
		const channel = cp.getChannelId();
		const first_peer = cp.getFirstPeerName(channel);
		const first_orderer = cp.getFirstOrdererName(channel);
		const org_name = cp.getClientOrg();
		return {
			channel_id: channel,
			uuid: cp.makeUniqueId(),
			orderer_url: cp.getOrderersUrl(first_orderer),
			peer_urls: [cp.getPeersUrl(first_peer)],
			msp_id: org_name,
			privateKeyPEM: cp.getAdminPrivateKeyPEM(org_name),
			signedCertPEM: cp.getAdminSignedCertPEM(org_name),
			orderer_tls_opts: cp.getOrdererTlsCertOpts(first_orderer),
			peer_tls_opts: cp.getPeerTlsCertOpts(first_peer),
			kvs_path: cp.getKvsPath()
		};
	};

	// write new settings to config files
	cp.write = function (obj) {
		console.log('saving the creds file has been disabled temporarily');
		var creds_file = cp.creds;
		const channel = cp.getChannelId();
		const org_2_use = cp.getClientOrg();
		const first_peer = cp.getFirstPeerName(channel);
		const first_ca = cp.getFirstCaName(org_2_use);
		const first_orderer = cp.getFirstOrdererName(channel);

		try {
			creds_file = JSON.parse(fs.readFileSync(cp.cp_path, 'utf8'));
		} catch (e) {
			logger.error('file not found', cp.cp_path, e);
		}

		if (obj.ordererUrl) {
			creds_file.orderers[first_orderer].url = obj.ordererUrl;
		}
		if (obj.peerUrl) {
			creds_file.peers[first_peer].url = obj.peerUrl;
		}
		if (obj.caUrl) {
			creds_file.certificateAuthorities[first_ca].url = obj.caUrl;
		}
		if (obj.chaincodeId) {
			let version = cp.getChaincodeVersion();
			if (obj.chaincodeVersion) {						// changing both id and version
				version = obj.chaincodeVersion;
			}
			creds_file.channels[channel].chaincodes = [obj.chaincodeId + ':' + version];
		}
		if (obj.chaincodeVersion) {
			let chaincodeId = cp.getChaincodeId();
			if (obj.chaincodeId) {							// changing both id and version
				chaincodeId = obj.chaincodeVersion;
			}
			creds_file.channels[channel].chaincodes = [chaincodeId + ':' + obj.chaincodeVersion];
		}
		if (obj.channelId) {
			const old_channel_obj = JSON.parse(JSON.stringify(creds_file.channels[channel]));
			creds_file.channels = {};
			creds_file.channels[obj.channelId] = old_channel_obj;
		}
		if (obj.enrollId && obj.enrollSecret) {
			creds_file.certificateAuthorities[first_ca].registrar[0] = {
				enrollId: obj.enrollId,
				enrollSecret: obj.enrollSecret
			};
		}

		try {
			fs.writeFileSync(cp.cp_path, JSON.stringify(creds_file, null, 4), 'utf8');	//save to file
		} catch (e) {
			logger.error('could not write file', cp.cp_path, e);
		}
		cp.creds = creds_file;															//replace old copy
	};

	return cp;
};
<commit_msg>wrong field when writting cp<commit_after>// ============================================================================================================================
// 													Connection Profile Parsing Library
//
// This file is to help safely parse the Connection Profile JSON data
// The connection profile is either in a file ("../../config/" folder) OR it was provided in the environmental variable "CONNECTION_PROFILE"
//
// - every file in this library's folder is getting rolled into the `cp` object. ie any function defined in those files is accessible to this one.
// - if you need something from the connection profile, chance are its defined somewhere in this folder
// ============================================================================================================================
var fs = require('fs');
var path = require('path');

module.exports = function (config_filename, logger) {
	var cp = {};
	var detect_env = require('./parts/detect_env.js')(logger);
	var misc = require('../misc.js')(logger);

	if (!config_filename) {
		config_filename = 'marbles_tls.json';										// default config file name
	}
	cp.config_path = path.join(__dirname, '../../config/' + config_filename);
	cp.config = require(cp.config_path);											// load the config file
	logger.info('Loaded config file', cp.config_path);								// path to config file

	// --------------------------------------------------------------------------------
	// Detect if connection profile data is in an environmental variable instead of a file
	// --------------------------------------------------------------------------------
	let use_env = detect_env.getConnectionProfileFromEnv();
	if (use_env) {																	// to use env or not to use env
		cp.using_env = true;
		cp.cp_path = 'there-is-no-file-using-env';
		cp.creds = use_env;
		logger.info('Loaded connection profile from an environmental variable');
	} else {																		// not in env, look for the files
		cp.using_env = false;
		cp.cp_path = path.join(__dirname, '../../config/' + cp.config.cred_filename);
		cp.creds = require(cp.cp_path);												// load the credential file
		logger.info('Loaded connection profile file', cp.cp_path);					// path to the blockchain connection profile
	}
	cp.config_filename = config_filename;

	// --------------------------------------------------------------------------------
	// Parse connection profile data to get various things:
	// --------------------------------------------------------------------------------
	// get network id
	cp.getNetworkName = function () {
		return cp.creds.name;
	};

	// get cred file name
	cp.getNetworkCredFileName = function () {
		return cp.config.cred_filename;
	};

	// build the tls options for the sdk
	cp.buildTlsOpts = function (node_obj) {
		let ret = {
			'ssl-target-name-override': null,
			pem: null,
			'grpc.http2.keepalive_time': 300,					//grpc 1.2.4
			'grpc.keepalive_time_ms': 300000,					//grpc 1.3.7
			'grpc.http2.keepalive_timeout': 35,					//grpc 1.2.4
			'grpc.keepalive_timeout_ms': 3500,					//grpc 1.3.7
		};
		if (node_obj) {
			if (node_obj.tlsCACerts) {
				ret.pem = cp.loadPem(node_obj.tlsCACerts);
			}
			if (node_obj.grpcOptions) {
				for (var field in ret) {
					if (node_obj.grpcOptions[field]) {
						ret[field] = node_obj.grpcOptions[field];
					}
				}
			}
		}
		return ret;
	};

	// get the very first channel name from creds
	cp.getFirstChannelId = function () {
		if (cp.creds && cp.creds.channels) {
			var channels = Object.keys(cp.creds.channels);
			if (channels[0]) {
				return channels[0];
			}
		}
		throw Error('No channels found in connection profile... this is problematic. A channel needs to be created before marbles can execute.');
	};

	// get the very first channel name from creds
	cp.getChannelId = function () {
		if (process.env.CHANNEL_ID) {							// if env version is set, use it
			return process.env.CHANNEL_ID;
		} else {
			return cp.getFirstChannelId();						// else just grab the first one we got
		}
	};

	// load cert from file path OR just pass cert back
	cp.loadPem = function (obj) {
		if (obj && obj.path) {											// looks like field is a path to a file
			var path2cert = path.join(__dirname, '../../config/' + obj.path);
			if (obj.path.indexOf('/') === 0) {
				path2cert = obj.path;									//its an absolute path
			}
			return fs.readFileSync(path2cert, 'utf8') + '\r\n'; 		//read from file, LOOKING IN config FOLDER
		} else {
			return obj.pem;												//can be null if network is not using TLS
		}
		return null;
	};

	// safely retrieve marbles config file fields
	cp.getMarblesField = function (marbles_field) {
		try {
			if (cp.config[marbles_field]) {
				return cp.config[marbles_field];
			} else {
				logger.warn('"' + marbles_field + '" not found in config json: ' + cp.config_path);
				return null;
			}
		} catch (e) {
			logger.warn('"' + marbles_field + '" not found in config json: ' + cp.config_path);
			return null;
		}
	};

	// --------------------------------------------------------------------------------
	// Absorb all the functions into the cp object
	// --------------------------------------------------------------------------------
	const chaincode = require('./parts/chaincode.js')(cp, logger);
	const ca = require('./parts/ca.js')(cp, logger);
	const peer = require('./parts/peer.js')(cp, logger);
	const helper = require('./parts/helper.js')(cp, logger);
	const orderer = require('./parts/orderer.js')(cp, logger);
	const other = require('./parts/other.js')(cp, logger);
	for (const func in chaincode) cp[func] = chaincode[func];
	for (const func in ca) cp[func] = ca[func];
	for (const func in peer) cp[func] = peer[func];
	for (const func in helper) cp[func] = helper[func];
	for (const func in orderer) cp[func] = orderer[func];
	for (const func in other) cp[func] = other[func];
	const org = require('./parts/org.js')(cp, logger);
	for (const func in org) cp[func] = org[func];

	console.log('\n\n\nConnection Profile Lib Functions:()');
	for (let i in cp) {
		if (typeof cp[i] === 'function') console.log('  ' + i + '()');
	}
	const verification = require('./parts/verification.js')(cp, logger);			// do this one last, it needs the others roll in first
	for (const func in verification) cp[func] = verification[func];
	// --------------------------------------------------------------------------------

	// --------------------------------------------------------------------------------
	// Build CP Options
	// --------------------------------------------------------------------------------
	// make a unique id for the sample & channel & org & peer
	cp.makeUniqueId = function () {
		const net_name = cp.getNetworkName();
		const channel = cp.getChannelId();
		const org = cp.getClientOrg();
		const first_peer = cp.getFirstPeerName(channel);
		return misc.saferString('marbles-' + net_name + channel + org + first_peer);
	};

	// build the marbles lib module options
	cp.makeMarblesLibOptions = function () {
		const channel = cp.getChannelId();
		const org_2_use = cp.getClientOrg();
		const first_ca = cp.getFirstCaName(org_2_use);
		const first_peer = cp.getFirstPeerName(channel);
		const first_orderer = cp.getFirstOrdererName(channel);
		return {
			block_delay: cp.getBlockDelay(),
			channel_id: cp.getChannelId(),
			chaincode_id: cp.getChaincodeId(),
			event_urls: (cp.getEventsSetting()) ? cp.getAllPeerUrls(channel).eventUrls : null,	//null is important
			chaincode_version: cp.getChaincodeVersion(),
			ca_tls_opts: cp.getCaTlsCertOpts(first_ca),
			orderer_tls_opts: cp.getOrdererTlsCertOpts(first_orderer),
			peer_tls_opts: cp.getPeerTlsCertOpts(first_peer),
			peer_urls: cp.getAllPeerUrls(channel).urls,
		};
	};

	// build the enrollment options for using an enroll ID
	cp.makeEnrollmentOptions = function (userIndex) {
		if (userIndex === undefined || userIndex == null) {
			throw new Error('User index not passed');
		} else {
			const channel = cp.getChannelId();
			const org_2_use = cp.getClientOrg();
			const first_ca = cp.getFirstCaName(org_2_use);
			const first_peer = cp.getFirstPeerName(channel);
			const first_orderer = cp.getFirstOrdererName(channel);
			const org_name = cp.getClientOrg();
			const user_obj = cp.getEnrollObj(first_ca, userIndex);		//there may be multiple users
			return {
				channel_id: channel,
				uuid: cp.makeUniqueId(),
				ca_urls: cp.getAllCaUrls(),
				ca_name: cp.getCaName(first_ca),
				orderer_url: cp.getOrderersUrl(first_orderer),
				peer_urls: [cp.getPeersUrl(first_peer)],
				enroll_id: user_obj.enrollId,
				enroll_secret: user_obj.enrollSecret,
				msp_id: org_name,
				ca_tls_opts: cp.getCaTlsCertOpts(first_ca),
				orderer_tls_opts: cp.getOrdererTlsCertOpts(first_orderer),
				peer_tls_opts: cp.getPeerTlsCertOpts(first_peer),
				kvs_path: cp.getKvsPath()
			};
		}
	};

	// build the enrollment options using an admin cert
	cp.makeEnrollmentOptionsUsingCert = function () {
		const channel = cp.getChannelId();
		const first_peer = cp.getFirstPeerName(channel);
		const first_orderer = cp.getFirstOrdererName(channel);
		const org_name = cp.getClientOrg();
		return {
			channel_id: channel,
			uuid: cp.makeUniqueId(),
			orderer_url: cp.getOrderersUrl(first_orderer),
			peer_urls: [cp.getPeersUrl(first_peer)],
			msp_id: org_name,
			privateKeyPEM: cp.getAdminPrivateKeyPEM(org_name),
			signedCertPEM: cp.getAdminSignedCertPEM(org_name),
			orderer_tls_opts: cp.getOrdererTlsCertOpts(first_orderer),
			peer_tls_opts: cp.getPeerTlsCertOpts(first_peer),
			kvs_path: cp.getKvsPath()
		};
	};

	// write new settings to config files
	cp.write = function (obj) {
		console.log('saving the creds file has been disabled temporarily');
		var creds_file = cp.creds;
		const channel = cp.getChannelId();
		const org_2_use = cp.getClientOrg();
		const first_peer = cp.getFirstPeerName(channel);
		const first_ca = cp.getFirstCaName(org_2_use);
		const first_orderer = cp.getFirstOrdererName(channel);

		try {
			creds_file = JSON.parse(fs.readFileSync(cp.cp_path, 'utf8'));
		} catch (e) {
			logger.error('file not found', cp.cp_path, e);
		}

		if (obj.ordererUrl) {
			creds_file.orderers[first_orderer].url = obj.ordererUrl;
		}
		if (obj.peerUrl) {
			creds_file.peers[first_peer].url = obj.peerUrl;
		}
		if (obj.caUrl) {
			creds_file.certificateAuthorities[first_ca].url = obj.caUrl;
		}
		if (obj.chaincodeId) {
			let version = cp.getChaincodeVersion();
			if (obj.chaincodeVersion) {						// changing both id and version
				version = obj.chaincodeVersion;
			}
			creds_file.channels[channel].chaincodes = [obj.chaincodeId + ':' + version];
		}
		if (obj.chaincodeVersion) {
			let chaincodeId = cp.getChaincodeId();
			if (obj.chaincodeId) {							// changing both id and version
				chaincodeId = obj.chaincodeId;
			}
			creds_file.channels[channel].chaincodes = [chaincodeId + ':' + obj.chaincodeVersion];
		}
		if (obj.channelId) {
			const old_channel_obj = JSON.parse(JSON.stringify(creds_file.channels[channel]));
			creds_file.channels = {};
			creds_file.channels[obj.channelId] = old_channel_obj;
		}
		if (obj.enrollId && obj.enrollSecret) {
			creds_file.certificateAuthorities[first_ca].registrar[0] = {
				enrollId: obj.enrollId,
				enrollSecret: obj.enrollSecret
			};
		}

		try {
			fs.writeFileSync(cp.cp_path, JSON.stringify(creds_file, null, 4), 'utf8');	//save to file
		} catch (e) {
			logger.error('could not write file', cp.cp_path, e);
		}
		cp.creds = creds_file;															//replace old copy
	};

	return cp;
};
<|endoftext|>


<commit_before>var PImage = require('../src/pureimage');

var fs = require('fs');
var black = 0x000000ff;
var red =   0xff0000ff;
var green = 0x00ff00ff;

if(!fs.existsSync("build")) {
    fs.mkdirSync("build");
}

{
    var img1 = PImage.make(100,50);

    eq(img1.width,100);
    eq(img1.height,50);
    eq(img1._buffer.length, 100*50*4);

    var ctx = img1.getContext('2d');

    eq(ctx.getPixeli32(0,0), 0x000000ff); // black with 100% alpha
    //ctx.setPixelRGBA(0,0, 255,0,0, 0.5);  // set to red with 50% alpha
    //eq(ctx.getPixeli32(0,0), 0xFF00007F); // red with 50% alpha

    //draw a red rect
    ctx.fillStyle = "#00FFFF";
    ctx.fillRect(10,0,200,200);
    eq(ctx.getPixeli32(1,1), 0x000000FF); // still black outside the rect
    eq(ctx.getPixeli32(15,25), 0x00FFFFFF); // red inside the rect
    ctx.compositePixel(1,1, 0x00FFFFFF); //set 1,1 to the current fill style, which is red
    eq(ctx.getPixeli32(1,1), 0x00FFFFFF); // this pixel is now red
}

{
    var img1 = PImage.make(100,100); // filled with black

    var img2 = PImage.make(16,16);   // filled with black
    eq(img2.width,16);
    eq(img2.height,16);
    var ctx = img2.getContext('2d');
    ctx.fillStyle = "#00ff00";
    ctx.fillRect(0,0,16,16);         //fill img2 with green

    var ctx = img1.getContext('2d');
    ctx.drawImage(img2, 10,10);
    eq(ctx.getPixeli32(0,0), black);
    eq(ctx.getPixeli32(11,11), green);
}

{

    //encoding test
    var img1 = PImage.make(100,100);
    var ctx = img1.getContext('2d');
    //make a simple blue and black checkerboard
    ctx.fillStyle = "blue";
    ctx.fillRect(0,0,50.0,50.0);
    ctx.fillRect(50,50,50,50);
    PImage.encodePNG(img1, fs.createWriteStream('build/checkerboard.png'), function(err) {
        console.log("wrote out the png file to build/checkerboard.png");
    });
}

{
    //simple polygon fill test
    var img1 = PImage.make(100,100);
    var ctx = img1.getContext('2d');
    ctx.fillStyle = 'blue';
    ctx.beginPath();
    ctx.moveTo(10,10);
    ctx.lineTo(100,30);
    ctx.lineTo(90,90);
    ctx.lineTo(10,10);
    ctx.fill();
    PImage.encodePNG(img1, fs.createWriteStream('polygon.png'), function(err) {
        console.log("wrote out the png file to polygon.png");
    });
}

{
    //draw lines with translation
    var img1 = PImage.make(100,100);
    var ctx = img1.getContext('2d');
    ctx.fillStyle = 'green';
    ctx.fillRect(0,0,5,5);
    ctx.translate(30,50);
    ctx.fillRect(0,0,5,5);
    PImage.encodePNG(img1, fs.createWriteStream('translate.png'), function(err) {
        console.log("wrote out the png file to translate.png");
    });

}

{

    //uint32 tests

    var uint32 = require('../src/uint32');
    var int = uint32.toUint32(0xff0000);
    var int2 = uint32.shiftLeft(int,8);
    var int3 = uint32.or(int2,0xff);
}

{
    //antialiased polygon
    var img = PImage.make(10,10);
    var ctx = img.getContext('2d');
    ctx.fillStyle = 'white';
    ctx.beginPath();
    ctx.moveTo(2,2);
    ctx.lineTo(8,2);
    ctx.lineTo(8,8);
    ctx.closePath();
    ctx.fill();
    /*
    for(var j=0; j<img.height; j++) {
        var line = "";
        for(var i=0; i<img.width; i++) {
            var px = (ctx.getPixeli32(i,j)>>24&0xFF);
            var str = px.toString(16);
            if(str == '0') {
                str = '00';
            }
            line += str+' ';
        }
        console.log(line);
    }
    */
    PImage.encodePNG(img, fs.createWriteStream('aapoly.png'), function(err) {
        console.log("wrote out the png file to aapoly.png");
    });
    PImage.encodeJPEG(img, fs.createWriteStream('aapoly.jpg'), function(err) {
        console.log("wrote out the png file to aapoly.jpg");
    });

    ctx.fillStyle = "red";
}

{

    //compositing tests
    var src = 0xFF0000FF;
    var dst = 0xFFFFFFFF;
    eq(PImage.compositePixel(src,dst),0xFF0000FF);
}

function eq(a,b) {
    if(a != b) throw new Error(a.toString(16) + " is not equal to " + b.toString(16));
}
function dumpBytes(img) {
    for(var i=0; i<10; i++) {
        console.log(i,img._buffer[i].toString(16));
    }
}
<commit_msg>move all generated output to build dir<commit_after>var PImage = require('../src/pureimage');

var fs = require('fs');
var black = 0x000000ff;
var red =   0xff0000ff;
var green = 0x00ff00ff;

if(!fs.existsSync("build")) {
    fs.mkdirSync("build");
}

{
    var img1 = PImage.make(100,50);

    eq(img1.width,100);
    eq(img1.height,50);
    eq(img1._buffer.length, 100*50*4);

    var ctx = img1.getContext('2d');

    eq(ctx.getPixeli32(0,0), 0x000000ff); // black with 100% alpha
    //ctx.setPixelRGBA(0,0, 255,0,0, 0.5);  // set to red with 50% alpha
    //eq(ctx.getPixeli32(0,0), 0xFF00007F); // red with 50% alpha

    //draw a red rect
    ctx.fillStyle = "#00FFFF";
    ctx.fillRect(10,0,200,200);
    eq(ctx.getPixeli32(1,1), 0x000000FF); // still black outside the rect
    eq(ctx.getPixeli32(15,25), 0x00FFFFFF); // red inside the rect
    ctx.compositePixel(1,1, 0x00FFFFFF); //set 1,1 to the current fill style, which is red
    eq(ctx.getPixeli32(1,1), 0x00FFFFFF); // this pixel is now red
}

{
    var img1 = PImage.make(100,100); // filled with black

    var img2 = PImage.make(16,16);   // filled with black
    eq(img2.width,16);
    eq(img2.height,16);
    var ctx = img2.getContext('2d');
    ctx.fillStyle = "#00ff00";
    ctx.fillRect(0,0,16,16);         //fill img2 with green

    var ctx = img1.getContext('2d');
    ctx.drawImage(img2, 10,10);
    eq(ctx.getPixeli32(0,0), black);
    eq(ctx.getPixeli32(11,11), green);
}

{

    //encoding test
    var img1 = PImage.make(100,100);
    var ctx = img1.getContext('2d');
    //make a simple blue and black checkerboard
    ctx.fillStyle = "blue";
    ctx.fillRect(0,0,50.0,50.0);
    ctx.fillRect(50,50,50,50);
    PImage.encodePNG(img1, fs.createWriteStream('build/checkerboard.png'), function(err) {
        console.log("wrote out the png file to build/checkerboard.png");
    });
}

{
    //simple polygon fill test
    var img1 = PImage.make(100,100);
    var ctx = img1.getContext('2d');
    ctx.fillStyle = 'blue';
    ctx.beginPath();
    ctx.moveTo(10,10);
    ctx.lineTo(100,30);
    ctx.lineTo(90,90);
    ctx.lineTo(10,10);
    ctx.fill();
    PImage.encodePNG(img1, fs.createWriteStream('build/polygon.png'), function(err) {
        console.log("wrote out the png file to build/polygon.png");
    });
}

{
    //draw lines with translation
    var img1 = PImage.make(100,100);
    var ctx = img1.getContext('2d');
    ctx.fillStyle = 'green';
    ctx.fillRect(0,0,5,5);
    ctx.translate(30,50);
    ctx.fillRect(0,0,5,5);
    PImage.encodePNG(img1, fs.createWriteStream('build/translate.png'), function(err) {
        console.log("wrote out the png file to build/translate.png");
    });

}

{

    //uint32 tests

    var uint32 = require('../src/uint32');
    var int = uint32.toUint32(0xff0000);
    var int2 = uint32.shiftLeft(int,8);
    var int3 = uint32.or(int2,0xff);
}

{
    //antialiased polygon
    var img = PImage.make(10,10);
    var ctx = img.getContext('2d');
    ctx.fillStyle = 'white';
    ctx.beginPath();
    ctx.moveTo(2,2);
    ctx.lineTo(8,2);
    ctx.lineTo(8,8);
    ctx.closePath();
    ctx.fill();
    /*
    for(var j=0; j<img.height; j++) {
        var line = "";
        for(var i=0; i<img.width; i++) {
            var px = (ctx.getPixeli32(i,j)>>24&0xFF);
            var str = px.toString(16);
            if(str == '0') {
                str = '00';
            }
            line += str+' ';
        }
        console.log(line);
    }
    */
    PImage.encodePNG(img, fs.createWriteStream('build/aapoly.png'), function(err) {
        console.log("wrote out the png file to build/aapoly.png");
    });
    PImage.encodeJPEG(img, fs.createWriteStream('build/aapoly.jpg'), function(err) {
        console.log("wrote out the png file to build/aapoly.jpg");
    });

    ctx.fillStyle = "red";
}

{

    //compositing tests
    var src = 0xFF0000FF;
    var dst = 0xFFFFFFFF;
    eq(PImage.compositePixel(src,dst),0xFF0000FF);
}

function eq(a,b) {
    if(a != b) throw new Error(a.toString(16) + " is not equal to " + b.toString(16));
}
function dumpBytes(img) {
    for(var i=0; i<10; i++) {
        console.log(i,img._buffer[i].toString(16));
    }
}
<|endoftext|>


<commit_before>$(document).ready(function() {
  $('#edit_seo_btn').bind('click', function() {
    $('#edit_seo_btn').slideUp();
    $('#edit_seo_dialog').slideDown();
    $('#seo_tag_title').focus();
  });

  $('#cancel_seo_btn, #save_seo_tag').bind('click', function() {
    hideSeoForm();
  });

  $('#more-options-btn').bind('click', function() {
    $('#more-options').show();
    $('#more-options-btn').hide();
  });

});

function hideSeoForm(){
  $('#edit_seo_dialog').slideUp();
  $('#edit_seo_btn').slideDown();
  $('#more-options').hide();
  $('#more-options-btn').show();
}<commit_msg>turbolinks enabeld<commit_after>$(document).on('page:load ready', function() {
  $('#edit_seo_btn').bind('click', function() {
    $('#edit_seo_btn').slideUp();
    $('#edit_seo_dialog').slideDown();
    $('#seo_tag_title').focus();
  });

  $('#cancel_seo_btn, #save_seo_tag').bind('click', function() {
    hideSeoForm();
  });

  $('#more-options-btn').bind('click', function() {
    $('#more-options').show();
    $('#more-options-btn').hide();
  });

});

function hideSeoForm(){
  $('#edit_seo_dialog').slideUp();
  $('#edit_seo_btn').slideDown();
  $('#more-options').hide();
  $('#more-options-btn').show();
}<|endoftext|>


<commit_before>//= require_directory ./SlickGrid-2.1/

var setUpImportClickHandlers = function(url, importCallback) {
  $('.import-commit').click(function() {
    miqSparkleOn();
    clearMessages();

    $.post(url, $('#import-form').serialize(), function(data) {
      var flashMessage = data[0];
      if (flashMessage.level == 'error') {
        showErrorMessage(flashMessage.message);
      } else {
        showSuccessMessage(flashMessage.message);
      }

      $('.import-or-export').show();
      $('.import-data').hide();

      if (importCallback !== undefined) {
        importCallback();
      }

      miqSparkleOff();
    }, 'json');
  });

  $('.import-cancel').click(function() {
    miqSparkleOn();
    clearMessages();

    $.post('cancel_import', $('#import-form').serialize(), function(data) {
      var flashMessage = data[0];
      showSuccessMessage(flashMessage.message);

      $('.import-or-export').show();
      $('.import-data').hide();
      miqSparkleOff();
    }, 'json');
  });

  $('#toggle-all').click(function() {
    $('.import-checkbox').prop('checked', this.checked);
  });
};

var clearMessages = function() {
  $('.import-flash-message .alert').removeClass('alert-success alert-danger alert-warning');
  $('.icon-placeholder').removeClass('pficon pficon-ok pficon-layered');
  $('.pficon-error-octagon').removeClass('pficon-error-octagon');
  $('.pficon-error-exclamation').removeClass('pficon-error-exclamation');
  $('.pficon-warning-triangle').removeClass('pficon-warning-triangle');
  $('.pficon-warning-exclamation').removeClass('pficon-warning-exclamation');
};

var flashMessageClickHandler = function() {
  clearMessages();
  this.hide();
};

var showSuccessMessage = function(message) {
  $('.import-flash-message .alert').addClass('alert-success');
  $('.icon-placeholder').addClass('pficon-ok').addClass('pficon');
  $('.import-flash-message .alert .message').html(message);
  $('.import-flash-message').show();

  $('.import-flash-message').click(flashMessageClickHandler);
};

var showErrorMessage = function(message) {
  $('.import-flash-message .alert').addClass('alert-danger');
  $('.icon-placeholder').addClass('pficon-layered');
  $('.icon-placeholder .pficon').first().addClass('pficon-error-octagon');
  $('.icon-placeholder .pficon').last().addClass('pficon-error-exclamation');
  $('.import-flash-message .alert .message').html(message);
  $('.import-flash-message').show();

  $('.import-flash-message').click(flashMessageClickHandler);
};

var showWarningMessage = function(message) {
  $('.import-flash-message .alert').addClass('alert-warning');
  $('.icon-placeholder').addClass('pficon-layered');
  $('.icon-placeholder .pficon').first().addClass('pficon-warning-triangle');
  $('.icon-placeholder .pficon').last().addClass('pficon-warning-exclamation');
  $('.import-flash-message .alert .message').html(message);
  $('.import-flash-message').show();

  $('.import-flash-message').click(flashMessageClickHandler);
};
<commit_msg>Fix flash message click handler javascript error<commit_after>//= require_directory ./SlickGrid-2.1/

var setUpImportClickHandlers = function(url, importCallback) {
  $('.import-commit').click(function() {
    miqSparkleOn();
    clearMessages();

    $.post(url, $('#import-form').serialize(), function(data) {
      var flashMessage = data[0];
      if (flashMessage.level == 'error') {
        showErrorMessage(flashMessage.message);
      } else {
        showSuccessMessage(flashMessage.message);
      }

      $('.import-or-export').show();
      $('.import-data').hide();

      if (importCallback !== undefined) {
        importCallback();
      }

      miqSparkleOff();
    }, 'json');
  });

  $('.import-cancel').click(function() {
    miqSparkleOn();
    clearMessages();

    $.post('cancel_import', $('#import-form').serialize(), function(data) {
      var flashMessage = data[0];
      showSuccessMessage(flashMessage.message);

      $('.import-or-export').show();
      $('.import-data').hide();
      miqSparkleOff();
    }, 'json');
  });

  $('#toggle-all').click(function() {
    $('.import-checkbox').prop('checked', this.checked);
  });
};

var clearMessages = function() {
  $('.import-flash-message .alert').removeClass('alert-success alert-danger alert-warning');
  $('.icon-placeholder').removeClass('pficon pficon-ok pficon-layered');
  $('.pficon-error-octagon').removeClass('pficon-error-octagon');
  $('.pficon-error-exclamation').removeClass('pficon-error-exclamation');
  $('.pficon-warning-triangle').removeClass('pficon-warning-triangle');
  $('.pficon-warning-exclamation').removeClass('pficon-warning-exclamation');
};

var flashMessageClickHandler = function() {
  clearMessages();
  $(this).hide();
};

var showSuccessMessage = function(message) {
  $('.import-flash-message .alert').addClass('alert-success');
  $('.icon-placeholder').addClass('pficon-ok').addClass('pficon');
  $('.import-flash-message .alert .message').html(message);
  $('.import-flash-message').show();

  $('.import-flash-message').click(flashMessageClickHandler);
};

var showErrorMessage = function(message) {
  $('.import-flash-message .alert').addClass('alert-danger');
  $('.icon-placeholder').addClass('pficon-layered');
  $('.icon-placeholder .pficon').first().addClass('pficon-error-octagon');
  $('.icon-placeholder .pficon').last().addClass('pficon-error-exclamation');
  $('.import-flash-message .alert .message').html(message);
  $('.import-flash-message').show();

  $('.import-flash-message').click(flashMessageClickHandler);
};

var showWarningMessage = function(message) {
  $('.import-flash-message .alert').addClass('alert-warning');
  $('.icon-placeholder').addClass('pficon-layered');
  $('.icon-placeholder .pficon').first().addClass('pficon-warning-triangle');
  $('.icon-placeholder .pficon').last().addClass('pficon-warning-exclamation');
  $('.import-flash-message .alert .message').html(message);
  $('.import-flash-message').show();

  $('.import-flash-message').click(flashMessageClickHandler);
};
<|endoftext|>


<commit_before>/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016, 2017 Waltz open source project
 * See README.md for more information
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import _ from "lodash";
import {initialiseData} from "../common";
import template from './actors-view.html';

const initialState = {
    actors: [],
    creatingActor: false,
    newActor: { isExternal: false }
};

function controller($q,
                    actorService,
                    notification) {

    const vm = initialiseData(this, initialState);

    function update(actor, change) {
        const updateCmd = Object.assign(change, { id: actor.id });
        return actorService.update(updateCmd)
            .then(() => notification.success('Updated'));
    }

    vm.updateName = (change, actor) => {
        if(change.newVal === "") return $q.reject("Too short");
        return update(actor, { name: change })
            .then(() => _.find(vm.actors, {'id': actor.id}).name = change.newVal);
    };

    vm.updateDescription = (change, actor) => {
        if(change.newVal === "") return $q.reject("Too short");
        return update(actor, { description: change })
            .then(() => _.find(vm.actors, {'id': actor.id}).description = change.newVal);
    };

    vm.updateIsExternal = (change, actor) => {
        if(change.newVal === null) return $q.reject("No value provided");
        return update(actor, { isExternal: change })
            .then(() => _.find(vm.actors, {'id': actor.id}).isExternal = change.newVal);
    };

    vm.startNewActor = () => {
        vm.creatingActor = true;
    };

    vm.saveNewActor = () => {
        actorService
            .create(vm.newActor)
            .then(() => {
                notification.success('Created');
                vm.creatingActor = false;
                vm.newActor = {};
                loadActors();
            });

    };

    vm.cancelNewActor = () => {
        vm.creatingActor = false;
        console.log('cancelled new');
    };

    function loadActors() {
        actorService
            .loadActors()
            .then(kinds => {
                vm.actors = kinds;
            });
    }

    loadActors();
}

controller.$inject = [
    '$q',
    'ActorService',
    'Notification'
];

export default {
    template,
    controller,
    controllerAs: 'ctrl',
    bindToController: true,
    scope: {}
};
<commit_msg>Update actors-view.js<commit_after>/*
 * Waltz - Enterprise Architecture
 * Copyright (C) 2016, 2017 Waltz open source project
 * See README.md for more information
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import _ from "lodash";
import {initialiseData} from "../common";
import template from "./actors-view.html";

const initialState = {
    actors: [],
    creatingActor: false,
    newActor: { isExternal: false }
};

function controller($q,
                    actorService,
                    notification) {

    const vm = initialiseData(this, initialState);

    function update(actor, change) {
        const updateCmd = Object.assign(change, { id: actor.id });
        return actorService.update(updateCmd)
            .then(() => notification.success("Updated"));
    }

    vm.updateName = (change, actor) => {
        if(change.newVal === "") return $q.reject("Too short");
        return update(actor, { name: change })
            .then(() => _.find(vm.actors, {"id": actor.id}).name = change.newVal);
    };

    vm.updateDescription = (change, actor) => {
        if(change.newVal === "") return $q.reject("Too short");
        return update(actor, { description: change })
            .then(() => _.find(vm.actors, {"id": actor.id}).description = change.newVal);
    };

    vm.updateIsExternal = (change, actor) => {
        if(change.newVal === null) return $q.reject("No value provided");
        return update(actor, { isExternal: change })
            .then(() => _.find(vm.actors, {"id": actor.id}).isExternal = change.newVal);
    };

    vm.startNewActor = () => {
        vm.creatingActor = true;
    };

    vm.saveNewActor = () => {
        actorService
            .create(vm.newActor)
            .then(() => {
                notification.success("Created");
                vm.creatingActor = false;
                vm.newActor = {};
                loadActors();
            });

    };

    vm.cancelNewActor = () => {
        vm.creatingActor = false;
        console.log("cancelled new");
    };

    function loadActors() {
        actorService
            .loadActors()
            .then(kinds => {
                vm.actors = kinds;
            });
    }

    loadActors();

    vm.selectActor = (actor) => {
        vm.selectedActor = actor;
    }

}

controller.$inject = [
    "$q",
    "ActorService",
    "Notification",
];

export default {
    template,
    controller,
    controllerAs: "$ctrl",
    bindToController: true,
    scope: {}
};
<|endoftext|>


<commit_before>import {CREATE_NETWORK_CLASS, CREATE_NETWORK_MODAL} from "./constants";
import { queryNetworkDatabase } from "./api/grnsight-api";
import { grnState } from "./grnstate";

export const createNetwork = function () {
    const createHTMLforForm = (sources) => {
        let result =  `

Create Network

            Network Source
            <select class=\'network-dropdown\' id=\'network-source\'>
                <option value=\'none\' selected=\'true\' disabled hidden>Select Network Source</option>
                    `;
        for (let source in sources) {
            result += `
                        <option value=\'${source}\'>${sources[source]}</option>
            `;
        }
        result += `</select>

Warning: changing network source will remove all current genes in network

            Select genes
            <input type=\'text\' id=\'network-search-bar\' name=\'network-search-bar\'></input>
            <button id=\'enter-search\' class=\'search-button\'>

            </button>

Added genes go here! Click on a gene to remove it

        <input type=\'submit\' id=\'submit-network\' value=\'Create Network\'></input>

        `;
        return result;
    };
    const createGeneButtons = function () {
        let result =  `

Added genes go below! Click on a gene to remove it.

        `
        for (let gene in grnState.customWorkbook.genes) {
            result += `

                        ${grnState.customWorkbook.genes[gene]}

                        (${gene})

            `
        }

        result += "

"
        return result
    };
    const displayCurrentGenes = function () {
        $("#selected-genes").remove();
        $("#selected-genes-container").append(createGeneButtons());
        for (let gene in grnState.customWorkbook.genes) {
            console.log(gene);
            $(`#${gene}`).on("click", (ev) => {
                ev.stopPropagation();
                $(`#${gene}`).remove();
                delete grnState.customWorkbook.genes[gene];
            });
        }
    };

    const addGene = function() {
        console.log("Begin Add Gene")
        let gene = `${$("#network-search-bar").val()}`;
        console.log(gene)
        // console.log("Gets here")
        // let source = grnState.customWorkbook.source
        // console.log("Gets here 2")
        $("#network-search-bar").val("")
        // console.log("Gets here")
        // console.log(`Gene: ${gene}`);
        // console.log(`Source: ${grnState.customWorkbook.sources[source].source}`);
        // console.log(`TimeStamp: ${grnState.customWorkbook.sources[source].timestamp}`);
        grnState.customWorkbook.genes[gene.toUpperCase()] = gene.toLowerCase()
        // get genes from database
            // queryNetworkDatabase({
            //     type:"NetworkGeneFromSource",
            //     info: {
            //         gene,
            //         source:grnState.customWorkbook.sources[source].source,
            //         timestamp:grnState.customWorkbook.sources[source].timestamp
            //     }
            // }).then(function (response) {
            //     let x = response
            //     console.log(x)
            // }).catch(function (error) {
            //     console.log(error.stack);
            //     console.log(error.name);
            //     console.log(error.message);
            // });
    };

    const updateGenes = function () {
        addGene();
        displayCurrentGenes();
    };

    const displayCreateNetworkModal = function () {
        $("#createNetworkFormContainer").remove();
        // $("#creatNetworkQuestions-container").append(createHTMLforForm(["1", "2", "3"]));
        grnState.customWorkbook = {
            genes : {},
            source : null
        };
    // get sources from database
        queryNetworkDatabase({type:"NetworkSource", info:null}).then(function (response) {
            $("#creatNetworkQuestions-container").append(createHTMLforForm(Object.keys(response.sources)));
            grnState.customWorkbook.sources = response.sources;
            console.log(grnState.customWorkbook)
        }).catch(function (error) {
            console.log(error.stack);
            console.log(error.name);
            console.log(error.message);
        });
        $("#network-source").on("change", () => {
            grnState.customWorkbook.source = $("#network-source").val();
            grnState.customWorkbook.genes = {};
            ev.stopPropagation();
            displayCurrentGenes();
        });
        // $('#getNetworkGenesForm').on("submit", ev => {
        //     let gene = `${$("#network-search-bar").val()}`;
        //     let source = grnState.customWorkbook.source
        //     console.log("Gets here");
        //     ev.stopPropagation();
        //     queryNetworkDatabase({
        //         type:"NetworkGeneFromSource",
        //         info: {
        //             gene,
        //             source:grnState.customWorkbook.sources[source].source,
        //             timestamp:grnState.customWorkbook.sources[source].timestamp
        //         }
        //     }).then(function (response) {
        //         let x = response
        //         console.log(x)
        //     }).catch(function (error) {
        //         console.log(error.stack);
        //         console.log(error.name);
        //         console.log(error.message);
        //     });
        //     return false;
        // });
        $("#enter-search").on("click", (ev) => {
            console.log("search button has been clicked")
            ev.stopPropagation();
            updateGenes();
        });
        $("#network-search-bar").on("keydown", (ev) => {
            if(ev.key === 'Enter') {
                console.log("search bar has been entered")
                ev.preventDefault();
                ev.stopPropagation();
                updateGenes();
            }
        });
        $(CREATE_NETWORK_MODAL).modal("show");
    };

    const performNetworkCreation = function () {
        return function () {
            displayCreateNetworkModal();
        };
    };

    // $(CREATE_NETWORK_CLASS).one("click", performNetworkCreation());
    $("body").on("click", CREATE_NETWORK_CLASS, performNetworkCreation());
};
<commit_msg>changed order of jquery event handlers<commit_after>import {CREATE_NETWORK_CLASS, CREATE_NETWORK_MODAL} from "./constants";
import { queryNetworkDatabase } from "./api/grnsight-api";
import { grnState } from "./grnstate";

export const createNetwork = function () {
    const createHTMLforForm = (sources) => {
        let result =  `

Create Network

            Network Source
            <select class=\'network-dropdown\' id=\'network-source\'>
                <option value=\'none\' selected=\'true\' disabled hidden>Select Network Source</option>
                    `;
        for (let source in sources) {
            result += `
                        <option value=\'${source}\'>${sources[source]}</option>
            `;
        }
        result += `</select>

Warning: changing network source will remove all current genes in network

            Select genes
            <input type=\'text\' id=\'network-search-bar\' name=\'network-search-bar\'></input>
            <button id=\'enter-search\' class=\'search-button\'>

            </button>

Added genes go here! Click on a gene to remove it

        <input type=\'submit\' id=\'submit-network\' value=\'Create Network\'></input>

        `;
        return result;
    };
    const createGeneButtons = function () {
        let result =  `

Added genes go below! Click on a gene to remove it.

        `
        for (let gene in grnState.customWorkbook.genes) {
            result += `

                        ${grnState.customWorkbook.genes[gene]}

                        (${gene})

            `
        }

        result += "

"
        return result
    };
    const displayCurrentGenes = function () {
        $("#selected-genes").remove();
        $("#selected-genes-container").append(createGeneButtons());
        for (let gene in grnState.customWorkbook.genes) {
            console.log(gene);
            $(`#${gene}`).on("click", (ev) => {
                ev.stopPropagation();
                $(`#${gene}`).remove();
                delete grnState.customWorkbook.genes[gene];
            });
        }
    };

    const addGene = function() {
        console.log("Begin Add Gene")
        let gene = `${$("#network-search-bar").val()}`;
        console.log(gene)
        // console.log("Gets here")
        // let source = grnState.customWorkbook.source
        // console.log("Gets here 2")
        $("#network-search-bar").val("")
        // console.log("Gets here")
        // console.log(`Gene: ${gene}`);
        // console.log(`Source: ${grnState.customWorkbook.sources[source].source}`);
        // console.log(`TimeStamp: ${grnState.customWorkbook.sources[source].timestamp}`);
        grnState.customWorkbook.genes[gene.toUpperCase()] = gene.toLowerCase()
        // get genes from database
            // queryNetworkDatabase({
            //     type:"NetworkGeneFromSource",
            //     info: {
            //         gene,
            //         source:grnState.customWorkbook.sources[source].source,
            //         timestamp:grnState.customWorkbook.sources[source].timestamp
            //     }
            // }).then(function (response) {
            //     let x = response
            //     console.log(x)
            // }).catch(function (error) {
            //     console.log(error.stack);
            //     console.log(error.name);
            //     console.log(error.message);
            // });
    };

    const updateGenes = function () {
        addGene();
        displayCurrentGenes();
    };

    const displayCreateNetworkModal = function () {
        $("#createNetworkFormContainer").remove();
        // $("#creatNetworkQuestions-container").append(createHTMLforForm(["1", "2", "3"]));
        grnState.customWorkbook = {
            genes : {},
            source : null
        };
    // get sources from database
        queryNetworkDatabase({type:"NetworkSource", info:null}).then(function (response) {
            $("#creatNetworkQuestions-container").append(createHTMLforForm(Object.keys(response.sources)));
            grnState.customWorkbook.sources = response.sources;
            console.log(grnState.customWorkbook)
        }).catch(function (error) {
            console.log(error.stack);
            console.log(error.name);
            console.log(error.message);
        });
        // $('#getNetworkGenesForm').on("submit", ev => {
        //     let gene = `${$("#network-search-bar").val()}`;
        //     let source = grnState.customWorkbook.source
        //     console.log("Gets here");
        //     ev.stopPropagation();
        //     queryNetworkDatabase({
        //         type:"NetworkGeneFromSource",
        //         info: {
        //             gene,
        //             source:grnState.customWorkbook.sources[source].source,
        //             timestamp:grnState.customWorkbook.sources[source].timestamp
        //         }
        //     }).then(function (response) {
        //         let x = response
        //         console.log(x)
        //     }).catch(function (error) {
        //         console.log(error.stack);
        //         console.log(error.name);
        //         console.log(error.message);
        //     });
        //     return false;
        // });
        $("#network-source").on("change", () => {
            grnState.customWorkbook.source = $("#network-source").val();
            grnState.customWorkbook.genes = {};
            console.log("User changed source!")
            console.log(grnState.customWorkbook)
            ev.stopPropagation();
            displayCurrentGenes();
        });
        $(CREATE_NETWORK_MODAL).modal("show");
        $("#enter-search").on("click", (ev) => {
            console.log("search button has been clicked")
            ev.stopPropagation();
            updateGenes();
        });
        $("#network-search-bar").on("keydown", (ev) => {
            if(ev.key === 'Enter') {
                console.log("search bar has been entered")
                ev.preventDefault();
                ev.stopPropagation();
                updateGenes();
            }
        });
    };

    const performNetworkCreation = function () {
        return function () {
            displayCreateNetworkModal();
        };
    };

    // $(CREATE_NETWORK_CLASS).one("click", performNetworkCreation());
    $("body").on("click", CREATE_NETWORK_CLASS, performNetworkCreation());
};
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Open Networking Laboratory
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 Sample view to illustrate key bindings.

 @author Simon Hunt
 */

(function (onos) {
    'use strict';

    var keyDispatch =  {
        Z: keyUndo,
        X: keyCut,
        C: keyCopy,
        V: keyPaste,
        space: keySpace
    };

    function keyUndo(view) {
        note(view, 'Z = UNDO');
    }

    function keyCut(view) {
        note(view, 'X = CUT');
    }

    function keyCopy(view) {
        note(view, 'C = COPY');
    }

    function keyPaste(view) {
        note(view, 'V = PASTE');
    }

    function keySpace(view) {
        note(view, 'The SpaceBar');
    }

    function note(view, msg) {
        view.$div.append('p')
            .text(msg)
            .style({
                'font-size': '10pt',
                color: 'darkorange',
                padding: '0 20px',
                margin: 0
            });
    }

    function keyCallback(view, key, keyCode, event) {
        note(view, 'Key = ' + key + ' KeyCode = ' + keyCode);
    }

    // Keys using a keyset to target specific keys only
    function load(view, ctx) {
        // this maps specific keys to specific functions (1)
        view.setKeys(keyDispatch);
        // whereas, this installs a general key handler function (2)
        view.setKeys(keyCallback);

        // Note that (1) takes precedence over (2)

        view.$div.append('p')
            .text('Press a key or two (try Z,X,C,V and others) ...')
            .style('padding', '2px 8px');
    }

    // == register the view here, with links to lifecycle callbacks

    onos.ui.addView('sampleKeys', {
        reset: true,    // empty the div on reset
        load: load
    });

}(ONOS));
<commit_msg>GUI -- Removed out of date comment.<commit_after>/*
 * Copyright 2014 Open Networking Laboratory
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 Sample view to illustrate key bindings.

 @author Simon Hunt
 */

(function (onos) {
    'use strict';

    var keyDispatch =  {
        Z: keyUndo,
        X: keyCut,
        C: keyCopy,
        V: keyPaste,
        space: keySpace
    };

    function keyUndo(view) {
        note(view, 'Z = UNDO');
    }

    function keyCut(view) {
        note(view, 'X = CUT');
    }

    function keyCopy(view) {
        note(view, 'C = COPY');
    }

    function keyPaste(view) {
        note(view, 'V = PASTE');
    }

    function keySpace(view) {
        note(view, 'The SpaceBar');
    }

    function note(view, msg) {
        view.$div.append('p')
            .text(msg)
            .style({
                'font-size': '10pt',
                color: 'darkorange',
                padding: '0 20px',
                margin: 0
            });
    }

    function keyCallback(view, key, keyCode, event) {
        note(view, 'Key = ' + key + ' KeyCode = ' + keyCode);
    }

    function load(view, ctx) {
        // this maps specific keys to specific functions (1)
        view.setKeys(keyDispatch);
        // whereas, this installs a general key handler function (2)
        view.setKeys(keyCallback);

        // Note that (1) takes precedence over (2)

        view.$div.append('p')
            .text('Press a key or two (try Z,X,C,V and others) ...')
            .style('padding', '2px 8px');
    }

    // == register the view here, with links to lifecycle callbacks

    onos.ui.addView('sampleKeys', {
        reset: true,    // empty the div on reset
        load: load
    });

}(ONOS));
<|endoftext|>


<commit_before>config = require('./../config/config.js');
var request = require("request");
//var tidy = require('htmltidy').tidy;
var pg = require('pg');
//var htmltidyOptions = require('htmltidy-options');

module.exports = function(app, passport) {

    // INDEX PAGE ===============================
    app.get('/dbmiannotator', function(req, res) {
	    if (req.isAuthenticated()){
            res.redirect('/dbmiannotator/main');
	    } else {
	        res.render('index.ejs', { message: req.flash('loginMessage') });
	    }
    });

    // LOGIN ===============================
    app.get('/dbmiannotator/login', function(req, res) {
        // render the page and pass in any flash data if it exists
        res.render('login.ejs', { message: req.flash('loginMessage') });
    });

    app.post('/dbmiannotator/login', passport.authenticate('local-login', {
        successRedirect : '/dbmiannotator/main',
        failureRedirect : '/dbmiannotator/login',
        failureFlash : true
    }));

    // SIGNUP ==============================
    app.get('/dbmiannotator/register', function(req, res) {
        res.render('register.ejs', { message: req.flash('signupMessage') });
    });

    app.post('/dbmiannotator/register', isRegisterFormValid, passport.authenticate('local-signup', {
	successRedirect : '/dbmiannotator/main',
	failureRedirect : '/dbmiannotator/register',
	failureFlash : true
    })
	    );

    // MAIN ==============================
    app.get('/dbmiannotator/main', isLoggedIn, initPluginProfile, function(req, res) {
        if (config.profile.userProfile != null) {
            annotationType = config.profile.userProfile.type;
        } else {
            annotationType = config.profile.def;
        }

	    // fetch all DDI annotations for current user
	    var url = "http://" + config.store.host +":" + config.store.port + "/search?email=" + req.user.email + "&annotationType=" + annotationType;

		res.render('main.ejs', {
		    user : req.user,
		    annotations : [],
		    exportMessage : req.flash('exportMessage'),
		    loadMessage : req.flash('loadMessage'),
		    host : config.annotator.host,
		});

	    // request({url: url, json: true}, function(error,response,body){
	    //     if (!error && response.statusCode === 200) {

		//         res.render('main.ejs', {
		//             user : req.user,
		//             annotations : body,
		//             exportMessage : req.flash('exportMessage'),
		//             loadMessage : req.flash('loadMessage'),
		//             host : config.annotator.host,
		//         });

	    //     } else {
		//         res.render('main.ejs', {
		//             user : req.user,
		//             annotations : {'total':0},
		//             exportMessage: req.flash('exportMessage'),
		//             loadMessage: req.flash('loadMessage'),
		//             host: config.annotator.host,
		//         });
	    //     }
	    // });
    });

    // LOGOUT ==============================
    app.get('/dbmiannotator/logout', function(req, res) {
        config.profile.pluginSetL = [];
        config.profile.userProfile = {};
        req.logout();
        res.redirect('/dbmiannotator');
    });

    // DISPLAY ==============================
    app.get('/dbmiannotator/displayWebPage', isLoggedIn, praseWebContents, function(req, res) {

	    var sourceUrl = req.query.sourceURL.trim();
	    var email = req.query.email;
	    var validUrl = require('valid-url');

	    if (validUrl.isUri(sourceUrl)){

		    // if (sourceUrl.match(/\.pdf/g)){ // local pdf resouces
		    //     res.redirect("/dbmiannotator/viewer.html?file=" + sourceUrl+"&email=" + email);
		    // }

		    if (sourceUrl.match(/localhost.*html/g)) {
                res.render('displayWebPage.ejs', {
			        htmlsource: req.htmlsource,
			        pluginSetL: config.profile.pluginSetL,
			        userProfile: config.profile.userProfile
                });
	        }
		    else {
		        req.flash('loadMessage', 'The url you just entered is not valid!');
		        res.redirect('/dbmiannotator/main');
		    }

	    }
    });

    // PLUGIN PROFILE ==============================
    app.post('/dbmiannotator/savePluginProfile', function(req, res) {
        console.log(req.body.pluginset);
        console.log(req.user.email);

        pg.connect(config.postgres, function(err, client, done) {

            if(err) {
                done();
                console.log(err);
                return res.status(500).json({ success: false, data: err});
            }

            if (config.profile.userProfile == null){  // no user profile, then insert
                console.log("[ERROR] user profile not avaliable!");
	            res.redirect('/dbmiannotator/main');

            } else {   // get user profile
                resultsL = []
                var queryUserProfile = client.query('SELECT u.uid, up.set_id FROM "user" u, user_profile up where u.uid = up.uid and u.email = $1 and up.status = $2', [req.user.email, true]);
                queryUserProfile.on('row', function(row) {
                    resultsL.push(row);
                });

                queryUserProfile.on('end', function() { // user profile changed, then update
                    if (resultsL[0].set_id != req.body.pluginset){
                        console.log("update user plugin profile");
                        client.query('UPDATE "user_profile" SET set_id = $1, created = now() FROM (SELECT * FROM "user" u where u.email = $2) AS u, "user_profile" up WHERE up.uid = u.uid AND up.status = true', [req.body.pluginset, req.user.email]);
                        done();
	                res.redirect('/dbmiannotator/main');
                    }
                    else {
                        console.log("user profile not need to update");
                        done();
	                res.redirect('/dbmiannotator/main');
                    }
                }, function(){
                    res.redirect('/dbmiannotator/main');
                });
            }

        });
    });

    // EXPORT TO JSON ==============================
    app.get('/dbmiannotator/exportjson', isLoggedIn, function(req, res){

	    var url = "http://" + config.store.host + ":" + config.store.port + "/search?email=" + req.query.email + "&annotationType=" + config.profile.def;

	    request({url: url, json: true}, function(error,response,body){
	        if (!error && response.statusCode === 200) {

                var annsJsonRes = JSON.stringify(body.rows);
                res.attachment('annotations-'+req.query.email+'.json');
		        res.setHeader('Content-Type', 'application/json');
		        res.end(annsJsonRes);
	        } else {
		        res.redirect('/dbmiannotator/main');
	        }
	    });
    });

    // EXPORT TO CSV ==============================
    app.get('/dbmiannotator/exportcsv', isLoggedIn, function(req, res){

	    var url = "http://" + config.store.host + ":" + config.store.port + "/search?email=" + req.query.email + "&annotationType=" + config.profile.def;

	    request({url: url, json: true}, function(error,response,body){
	        if (!error && response.statusCode === 200) {

                var jsonObjs = body.rows;

                res.attachment('annotations-'+req.query.email+'.csv');
		        res.setHeader('Content-Type', 'text/csv');
                var csvTxt = '"document"\t"claim label"\t"claim text"\t"method"\t"relationship"\t"drug1"\t"drug2"\t"precipitant"\t"enzyme"\t"evRelationship"\t"participants"\t"participants text"\t"drug1 dose"\t"drug1 formulation"\t"drug1 duration"\t"drug1 regimens"\t"drug1 dose text"\t"drug2 dose"\t"drug2 formulation"\t"drug2 duration"\t"drug2 regimens"\t"drug2 dose text"\t"auc"\t"auc type"\t"auc direction"\t"auc text"\t"cmax"\t"cmax type"\t"cmax direction"\t"cmax text"\t"cl"\t"cl type"\t"cl direction"\t"cl text"\t"halflife"\t"halflife type"\t"halflife direction"\t"halflife text"\t"group randomization"\t"parallel group design"\n';

                for (var i = 0; i < jsonObjs.length; i++) {
                    jsonObj = jsonObjs[i];
                    claim = jsonObj.argues;
                    dataL = claim.supportsBy;

                    var claimRow = '"' + jsonObj.rawurl + '"\t"' + claim.label + '"\t"' + claim.hasTarget.hasSelector.exact + '"\t"' + claim.method + '"\t"' + claim.qualifiedBy.relationship + '"\t"' + claim.qualifiedBy.drug1 + '"\t"' + claim.qualifiedBy.drug2 + '"\t"' + (claim.qualifiedBy.precipitant || '') + '"\t"' + (claim.qualifiedBy.enzyme || '' ) + '"';
                    csvTxt += claimRow;

                    for (var j = 0; j < dataL.length; j++) {
                        var data = dataL[j];
                        var method = data.supportsBy;
                        var material = method.supportsBy;
                        var dataRow = "";

                        dataRow += '\t"' + (data.evRelationship || '') + '"';

                        if (material.participants != null)
                            dataRow += '\t"' + (material.participants.value || '') + '"\t"' + (getSpanFromField(material.participants) || '') + '"';
                        else
                            dataRow += '\t\t';

                        if (material.drug1Dose != null)
                            dataRow += '\t"' + (material.drug1Dose.value || '') + '"\t"' + (material.drug1Dose.formulation || '') + '"\t"'  + (material.drug1Dose.duration || '') + '"\t"' + (material.drug1Dose.regimens || '') + '"\t"' + (getSpanFromField(material.drug1Dose) || '') + '"';
                        else
                            dataRow += '\t\t\t\t';

                        if (material.drug2Dose != null)
                            dataRow += '\t"' + (material.drug2Dose.value || '') + '"\t"' + (material.drug2Dose.formulation || '') + '"\t"'  + (material.drug2Dose.duration || '') + '"\t"' + (material.drug2Dose.regimens || '') + '"\t"' + (getSpanFromField(material.drug2Dose) || '') + '"';
                        else
                            dataRow += '\t\t\t\t';

                        dataFieldsL = ["auc","cmax","clearance","halflife"];
                        for (p = 0; p < dataFieldsL.length; p++) {
                            field = dataFieldsL[p];
                            if (data[field] != null)
                                dataRow += '\t"' + (data[field].value || '') + '"\t"' + (data[field].type || '') + '"\t"' + (data[field].direction || '') + '"\t"' + (getSpanFromField(data[field]) || '') + '"';
                            else
                                dataRow += '\t\t\t\t';
                        }

                        if (data.grouprandom != null)
                            dataRow += '\t"' + (data.grouprandom || '') + '"';
                        else
                            dataRow += '\t';

                        if (data.parallelgroup != null)
                            dataRow += '\t"' + (data.parallelgroup || '') + '"';
                        else
                            dataRow += '\t';

                        csvTxt += dataRow + "\n";
                    }
                }

		        res.attachment('annotations-'+req.query.email+'.csv');
		        res.setHeader('Content-Type', 'text/csv');
		        res.end(csvTxt);

	        } else {
		        //req.flash('exportMessage', 'exported failed, annotation fetch exception, please see logs or contact Yifan at yin2@pitt.edu!');
		        res.redirect('/dbmiannotator/main');
	        }
	    });
    });
};

// UTIL FUNCTIONS ==============================
function getSpanFromField(field) {
    if (field.hasTarget !=null) {
        if (field.hasTarget.hasSelector !=null)
            return field.hasTarget.hasSelector.exact;
    } else {
        return "";
    }
}

// MIDDLE WARE FUNCTIONS ==============================

// parse web contents from url
function praseWebContents(req, res, next){
    var sourceUrl = req.query.sourceURL.trim();

    if(sourceUrl.match(/localhost.*html/g)){
        var options = {
            host: sourceUrl,
            method: 'POST'
        }

        request(sourceUrl, function(err, res, body){

            // skip tidy beacuse changing of char encoding
            labelDecode = body.replace(/&/g,'&').replace(/ /g,' ');
            req.htmlsource = labelDecode;
            next();

            // normalize html source
            // tidy(labelDecode, htmltidyOptions['Kastor tidy - XHTML Clean page UTF-8'], function(err, html) {
            //     if (err){
            //         console.log(err);
            //     }
            //     req.htmlsource = html;
            //     next();
            // });

        });

    } else {
        next();
    }
}

// get plugin profile
function initPluginProfile(req, res, next){
    var pluginSetL = [];
    var userProfileL = [];

    var data = {text: req.body.text, complete: false};

    pg.connect(config.postgres, function(err, client, done) {

        if(err) {
            done();
            console.log(err);
            return res.status(500).json({ success: false, data: err});
        }
        // get all available plugin sets
        var queryPlugins = client.query("SELECT ps.id, ps.name, ps.type, ps.description FROM plugin_set ps WHERE ps.status = True ORDER BY ps.id ASC;");

        queryPlugins.on('row', function(row) {
            pluginSetL.push(row);
        });

        queryPlugins.on('end', function() {
            config.profile.pluginSetL = pluginSetL;
        });
        // get plugin set from user setting
        var queryUserProfile = client.query('SELECT u.uid, up.set_id, ps.name, ps.type FROM "user" u, "user_profile" up, "plugin_set" ps where u.uid = up.uid and up.set_id = ps.id and u.email = $1 and up.status = True', [req.user.email]);

        queryUserProfile.on('row', function(row) {
            userProfileL.push(row);
        });
        queryUserProfile.on('end', function() {
            if (userProfileL.length > 0){
                config.profile.userProfile = userProfileL[0];
                console.log("init pluginProfile - get user profile");
                console.log(config.profile.userProfile)
            }
            next();
            client.end();
        });

    });
}

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/dbmiannotator');
}

// validate inputs in register form
function isRegisterFormValid(req, res, next){

    req.assert('email', 'Email is not valid').isEmail();
    req.assert('username', 'Username must be at least 4 characters long').len(4);
    req.assert('password', 'Password must be at least 6 characters long').len(6);
    req.assert('repassword', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if (errors) {

	res.render('register', {
	    title: 'Register Form Validation',
	    message: '',
	    errors: errors
        });

    } else {
	return next();
    }

}

<commit_msg>add annotation id to exported csv<commit_after>config = require('./../config/config.js');
var request = require("request");
//var tidy = require('htmltidy').tidy;
var pg = require('pg');
//var htmltidyOptions = require('htmltidy-options');

module.exports = function(app, passport) {

    // INDEX PAGE ===============================
    app.get('/dbmiannotator', function(req, res) {
	    if (req.isAuthenticated()){
            res.redirect('/dbmiannotator/main');
	    } else {
	        res.render('index.ejs', { message: req.flash('loginMessage') });
	    }
    });

    // LOGIN ===============================
    app.get('/dbmiannotator/login', function(req, res) {
        // render the page and pass in any flash data if it exists
        res.render('login.ejs', { message: req.flash('loginMessage') });
    });

    app.post('/dbmiannotator/login', passport.authenticate('local-login', {
        successRedirect : '/dbmiannotator/main',
        failureRedirect : '/dbmiannotator/login',
        failureFlash : true
    }));

    // SIGNUP ==============================
    app.get('/dbmiannotator/register', function(req, res) {
        res.render('register.ejs', { message: req.flash('signupMessage') });
    });

    app.post('/dbmiannotator/register', isRegisterFormValid, passport.authenticate('local-signup', {
	successRedirect : '/dbmiannotator/main',
	failureRedirect : '/dbmiannotator/register',
	failureFlash : true
    })
	    );

    // MAIN ==============================
    app.get('/dbmiannotator/main', isLoggedIn, initPluginProfile, function(req, res) {
        if (config.profile.userProfile != null) {
            annotationType = config.profile.userProfile.type;
        } else {
            annotationType = config.profile.def;
        }

	    // fetch all DDI annotations for current user
	    var url = "http://" + config.store.host +":" + config.store.port + "/search?email=" + req.user.email + "&annotationType=" + annotationType;

		res.render('main.ejs', {
		    user : req.user,
		    annotations : [],
		    exportMessage : req.flash('exportMessage'),
		    loadMessage : req.flash('loadMessage'),
		    host : config.annotator.host,
		});

	    // request({url: url, json: true}, function(error,response,body){
	    //     if (!error && response.statusCode === 200) {

		//         res.render('main.ejs', {
		//             user : req.user,
		//             annotations : body,
		//             exportMessage : req.flash('exportMessage'),
		//             loadMessage : req.flash('loadMessage'),
		//             host : config.annotator.host,
		//         });

	    //     } else {
		//         res.render('main.ejs', {
		//             user : req.user,
		//             annotations : {'total':0},
		//             exportMessage: req.flash('exportMessage'),
		//             loadMessage: req.flash('loadMessage'),
		//             host: config.annotator.host,
		//         });
	    //     }
	    // });
    });

    // LOGOUT ==============================
    app.get('/dbmiannotator/logout', function(req, res) {
        config.profile.pluginSetL = [];
        config.profile.userProfile = {};
        req.logout();
        res.redirect('/dbmiannotator');
    });

    // DISPLAY ==============================
    app.get('/dbmiannotator/displayWebPage', isLoggedIn, praseWebContents, function(req, res) {

	    var sourceUrl = req.query.sourceURL.trim();
	    var email = req.query.email;
	    var validUrl = require('valid-url');

	    if (validUrl.isUri(sourceUrl)){

		    // if (sourceUrl.match(/\.pdf/g)){ // local pdf resouces
		    //     res.redirect("/dbmiannotator/viewer.html?file=" + sourceUrl+"&email=" + email);
		    // }

		    if (sourceUrl.match(/localhost.*html/g)) {
                res.render('displayWebPage.ejs', {
			        htmlsource: req.htmlsource,
			        pluginSetL: config.profile.pluginSetL,
			        userProfile: config.profile.userProfile
                });
	        }
		    else {
		        req.flash('loadMessage', 'The url you just entered is not valid!');
		        res.redirect('/dbmiannotator/main');
		    }

	    }
    });

    // PLUGIN PROFILE ==============================
    app.post('/dbmiannotator/savePluginProfile', function(req, res) {
        console.log(req.body.pluginset);
        console.log(req.user.email);

        pg.connect(config.postgres, function(err, client, done) {

            if(err) {
                done();
                console.log(err);
                return res.status(500).json({ success: false, data: err});
            }

            if (config.profile.userProfile == null){  // no user profile, then insert
                console.log("[ERROR] user profile not avaliable!");
	            res.redirect('/dbmiannotator/main');

            } else {   // get user profile
                resultsL = []
                var queryUserProfile = client.query('SELECT u.uid, up.set_id FROM "user" u, user_profile up where u.uid = up.uid and u.email = $1 and up.status = $2', [req.user.email, true]);
                queryUserProfile.on('row', function(row) {
                    resultsL.push(row);
                });

                queryUserProfile.on('end', function() { // user profile changed, then update
                    if (resultsL[0].set_id != req.body.pluginset){
                        console.log("update user plugin profile");
                        client.query('UPDATE "user_profile" SET set_id = $1, created = now() FROM (SELECT * FROM "user" u where u.email = $2) AS u, "user_profile" up WHERE up.uid = u.uid AND up.status = true', [req.body.pluginset, req.user.email]);
                        done();
	                res.redirect('/dbmiannotator/main');
                    }
                    else {
                        console.log("user profile not need to update");
                        done();
	                res.redirect('/dbmiannotator/main');
                    }
                }, function(){
                    res.redirect('/dbmiannotator/main');
                });
            }

        });
    });

    // EXPORT TO JSON ==============================
    app.get('/dbmiannotator/exportjson', isLoggedIn, function(req, res){

	    var url = "http://" + config.store.host + ":" + config.store.port + "/search?email=" + req.query.email + "&annotationType=" + config.profile.def;

	    request({url: url, json: true}, function(error,response,body){
	        if (!error && response.statusCode === 200) {

                var annsJsonRes = JSON.stringify(body.rows);
                res.attachment('annotations-'+req.query.email+'.json');
		        res.setHeader('Content-Type', 'application/json');
		        res.end(annsJsonRes);
	        } else {
		        res.redirect('/dbmiannotator/main');
	        }
	    });
    });

    // EXPORT TO CSV ==============================
    app.get('/dbmiannotator/exportcsv', isLoggedIn, function(req, res){

	    var url = "http://" + config.store.host + ":" + config.store.port + "/search?email=" + req.query.email + "&annotationType=" + config.profile.def;

	    request({url: url, json: true}, function(error,response,body){
	        if (!error && response.statusCode === 200) {

                var jsonObjs = body.rows;

                res.attachment('annotations-'+req.query.email+'.csv');
		        res.setHeader('Content-Type', 'text/csv');
                var csvTxt = '"document"\t"claim label"\t"claim text"\t"method"\t"relationship"\t"drug1"\t"drug2"\t"precipitant"\t"enzyme"\t"evRelationship"\t"participants"\t"participants text"\t"drug1 dose"\t"drug1 formulation"\t"drug1 duration"\t"drug1 regimens"\t"drug1 dose text"\t"drug2 dose"\t"drug2 formulation"\t"drug2 duration"\t"drug2 regimens"\t"drug2 dose text"\t"auc"\t"auc type"\t"auc direction"\t"auc text"\t"cmax"\t"cmax type"\t"cmax direction"\t"cmax text"\t"cl"\t"cl type"\t"cl direction"\t"cl text"\t"halflife"\t"halflife type"\t"halflife direction"\t"halflife text"\t"group randomization"\t"parallel group design"\t"id"\n';

                for (var i = 0; i < jsonObjs.length; i++) {
                    jsonObj = jsonObjs[i];
                    claim = jsonObj.argues;
                    dataL = claim.supportsBy;

                    var claimRow = '"' + jsonObj.rawurl + '"\t"' + claim.label + '"\t"' + claim.hasTarget.hasSelector.exact + '"\t"' + claim.method + '"\t"' + claim.qualifiedBy.relationship + '"\t"' + claim.qualifiedBy.drug1 + '"\t"' + claim.qualifiedBy.drug2 + '"\t"' + (claim.qualifiedBy.precipitant || '') + '"\t"' + (claim.qualifiedBy.enzyme || '' ) + '"';

                    for (var j = 0; j < dataL.length; j++) {
                        var data = dataL[j];
                        var method = data.supportsBy;
                        var material = method.supportsBy;
                        var dataRow = "";

                        dataRow += '\t"' + (data.evRelationship || '') + '"';

                        if (material.participants != null)
                            dataRow += '\t"' + (material.participants.value || '') + '"\t"' + (getSpanFromField(material.participants) || '') + '"';
                        else
                            dataRow += '\t\t';

                        if (material.drug1Dose != null)
                            dataRow += '\t"' + (material.drug1Dose.value || '') + '"\t"' + (material.drug1Dose.formulation || '') + '"\t"'  + (material.drug1Dose.duration || '') + '"\t"' + (material.drug1Dose.regimens || '') + '"\t"' + (getSpanFromField(material.drug1Dose) || '') + '"';
                        else
                            dataRow += '\t\t\t\t';

                        if (material.drug2Dose != null)
                            dataRow += '\t"' + (material.drug2Dose.value || '') + '"\t"' + (material.drug2Dose.formulation || '') + '"\t"'  + (material.drug2Dose.duration || '') + '"\t"' + (material.drug2Dose.regimens || '') + '"\t"' + (getSpanFromField(material.drug2Dose) || '') + '"';
                        else
                            dataRow += '\t\t\t\t';

                        dataFieldsL = ["auc","cmax","clearance","halflife"];
                        for (p = 0; p < dataFieldsL.length; p++) {
                            field = dataFieldsL[p];
                            if (data[field] != null)
                                dataRow += '\t"' + (data[field].value || '') + '"\t"' + (data[field].type || '') + '"\t"' + (data[field].direction || '') + '"\t"' + (getSpanFromField(data[field]) || '') + '"';
                            else
                                dataRow += '\t\t\t\t';
                        }

                        if (data.grouprandom != null)
                            dataRow += '\t"' + (data.grouprandom || '') + '"';
                        else
                            dataRow += '\t';

                        if (data.parallelgroup != null)
                            dataRow += '\t"' + (data.parallelgroup || '') + '"';
                        else
                            dataRow += '\t';

                        dataRow += '\t"' + jsonObj.id + '"'
                        dataRow = claimRow + dataRow + '\n';
                        csvTxt += dataRow;
                    }
                }

		        res.attachment('annotations-'+req.query.email+'.csv');
		        res.setHeader('Content-Type', 'text/csv');
		        res.end(csvTxt);

	        } else {
		        //req.flash('exportMessage', 'exported failed, annotation fetch exception, please see logs or contact Yifan at yin2@pitt.edu!');
		        res.redirect('/dbmiannotator/main');
	        }
	    });
    });
};

// UTIL FUNCTIONS ==============================
function getSpanFromField(field) {
    if (field.hasTarget !=null) {
        if (field.hasTarget.hasSelector !=null)
            return field.hasTarget.hasSelector.exact;
    } else {
        return "";
    }
}

// MIDDLE WARE FUNCTIONS ==============================

// parse web contents from url
function praseWebContents(req, res, next){
    var sourceUrl = req.query.sourceURL.trim();

    if(sourceUrl.match(/localhost.*html/g)){
        var options = {
            host: sourceUrl,
            method: 'POST'
        }

        request(sourceUrl, function(err, res, body){

            // skip tidy beacuse changing of char encoding
            labelDecode = body.replace(/&/g,'&').replace(/ /g,' ');
            req.htmlsource = labelDecode;
            next();

            // normalize html source
            // tidy(labelDecode, htmltidyOptions['Kastor tidy - XHTML Clean page UTF-8'], function(err, html) {
            //     if (err){
            //         console.log(err);
            //     }
            //     req.htmlsource = html;
            //     next();
            // });

        });

    } else {
        next();
    }
}

// get plugin profile
function initPluginProfile(req, res, next){
    var pluginSetL = [];
    var userProfileL = [];

    var data = {text: req.body.text, complete: false};

    pg.connect(config.postgres, function(err, client, done) {

        if(err) {
            done();
            console.log(err);
            return res.status(500).json({ success: false, data: err});
        }
        // get all available plugin sets
        var queryPlugins = client.query("SELECT ps.id, ps.name, ps.type, ps.description FROM plugin_set ps WHERE ps.status = True ORDER BY ps.id ASC;");

        queryPlugins.on('row', function(row) {
            pluginSetL.push(row);
        });

        queryPlugins.on('end', function() {
            config.profile.pluginSetL = pluginSetL;
        });
        // get plugin set from user setting
        var queryUserProfile = client.query('SELECT u.uid, up.set_id, ps.name, ps.type FROM "user" u, "user_profile" up, "plugin_set" ps where u.uid = up.uid and up.set_id = ps.id and u.email = $1 and up.status = True', [req.user.email]);

        queryUserProfile.on('row', function(row) {
            userProfileL.push(row);
        });
        queryUserProfile.on('end', function() {
            if (userProfileL.length > 0){
                config.profile.userProfile = userProfileL[0];
                console.log("init pluginProfile - get user profile");
                console.log(config.profile.userProfile)
            }
            next();
            client.end();
        });

    });
}

// route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/dbmiannotator');
}

// validate inputs in register form
function isRegisterFormValid(req, res, next){

    req.assert('email', 'Email is not valid').isEmail();
    req.assert('username', 'Username must be at least 4 characters long').len(4);
    req.assert('password', 'Password must be at least 6 characters long').len(6);
    req.assert('repassword', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if (errors) {

	res.render('register', {
	    title: 'Register Form Validation',
	    message: '',
	    errors: errors
        });

    } else {
	return next();
    }

}

<|endoftext|>


<commit_before>_.extend(this, {
	value: null,

	construct: function(config) {
		$.textarea.applyProperties(_.omit(config, 'id', '__parentSymbol', '__itemTemplate', '$model'));

		$.value = '';

		if (OS_IOS)
			$.label.applyProperties({
				text: config.hintText,
				font: config.font
			});
	},

	setValue: function(value) {
		$.textarea.value = value;
		$.value = value;

		if($.textarea.value.length)
			$.label.hide();
	},

	focus: function() {
		$.textarea.focus();
	},

	blur: function() {
		$.textarea.blur();
	},

	addEventListener: function(type, callback) {
		$.on(type, callback);
	},

	removeEventListener: function(type, callback) {
		$.off(type, callback);
	},

	destruct: function() {
		$.off();
	}
});

function onFocus(evt) {
	if (OS_IOS) {
		$.label.hide();
	}

	$.trigger(evt.type, evt);
}

function onBlur(evt) {
	if (OS_IOS) {
		if (!this.hasText())
			$.label.show();
	}

	$.trigger(evt.type, evt);
}

function onChange(evt) {
	$.value = this.value;
}
<commit_msg>Added applyProperties<commit_after>_.extend(this, {
	value: null,

	construct: function(config) {
		$.textarea.applyProperties(_.omit(config, 'id', '__parentSymbol', '__itemTemplate', '$model'));

		$.value = '';

		if (OS_IOS)
			$.label.applyProperties({
				text: config.hintText,
				font: config.font
			});
	},

	setValue: function(value) {
		$.textarea.value = value;
		$.value = value;

		if($.textarea.value.length)
			$.label.hide();
	},

	focus: function() {
		$.textarea.focus();
	},

	blur: function() {
		$.textarea.blur();
	},

	addEventListener: function(type, callback) {
		$.on(type, callback);
	},

	removeEventListener: function(type, callback) {
		$.off(type, callback);
	},

	applyProperties: function(config) {
		$.textarea.applyProperties(config);
	},

	destruct: function() {
		$.off();
	}
});

function onFocus(evt) {
	if (OS_IOS) {
		$.label.hide();
	}

	$.trigger(evt.type, evt);
}

function onBlur(evt) {
	if (OS_IOS) {
		if (!this.hasText())
			$.label.show();
	}

	$.trigger(evt.type, evt);
}

function onChange(evt) {
	$.value = this.value;
}
<|endoftext|>


<commit_before>'use strict';

var MEDIA_URL = '/staticuploads/';

/**
 * Handle login with facebook button.
 */
$('.loginBtn--facebook').click(function(){
  event.preventDefault();

  // Check if the "share" button was clicked.
  if($(this).hasClass('fb-share')) {
    shareThisPost();
  } else {
    checkLoginState();
  }
});

/**
 * Share a post to facebook.
 */
function shareThisPost(){
  // var href = $(location).attr('href');
  // console.log(href);
  // var name = href.split("/")[4];
  // var description = $('#description').text();
  // var caption = $('#description').text();
  // var baseHref = href.split("/")[0] + '//' + href.split("/")[2];
  // var image = baseHref + $('#FB-image-game').attr('src');
  // console.log(image);

  FB.ui({
    method: 'share',
    href: 'https://developers.facebook.com/docs/',
    display: 'popup',
  }, function(response){});

  // FB.ui({
  //   // method: 'share',
  //   // name: 'Something',
  //   // picture: image,
  //   // href: url.toString(),
  //   hashtag: '#WhatsBuzz'
  //   // link: url,
  //   // description: captionText,
  //   // caption: 'http://www.whatsbuzz.co.il'
  //
  // }, function(response){
  //   if (response && response.post_id) {
  //     console.log('share success');
  //   } else {
  //     console.log('share error');
  //   }
  // });
}

/**
 * Handle the quizzes button, when displayed.
 */
$('#quizzes-game').click(function(){
  $('#facebooklogin').hide();
  showSpinner();

  // Show the quiz and hide the play button
  setTimeout(function(){
    $('#quizzes').show();
  }, 5250);
});

/**
 * Handle "show more" button in the nav pages.
 * Get posts, by type, from server and display them on the page.
 */
$('#show-more-in-page').click(function(event){
  event.preventDefault();
  var type = $('.show-more').data('posts-type');
  var start = $('.posts').length;
  $.get("/get-more-posts/" + type + "/" + start, function(data){
    // Convert the data to array of js objects.
    var data = JSON.parse(data[0].posts);

    // Create a post for each of them.
    data.forEach(function(postObject){
      // The title.
      var postTitle = $('<h2>').text(postObject.fields.title);
      // The image banner.
      var postImage = $('<img>').addClass('banner-image').attr('src', MEDIA_URL + postObject.fields.image_banner).attr('alt', postObject.fields.image_banner);
      // The button link.
      var postSlog = $('<a>').attr('href', "/posts/" + postObject.fields.slug).append($('<div>').addClass('row link').append($('<p>').text("התחל משחק")));

      // The whole post card.
      var postObj = $('<div>').addClass('col-sm-6 posts').append($('<div>').addClass('post').append(postTitle).append(postImage).append(postSlog));

      $('#main-posts').append(postObj);
    });
  });
});<commit_msg>fb share.<commit_after>'use strict';

var MEDIA_URL = '/staticuploads/';

/**
 * Handle login with facebook button.
 */
$('.loginBtn--facebook').click(function(){
  event.preventDefault();

  // Check if the "share" button was clicked.
  if($(this).hasClass('fb-share')) {
    shareThisPost();
  } else {
    checkLoginState();
  }
});

/**
 * Share a post to facebook.
 */
function shareThisPost(){
  var href = $(location).attr('href');
  var name = href.split("/")[4];
  var description = $('#description').text();
  var baseHref = href.split("/")[0] + '//' + href.split("/")[2];
  var image = baseHref + $('#FB-image-game').attr('src');

  FB.ui({
    method: 'share',
    name: 'Something',
    picture: image,
    href: 'href',
    hashtag: '#hashtag',
    link: url,
    description: description,
    caption: 'http://www.whatsbuzz.co.il',
    display: 'popup',
  }, function(response){
    if (response && response.post_id) {
      console.log('share success');
    } else {
      console.log('share error');
    }
  });
}

/**
 * Handle the quizzes button, when displayed.
 */
$('#quizzes-game').click(function(){
  $('#facebooklogin').hide();
  showSpinner();

  // Show the quiz and hide the play button
  setTimeout(function(){
    $('#quizzes').show();
  }, 5250);
});

/**
 * Handle "show more" button in the nav pages.
 * Get posts, by type, from server and display them on the page.
 */
$('#show-more-in-page').click(function(event){
  event.preventDefault();
  var type = $('.show-more').data('posts-type');
  var start = $('.posts').length;
  $.get("/get-more-posts/" + type + "/" + start, function(data){
    // Convert the data to array of js objects.
    var data = JSON.parse(data[0].posts);

    // Create a post for each of them.
    data.forEach(function(postObject){
      // The title.
      var postTitle = $('<h2>').text(postObject.fields.title);
      // The image banner.
      var postImage = $('<img>').addClass('banner-image').attr('src', MEDIA_URL + postObject.fields.image_banner).attr('alt', postObject.fields.image_banner);
      // The button link.
      var postSlog = $('<a>').attr('href', "/posts/" + postObject.fields.slug).append($('<div>').addClass('row link').append($('<p>').text("התחל משחק")));

      // The whole post card.
      var postObj = $('<div>').addClass('col-sm-6 posts').append($('<div>').addClass('post').append(postTitle).append(postImage).append(postSlog));

      $('#main-posts').append(postObj);
    });
  });
});<|endoftext|>