text:
'use strict';

var request = require('superagent'),
	step = require('step'),
	util = require('util'),
	cypher = require('./utils/cypher'),
	Validator = require('./utils/validator'),
	parser = require('./utils/parser');

module.exports = Neo4j;

function Neo4j(url, token){
	if(typeof url !== 'undefined' && url !== ''){
		this.url = url.slice(-1) !== '/' ? url : url.slice(0, -1); // remove trailing forward slash if present
	} else {
		this.url = 'http://localhost:7474';
	}

	if(token){
		this.header = {'Authorization': 'Basic realm="Neo4j" ' + token};
	} else {
		this.header = {};
	}
}

/*	Insert a Node
	Returns the node that is inserted and his node id (property: _id)
	Examples:
	Insert a Node with no label:
		insertNode({ name: 'Kristof' }, callback);
	Insert a Node with one label:
		insertNode({ name: 'Kristof' }, ['Student'], callback);
		insertNode({ name: 'Kristof' }, 'Student', callback);
		returns { _id: 14, name: 'Kristof' }
	Insert a Node with three labels:
		insertNode({ name:'Darth Vader', level: 99, hobbies: ['lightsaber fighting', 'cycling in space'], shipIds: [123, 321] }, ['User', 'Evil' ,'Man'], callback);
		returns { _id: 17, name:'Darth Vader', level: 99, hobbies: ['lightsaber fighting', 'cycling in space'], shipIds: [123, 321] }	*/

Neo4j.prototype.insertNode = function(node, labels, callback){
	var that = this;
	// Insert node without a label with post request
	if(typeof callback === 'undefined') {
		callback = labels;
		request
			.post(this.url + '/db/data/node')
			.set(this.header)
			.send(node)
			.end(function(result){
				if(result.body && result.body.data) {
					that.addNodeId(result.body, callback);
				} else {
					callback(new Error('Response body is empty'), null);
				}
			});
	} else {
		var val = new Validator();

		if(val.labels(labels).hasErrors) {
			return callback(val.error(), null);
		}

		// Flexibility: make array of single string
		if(typeof labels === 'string') {
			labels = [labels];
		}

		// Insert node and label(s) with cypher query
		if(labels instanceof Array){
			var query = 'CREATE (data'+  cypher.labels(labels) + ' {params}) RETURN data';
			this.cypherQuery(query, { params: node }, function(err, res) {
				if(err) {
					callback(err, null);
				}	else {
					callback(err, res.data[0]);
				}
			});
		} else {
			callback(new Error('The second parameter "labels" should be an array with strings OR "labels" should be a callback function.'), null);
		}
	}
};

/*	Get an array of labels of a Node
	Example:
	Get all labels of node 77:
		readLabels(77, callback);
		returns ['User','Student','Man']
*/

Neo4j.prototype.readLabels = function(node_id, callback){
	request
		.get(this.url + '/db/data/node/' + node_id + '/labels')
		.set(this.header)
		.end(function(result){
			if(result.body) {
				callback(null, result.body);
			} else {
				callback(new Error('Response is empty'), null);
			}
		});
};

/* Delete a Node --------- */
// Nodes with Relationships cannot be deleted -> deliver proper error message

Neo4j.prototype.deleteNode = function(node_id, callback){
	request
		.del(this.url + '/db/data/node/' + node_id)
		.set(this.header)
		.end(function(result){
			switch(result.statusCode){
				case 204:
					callback(null, true); // Node was deleted.
					break;
				case 404:
					callback(null, false); // Node doesn't exist.
					break;
				case 409:
					callback(null, false); // Node has Relationships and cannot be deleted.
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' occurred while deleting a node.'), null);
			}
		});
};

// Delete all nodes with `labels` and `properties`.
// * `labels`          String|Array[String]    e.g.: '', [], 'User', ['User', 'Student']
// * 'properties'      Object                  e.g.: { userid: '124' }
// Returns the number of deleted nodes.

// Examples:
//   deleteNodesWithLabelsAndProperties('User',{ firstname: 'Sam', male: true }, callback);
//   deleteNodesWithLabelsAndProperties(['User','Admin'], { 'name': 'Sam'}, callback);

Neo4j.prototype.deleteNodesWithLabelsAndProperties = function (labels, properties, callback){
  var where = cypher.where('data', properties);
  var query = 'MATCH (data'+  cypher.labels(labels) + ')';

  if (where !== '') {
    query += ' WHERE ' + where;
  }

  query += ' DELETE data RETURN count(data)';

  this.cypherQuery(query, properties, function (err, res) {
		if (err) {
			callback(err);
		} else {
			callback(null, res.data[0]);
		}
  });
};

/*  Read a Node ---------- */

Neo4j.prototype.readNode = function(node_id, callback) {
	var that = this;
	request
		.get(this.url + '/db/data/node/' + node_id)
		.set(this.header)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					that.addNodeId(result.body, callback); // Node found.
					break;
				case 404:
					callback(null, false); // Node doesn't exist.
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' occurred while reading a node.'), null);
			}
		});
};

/*	Replace a Node's properties
    This will replace all existing properties on the node with the new set of attributes. */

var replaceNodeById = function(node_id, node_data, callback) {
  var that = this;
  request
    .put(that.url + '/db/data/node/' + node_id + '/properties')
	.set(this.header)
    .send(that.stringifyValueObjects(that.replaceNullWithString(node_data)))
		.end(function(result) {
      switch(result.statusCode) {
        case 204:
          callback(null, true);
          break;
        case 404:
          callback(null, false);
          break;
        default:
          callback(new Error('HTTP Error ' + result.statusCode + ' when updating a Node.'), null);
      }
    });
};
// Create an alias
Neo4j.prototype.replaceNodeById = replaceNodeById;
Neo4j.prototype.updateNode = replaceNodeById;

/*  Update a Node properties
    This will update all existing properties on the node with the new set of attributes. */

Neo4j.prototype.updateNodeById = function(node_id, node_data, callback) {
  var query = 'START data=node({_id}) SET ' + cypher.set('data', node_data) + ' RETURN data';
  node_data._id = node_id;
  this.cypherQuery(query , node_data, function(err, res) {
		if (err) {
			callback(err);
		} else {
			callback(null, res.data[0]);
		}
  });
};

// Update all nodes with `labels` and `oldProperties`, set the `newProperties` and remove `removeProperties`.
// Return nothing if `returnUpdatedNodes` is `false`. Default will return all updated nodes.

// * `labels`              String|Array[String]    e.g.: '' or [] or 'User' or ['User', 'Student']
// * 'oldProperties'       Object                  e.g.: { userid: '124' }
// * `newProperties`       Object                  e.g.: { email: 'fred@example.com' }
// * `removeProperties`    Object                  e.g.: ['old_email', 'old_address'] (Optional)
// * `returnUpdatedNodes`  Boolean                 e.g.: `false` (Optional, default: `true`)

Neo4j.prototype.updateNodesWithLabelsAndProperties = function (labels, oldProperties, newProperties, removeProperties, returnUpdatedNodes, callback) {
  var whereSetProperties = cypher.whereSetProperties('data', oldProperties, newProperties);
  var where = whereSetProperties.where;
  var query = 'MATCH (data'+  cypher.labels(labels) + ')';
  var remove;

  if (typeof removeProperties === 'function') {
    callback = removeProperties;
    returnUpdatedNodes = true;
  } else {
    remove = cypher.remove('data', removeProperties);
    if (typeof returnUpdatedNodes === 'function') {
      callback = returnUpdatedNodes;
      returnUpdatedNodes = true;
    }
  }

  if (where !== '') {
    query += ' WHERE ' + where;
  }

  query += ' SET ' + whereSetProperties.set;

  if (remove && remove !== '') {
    query += ' REMOVE ' + remove;
  }

  if (returnUpdatedNodes) {
    query += ' RETURN data';
  }

  this.cypherQuery(query , whereSetProperties.properties, function(err, res) {
		if (err) {
			callback(err);
		} else {
			callback(null, res.data);
		}
  });
};

/* Insert a Relationship ------ */

Neo4j.prototype.insertRelationship = function(root_node_id, other_node_id, relationship_type, relationship_data, callback) {
	var that = this;
	request
		.post(that.url + '/db/data/node/' + root_node_id + '/relationships')
		.set(this.header)
		.send({
			to: that.url + '/db/data/node/' + other_node_id,
			type: relationship_type,
			data: that.stringifyValueObjects(that.replaceNullWithString(relationship_data))
		})
		.end(function(result) {
			switch(result.statusCode) {
				case 201:
					that.addRelationshipId(result.body, callback);
					break;
				case 400: // Endnode not found exception
					callback(null, false);
					break;
				case 404: // Startnode not found exception
					callback(null, false);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when inserting a Relationship.'), null);
			}
		});
};

/* Delete a Relationship --------- */

Neo4j.prototype.deleteRelationship = function(relationship_id, callback) {
	var that = this;
	request
		.del(that.url + '/db/data/relationship/' + relationship_id)
		.set(this.header)
		.end(function(result) {
			switch(result.statusCode) {
				case 204:
					callback(null, true);
					break;
				case 404: // Relationship with that id doesn't exist.
					callback(null, false);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when deleting a Relationship.'), null);
			}
		});
};

/* Read a Relationship ----------- */

Neo4j.prototype.readRelationship = function(relationship_id, callback) {
	var that = this;

	request
		.get(that.url + '/db/data/relationship/' + relationship_id)
		.set(this.header)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					that.addRelationshipId(result.body, callback);
					break;
				case 404:
					callback(null, false);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when reading a Relationship'), null);
			}
		});
};

/* Update a Relationship -------- */

Neo4j.prototype.updateRelationship = function(relationship_id, relationship_data, callback) {
	var that = this;

	request
		.put(that.url + '/db/data/relationship/' + relationship_id + '/properties')
		.set(this.header)
		.send(that.stringifyValueObjects(that.replaceNullWithString(relationship_data)))
		.end(function(result) {
			switch(result.statusCode) {
				case 204:
					callback(null, true);
					break;
				case 404:
					callback(null, false);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when updating a Relationship.'), null);
			}
		});
};

/* Create an Index ---------- */

Neo4j.prototype.insertIndex = function(index, callback) {
	var that = this;

	request
		.post(that.url + '/db/data/index/' + index.type + '/')
		.set(this.header)
		.send({
			'name': index.index,
			'config': index.config
		})
		.end(function(result) {
			switch(result.statusCode) {
				case 201:
					callback(null, result.body);
					break;
				case 404:
					callback(null, false);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when inserting an Index.'), null);
			}
		});
};

/*	Create an index on a property of a label
	Example:
	Create an index on the first name of a person.
		insertLabelIndex('Person', 'firstname', callback);
		returns {
				  'label' : 'Person',
				  'property-keys' : [ 'firstname' ]
				}
	Note:
	Compound indexes are not yet supported, only one property per index is allowed.
	So ['firstname', 'lastname'] is not supported yet. */

Neo4j.prototype.insertLabelIndex = function(label, property_key, callback) {
	request
			.post(this.url + '/db/data/schema/index/' + label)
			.set(this.header)
			.send({ 'property_keys' : [property_key] })
			.end(function(result){
				if(result.body) {
					callback(null, result.body);
				} else {
					callback(new Error('Response is empty'), null);
				}
	});
};

Neo4j.prototype.insertNodeIndex = function(index, callback) {
	var _index = index;
	if(typeof index === 'string') {
		_index = {
			type: 'node',
			index: index
		};
	}
	this.insertIndex(_index, callback);
};

Neo4j.prototype.insertRelationshipIndex = function(index, callback) {
	var _index = index;
	if(typeof index === 'string') {
		_index = {
			type: 'relationship',
			index: index
		};
	}
	this.insertIndex(_index, callback);
};

/* Delete an Index ---------- */

Neo4j.prototype.deleteIndex = function(index, callback) {
	request
		.del(this.url + '/db/data/index/' + index.type + '/' + index.index)
		.set(this.header)
		.end(function(result) {
			switch(result.statusCode) {
				case 204:
					callback(null, true); // Index was deleted.
					break;
				case 404:
					callback(null, false); // Index doesn't exist.
					break;
				default:
					callback(new Error('Unknown Error while deleting Index'), null);
			}
	});
};

Neo4j.prototype.deleteNodeIndex = function(index, callback) {
	this.deleteIndex({type: 'node', index: index}, callback);
};

Neo4j.prototype.deleteRelationshipIndex = function(index, callback) {
	this.deleteIndex({type: 'relationship', index: index}, callback);
};

Neo4j.prototype.deleteLabelIndex = function(label, property_key, callback) {
	request
	.del(this.url + '/db/data/schema/index/' + label + '/' + property_key)
	.set(this.header)
	.end(function(result) {
		switch(result.statusCode) {
			case 204:
				callback(null, true); // Index was deleted.
				break;
			case 404:
				callback(null, false); // Index doesn't exist.
				break;
			default:
				callback(new Error('Unknown Error while deleting Index'), null);
		}
	});
};

function listIndexes (url, callback, header) {
	request
	.get(url)
	.set(header)
	.end(function(result) {
		switch(result.statusCode) {
			case 200:
			case 204:
				callback(null, result.body);
				break;
			case 404:
				callback(null, false);
				break;
			default:
				callback(new Error('HTTP Error ' + result.statusCode + ' when listing all indexes.'), null);
		}
	});
}

Neo4j.prototype.listIndexes = function(indexType, callback) {
	var url = this.url + '/db/data/index/' + indexType;
	listIndexes(url, callback, this.header);
};

Neo4j.prototype.listNodeIndexes = function(callback) {
	var url = this.url + '/db/data/index/node';
	listIndexes(url, callback, this.header);
};

Neo4j.prototype.listRelationshipIndexes = function(callback) {
	var url = this.url + '/db/data/index/relationship';
	listIndexes(url, callback, this.header);
};

/*	List indexes for a label
	Example:
	listLabelIndexes('City', callback);
	returns [ { label: 'City', 'property-keys': [ 'postalcode' ] },
  			  { label: 'City', 'property-keys': [ 'name' ] } ]		*/

Neo4j.prototype.listLabelIndexes = function(label, callback) {
	var url = this.url + '/db/data/schema/index/' + label;
	listIndexes(url, callback, this.header);
};

/* Add item to Index ---------- */

Neo4j.prototype.addItemToIndex = function (args, callback) {
	var that = this;

	request
		.post(that.url + '/db/data/index/' + args.indexType + '/' + args.indexName)
		.set(this.header)
		.send({
			'uri': that.url + '/db/data/' + args.indexType + '/' + args.itemId,
			'key': args.indexKey,
			'value': args.indexValue
		})
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					that.addNodeId(result.body, callback);
					break;
				case 201:
					that.addNodeId(result.body, callback);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when adding an Item to an Index'), null);
			}
		});
};

Neo4j.prototype.addNodeToIndex = function(nodeId, indexName, indexKey, indexValue, callback) {
	this.addItemToIndex({
		indexType: 'node',
		itemId: nodeId,
		indexName: indexName,
		indexKey: indexKey,
		indexValue: indexValue
	}, callback);
};

Neo4j.prototype.addRelationshipToIndex = function(nodeId, indexName, indexKey, indexValue, callback) {
	this.addItemToIndex({
		indexType: 'relationship',
		itemId: nodeId,
		indexName: indexName,
		indexKey: indexKey,
		indexValue: indexValue
	}, callback);
};

/*	Adding one or multiple labels to a node.
	Given a node id (integer) and one label (string) or multiple labels (array of strings) (non-empty strings)
	returns true if successfully added a label otherwise it will return false.
	Examples:
	addLabelsToNode(77, 'User', callback);
	addLabelsToNode(77, ['User', 'Student'], callback);
		returns true
	addLabelsToNode(77, ['User', ''], callback);
		returns an error! no empty string allowed	*/

Neo4j.prototype.addLabelsToNode = function(nodeId, labels, callback) {
	var url = this.url + '/db/data/node/' + nodeId + '/labels';
	var errorMsg = '"Labels" should be a non-empty string or an array of non-empty strings.';

	if (typeof labels === 'string') {
		if (labels === '') {
			return callback(new Error(errorMsg), null);
		}
		labels = [labels];
	}

	if (labels instanceof Array) {
		request
			.post(url)
		    .set(this.header)
			.send(labels)
			.end(function(result) {
				switch(result.statusCode) {
					case 204:
						callback(null, true); // Labels added
						break;
					case 400:
						callback(new Error(errorMsg), null); // Empty label
						break;
					case 404:
						callback(null, false); // Node doesn't exist
						break;
					default:
						callback(new Error('HTTP Error ' + result.statusCode + ' when adding a label to a node.'), null);
				}
			});
	} else {
		callback(new Error(errorMsg), null);
	}
};

/*	Replacing labels on a node.
	This removes any labels currently on a node, and replaces them with the new labels.
	Given a node id (integer) and one label (string) or multiple labels (array of strings) (non-empty strings)
	returns true if successfully replaced all labels otherwise it will return false or an error.
	Examples:
	replaceLabelsFromNode(77, 'User', callback);
	replaceLabelsFromNode(77, ['User', 'Student'], callback);
		returns true
	replaceLabelsFromNode(77, ['User', ''], callback);
	replaceLabelsFromNode(77, null, callback);
		returns an error! no empty string allowed	*/

Neo4j.prototype.replaceLabelsFromNode = function(nodeId, labels, callback) {
	var errorMsg = '"Labels" should be a non-empty string or an array of non-empty strings.';

	if (typeof labels === 'string') {
		if(labels === '') {
			return callback(new Error(errorMsg), null);
		}
		labels = [labels];
	}

	if (labels instanceof Array) {
		request
			.put(this.url + '/db/data/node/' + nodeId + '/labels')
			.send(labels)
		    .set(this.header)
			.end(function(result) {
				switch(result.statusCode) {
					case 204:
						callback(null, true);
						break;
					case 400:
						callback(new Error(errorMsg), null); // Empty label
						break;
					case 404:
						callback(null, false);
						break;
					default:
						callback(new Error('HTTP Error ' + result.statusCode + ' when replacing labels.'), null);
			}
		});
	} else {
		callback(new Error(errorMsg), null);
	}
};

/*	Removing a label from a node
	Given a node id (positive integer) and one label (non-empty string)
	returns true if successfully removed the label otherwise it will return false (Node doesn't exist) or an error.
	Examples:
	deleteLabelFromNode(77, 'User', callback);
		returns true
	deleteLabelFromNode(77, ['Student'], callback);
	deleteLabelFromNode(77, '', callback);
		returns an error, label should be a non-empty string */

Neo4j.prototype.deleteLabelFromNode = function(nodeId, label, callback) {
	var val = new Validator();
	val.nodeId(nodeId).label(label);

	if (val.hasErrors) {
		return callback(val.error(), null);
	}

	request
		.del(this.url + '/db/data/node/' + nodeId + '/labels/'+ label)
		.set(this.header)
		.end(function(result) {
			switch(result.statusCode) {
				case 204:
					callback(null, true); // Label was deleted.
					break;
				case 404:
					callback(null, false); // Node doesn't exist.
					break;
				default:
					callback(new Error('Unknown Error while deleting Index'), null);
		}
	});
};

/*	Get all nodes with a label
	Given a label (non-empty string)
	returns an array of nodes with that label
	Examples:
	readNodesWithLabel('User', callback);
		returns an array with nodes with the label 'User'
	deleteLabelFromNode('DoesNotExist', callback);
		returns an empty array	 */

Neo4j.prototype.readNodesWithLabel = function(label, callback) {
	var that = this;
	var val = new Validator();

	if (val.label(label).hasErrors) {
		return callback(val.error(), null);
	}

	request
		.get(this.url + '/db/data/label/' + label + '/nodes')
		.set(this.header)
		.end(function(result) {
			var body = result.body;
			switch(result.statusCode) {
				case 200:
					if (body && body.length >= 1) {
						step(
							function addIds() {
								var group = this.group();
								body.forEach(function(node) {
									that.addNodeId(node, group());
								});
							},
							function sumUp(err, nodes) {
								if (err) {
									throw err;
								}
								callback(null, nodes);
							});
					} else {
						callback(null, body);
					}
					break;
				case 404:
					callback(null, false);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when reading a Relationship'), null);
			}
		});
};

/*	Get all nodes with labels and properties
	Given one label (non-empty string) or multiple labels (array of strings) and one or more properties in json
	returns an array of nodes with these labels and properties
	Examples:
	readNodesWithLabelsAndProperties('User',{ firstname: 'Sam', male: true }, callback);
		returns an array with nodes with the label 'User' and properties firstname='Sam' and male=true
	readNodesWithLabelsAndProperties(['User','Admin'], { 'name': 'DoesNotExist'}, callback);
		returns an empty array	 		*/

Neo4j.prototype.readNodesWithLabelsAndProperties = function(labels, properties, callback) {
	var that = this;
	var val = new Validator();
	val.labels(labels).properties(properties);

	if (val.hasErrors) {
		return callback(val.error(), null);
	}

	// Only one label and one property provided
	if (typeof labels === 'string' && Object.keys(properties).length === 1) {
		var props = cypher.jsonToURL(properties);
		request
			.get(this.url + '/db/data/label/' + labels + '/nodes?' + props)
			.set(this.header)
			.end(function(result) {
				var body = result.body;
				switch(result.statusCode) {
					case 200:
						if (body && body.length >= 1) {
							step(
								function addIds(){
									var group = this.group();
									body.forEach(function(node){
										that.addNodeId(node, group());
									});
								},
								function sumUp(err, nodes){
									if(err) {
										throw err;
									}
									callback(null, nodes);
								});
						} else {
							callback(null, body);
						}
						break;
					case 404:
						callback(null, false);
						break;
					default:
						callback(new Error('HTTP Error ' + result.statusCode + ' when reading Nodes.'), null);
				}
			});
		} else { // Multiple labels or properties provided
			var query = 'MATCH (data'+  cypher.labels(labels) + ') WHERE ' + cypher.where('data', properties) + ' RETURN data';
			this.cypherQuery(query, properties, function(err, res) {
				if (err) {
					callback(err, null);
				} else {
					callback(err, res.data);
				}
			});
		}
};

/*	List all labels.
	Example:
	listAllLabels(callback);
		returns [ 'User', 'Person', 'Male', 'Animal' ] */

Neo4j.prototype.listAllLabels = function(callback) {
	request
	.get(this.url + '/db/data/labels')
	.set(this.header)
	.end(function(result) {
		switch(result.statusCode) {
			case 200:
				callback(null, result.body);
				break;
			case 404:
				callback(null, false);
				break;
			default:
				callback(new Error('HTTP Error ' + result.statusCode + ' when listing all labels.'), null);
		}
	});
};

/* CONSTRAINTS */

/*	Create a uniqueness constraint on a property.
	Example:
		createUniquenessConstraint('User','email', callback);
		returns 	{
					  'label' : 'User',
					  'type' : 'UNIQUENESS',
					  'property-keys' : [ 'email' ]
					}			*/

var createUniquenessConstraint = function(label, property_key, callback) {
	var that = this;
	var val = new Validator();
	val.label(label).property(property_key);

	if (val.hasErrors) {
		return callback(val.error(), null);
	}

	request
		.post(that.url + '/db/data/schema/constraint/' + label + '/uniqueness')
		.set(this.header)
		.send({ 'property_keys' : [property_key] })
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					callback(null, result.body);
					break;
				case 409:
					callback(null, false); // Constraint already exists
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when creating a uniqueness contraint.'), null);
			}
		});
};
Neo4j.prototype.createUniquenessConstraint = createUniquenessConstraint;
Neo4j.prototype.createUniquenessContstraint = createUniquenessConstraint;

/*	Get a specific uniqueness constraint for a label and a property
	Example:
		readUniquenessConstraint('User','email', callback);
		returns [ {
				  'label' : 'User',
				  'property-keys' : [ 'email' ],
				  'type' : 'UNIQUENESS'
				} ]						 		*/

Neo4j.prototype.readUniquenessConstraint = function(label, property, callback) {
	var val = new Validator();
	val.label(label).property(property);

	if (val.hasErrors) {
		return callback();
	}

	request
		.get(this.url + '/db/data/schema/constraint/' + label + '/uniqueness/' + property)
		.set(this.header)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					callback(null, result.body);
					break;
				case 404:
					callback(null, false);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when reading uniqueness constraints'), null);
			}
	});
};

/*	Get all uniqueness constraints for a label.
	Example:
		listAllUniquenessConstraintsForLabel('User', callback);
		returns [ {
				  'label' : 'User',
				  'property-keys' : [ 'uid' ],
				  'type' : 'UNIQUENESS'
				}, {
				  'label' : 'User',
				  'property-keys' : [ 'email' ],
				  'type' : 'UNIQUENESS'
				} ]						 		*/

Neo4j.prototype.listAllUniquenessConstraintsForLabel = function(label, callback) {
	var val = new Validator();
	val.label(label);
	if (val.hasErrors) {
		return callback();
	}

	request
		.get(this.url + '/db/data/schema/constraint/' + label + '/uniqueness')
		.set(this.header)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					callback(null, result.body);
					break;
				case 404:
					callback(null, false);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when listing all uniqueness constraints.'), null);
			}
	});
};

/*	Get all constraints for a label.
	Example:
		listAllConstraintsForLabel('User', callback);
		returns [ {
				  'label' : 'User',
				  'property-keys' : [ 'uid' ],
				  'type' : 'UNIQUENESS'
				}, {
				  'label' : 'User',
				  'property-keys' : [ 'email' ],
				  'type' : 'UNIQUENESS'
				} ]						*/

Neo4j.prototype.listAllConstraintsForLabel = function(label, callback) {
	var val = new Validator();
	val.label(label);
	if (val.hasErrors) {
		return callback();
	}

	request
	.get(this.url + '/db/data/schema/constraint/' + label)
	.set(this.header)
	.end(function(result) {
		switch(result.statusCode) {
			case 200:
				callback(null, result.body);
				break;
			case 404:
				callback(null, false);
				break;
			default:
				callback(new Error('HTTP Error ' + result.statusCode + ' when listing all constraints.'), null);
		}
	});
};

/*	Get all constraints.
	Example:
		listAllConstraints(callback);
		returns [ {
				  'label' : 'Product',
				  'property-keys' : [ 'pid' ],
				  'type' : 'UNIQUENESS'
				}, {
				  'label' : 'User',
				  'property-keys' : [ 'email' ],
				  'type' : 'UNIQUENESS'
				} ]								*/

Neo4j.prototype.listAllConstraints = function(callback) {
	request
	.get(this.url + '/db/data/schema/constraint')
	.set(this.header)
	.end(function(result) {
		switch(result.statusCode) {
			case 200:
				callback(null, result.body);
				break;
			case 404:
				callback(null, false);
				break;
			default:
				callback(new Error('HTTP Error ' + result.statusCode + ' when listing all constraints.'), null);
		}
	});
};

/*	Drop uniqueness constraint for a label and a property.
	Returns true if constraint was successfully removed.
	Returns false if the constraint was not found.
	Example:
		dropContstraint('User','email', callback);
		returns true	*/

Neo4j.prototype.dropUniquenessContstraint = function(label, property_key, callback) {
	var val = new Validator();
	val.label(label).property(property_key);

	if(val.hasErrors) {
		return callback(val.error(), null);
	}

	request
		.del(this.url + '/db/data/schema/constraint/' + label + '/uniqueness/' + property_key)
		.set(this.header)
		.end(function(result) {
			switch(result.statusCode) {
				case 204:
					callback(null, true); // Constraint was deleted.
					break;
				case 404:
					callback(null, false); // Constraint doesn't exist.
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when removing a uniqueness contraint.'), null);
			}
		});
};

/* TRANSACTIONS */

/*	NOTE:
	Details 'statements' property in beginTransaction, addStatementsToTransaction,
	commitTransaction and beginAndCommitTransaction:

	Return results in graph format by adding	resultDataContents : [ 'row', 'graph' ]	to a statement.
	If you want to understand the graph structure of nodes and relationships returned by your query,
	you can specify the 'graph' results data format.
	For example, this is useful when you want to visualise the graph structure.
	The format collates all the nodes and relationships from all columns of the result,
	and also flattens collections of nodes and relationships, including paths.

	Note the resultDataContents property.

	Example of a 'statements' parameter:
	{
		statements:	[ { statement : 'CREATE ( bike:Bike { weight: 10 } )CREATE ( frontWheel:Wheel { spokes: 3 } )CREATE ( backWheel:Wheel { spokes: 32 } )CREATE p1 = bike -[:HAS { position: 1 } ]-> frontWheel CREATE p2 = bike -[:HAS { position: 2 } ]-> backWheel RETURN bike, p1, p2',
    					resultDataContents : [ 'row', 'graph' ]
					} ]
	}

/*	Begin a transaction
	You begin a new transaction by posting zero or more Cypher statements to the transaction endpoint.
	The server will respond with the result of your statements, as well as the location of your open transaction.
	In the 'transaction' section you will find the expire date of the transaction. It's a RFC1123 formatted timestamp.
	The transactionId will be added to the result.
	Check the above 'NOTE' for more details about the statements parameter.

	Examples:
	beginTransaction(callback);
	returns  {
				commit: 'http://localhost:7474/db/data/transaction/10/commit',
				results: [],
				transaction: { expires: 'Tue, 24 Sep 2013 19:43:31 +0000' },
				errors: [],
				_id: 10
			}

	beginTransaction({
					  statements : [ {
					    statement : 'CREATE (n {props}) RETURN n',
					    parameters : {
					      props : {
					        name : 'Adam',
					        age: 22
					      }
					    }
					  } ]
					}, calback);
	returns {
				commit: 'http://localhost:7474/db/data/transaction/18/commit',
			  	results: [ { columns: [ 'person' ], data: [ { row: [ { age: 22, name: 'Adam' } ] } ] } ],
			  	transaction: { expires: 'Sun, 22 Sep 2013 19:31:17 +0000' },
			  	errors: [],
			  	_id: 18
			}																								*/

Neo4j.prototype.beginTransaction = function(statements, callback) {
	var that = this;
	if (!statements || typeof statements === 'function') {
		callback = statements;
		statements = { statements : [] };
	}
	request
		.post(this.url + '/db/data/transaction')
		.set(this.header)
		.send(statements)
		.end(function(result) {
			switch(result.statusCode) {
				case 201:
					that.addTransactionId(result.body, callback);
					break;
				case 404:
					callback(null, false);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when beginning transaction.'), null);
			}
		});
};

/*	Execute statements in an open transaction
	Given that you have an open transaction, you can make a number of requests,
	each of which executes additional statements, and keeps the transaction open by resetting the transaction timeout.
	If the transaction in rolled back or it does not exist false will be returned (to callback)
	In the 'transaction' section you will find the expire date of the transaction. It's a RFC1123 formatted timestamp.
	The transactionId will be added to the result.
	Check the above 'NOTE' for more details about the statements parameter.

	Example:
		db.addStatementsToTransaction(7, {
											statements : [ {
												statement : 'CREATE (p:Person {props}) RETURN p',
													parameters : {
														props : {
															name : 'Adam',
															age: 23
														}
													}
												}]
										}, callback);
		returns {
					commit: 'http://localhost:7474/db/data/transaction/22/commit',
					results: [],
					transaction: { expires: 'Wed, 25 Sep 2013 13:45:17 +0000' },
					errors: [],
					transactionId: 22
				}																		*/

Neo4j.prototype.addStatementsToTransaction = function(transactionId, statements, callback) {
	var that = this;
	var val = new Validator();
	val.transaction(transactionId);

	if (val.hasErrors) {
		return callback(val.error(), null);
	}

	request
		.post(this.url + '/db/data/transaction/' + transactionId)
		.set(this.header)
		.send(statements)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					that.addTransactionId(result.body, function afterAddingTransactionId (err, res) {
						if (res.errors && res.errors.length > 0) {
							callback(new Error('An error occured when adding statements to the transaction. See "errors" inside the result for more details.'), res);
						} else {
							callback(null, res);
						}
					});
					break;
				case 404:
					callback(null, false); // Transaction doesn't exist.
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when adding statements to transaction.'), null);
			}
		});
};

/*	Reset transaction timeout of an open transaction
	Every orphaned transaction is automatically expired after a period of inactivity.
	This may be prevented by resetting the transaction timeout.
	This request will reset the transaction timeout and return the new time at which
	the transaction will expire as an RFC1123 formatted timestamp value in the "transaction" section of the response.
	If the transaction in rolled back or it does not exist false will be returned (to callback)
	The transactionId will be added to the result.

	Example:
		resetTimeoutTransaction(7, callback);
		returns {
					commit: 'http://localhost:7474/db/data/transaction/7/commit',
					results: [],
					transaction: { expires: 'Tue, 24 Sep 2013 18:13:43 +0000' },
					errors: [],
  					transactionId: 7
  				}																	*/

Neo4j.prototype.resetTimeoutTransaction = function(transactionId, callback) {
	var that = this;
	var val = new Validator();
	val.transaction(transactionId);

	if (val.hasErrors) {
		return callback(val.error(), null);
	}

	request
		.post(this.url + '/db/data/transaction/' + transactionId)
		.set(this.header)
		.send({ statements : [ ]})
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					that.addTransactionId(result.body, callback);
					break;
				case 404:
					callback(null, false); // Transaction doesn't exist.
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when resetting transaction timeout.'), null);
			}
		});
};

/*	Commit an open transaction
	Given you have an open transaction, you can send a commit request.
	Optionally, you submit additional statements along with the request that will
	be executed before committing the transaction.
	If the transaction in rolled back or it does not exist false will be returned (to callback)
	Check the above 'NOTE' for more details about the statements parameter.

	Example:
	commitTransaction(7, {
								statements : [ {
									statement : 'CREATE (p:Person {props}) RETURN p',
										parameters : {
											props : {
												name : 'Adam',
												age: 24,
												favoriteColors: ['Green', 'Vanilla White']
											}
										}
									}]
							});
	returns	{
				results: [ { columns: [ 'p' ],
				data: [ { row: [ {  name: 'Adam',
									age: 24,
									favoriteColors: [ 'Green', 'Vanilla White' ] } ] } ]
						} ],
				errors: []
			}					*/

Neo4j.prototype.commitTransaction = function(transactionId, statements, callback){
	var that = this;
	var val = new Validator();
	val.transaction(transactionId);

	if (val.hasErrors) {
		return callback(val.error(), null);
	}

	if (!statements || typeof statements === 'function') {
		callback = statements;
		statements = { statements : [] };
	}

	request
		.post(this.url + '/db/data/transaction/' + transactionId + '/commit')
		.set(this.header)
		.send(statements)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					callback(null, result.body);
					break;
				case 404:
					callback(null, false); // Transaction doesn't exist.
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when commiting transaction.'), null);
			}
		});
};

/*	Rollback an open transaction
	Given that you have an open transaction, you can send a roll back request.
	The server will roll back the transaction.
	If the transaction was already rolled back or it does not exist false will be returned (to callback)
	If the transaction has been rolled back true will be returned.

	Examples:
		rollbackTransaction(10, callback); // transaction 10 exists
		returns true
		rollbackTransaction(12345, callback); // transaction 12345 doesn't exist
		returns false																*/

Neo4j.prototype.rollbackTransaction = function(transactionId, callback) {
	var that = this;
	var val = new Validator();
	val.transaction(transactionId);

	if (val.hasErrors) {
		return callback(val.error(), null);
	}

	request
		.del(this.url + '/db/data/transaction/' + transactionId)
		.set(this.header)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					callback(null, true);
					break;
				case 404:
					callback(null, false); // Transaction doesn't exist.
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when rolling back transaction.'), null);
			}
		});
};

/*	Begin and commit a transaction in one request
	If there is no need to keep a transaction open across multiple HTTP requests, you can begin a transaction,
	execute statements, and commit with just a single HTTP request.
	If the transaction in rolled back or it does not exist false will be returned (to callback)
	Check the above 'NOTE' for more details about the statements parameter.

	Examples:
		beginAndCommitTransaction({
									statements : [ {
										statement : 'CREATE (p:Person {props}) RETURN p',
											parameters : {
												props : {
													name : 'Adam',
													age: 21.17,
													favoriteNumbers: [123, 456789],
													gender: true
												}
											}
										}]
								}, callback);
		returns {
					results: [ { columns: [ 'p' ],
					data: [ { row: [ {	gender: true,
										name: 'Adam',
										favoriteNumbers: [ 123, 456789 ],
										age: 21.17 } ] } ] } ],
					errors: []
				}

		beginAndCommitTransaction({
									statements : [ {
										statement : 'CREATE (p:Person {props}) RETURN p',
										parameters : {
											props : {
												name : 'Adam',
												age: 21.17,
												favoriteNumbers: [123, 456789],
												gender: true
											}
										},
										resultDataContents : [ 'row', 'graph' ]
									}]
								}, callback);

		returns {	results: [ { columns: [ 'p' ],
					data: [ { row: [ {	gender: true,
										name: 'Adam',
										favoriteNumbers: [ 123, 456789 ],
										age: 21.17 } ],
										graph:{ nodes: [ {	id: '382',
															labels: [ 'Person' ],
															properties: {	gender: true,
																			name: 'Adam',
																			favoriteNumbers: [ 123, 456789 ],
																			age: 21.17 } } ],
																			relationships: [] } } ] } ],
					errors: [] }																				*/

Neo4j.prototype.beginAndCommitTransaction = function(statements, callback) {
	request
		.post(this.url + '/db/data/transaction/commit')
		.set(this.header)
		.set('X-Stream', true)
		.send(statements)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					callback(null, result.body);
					break;
				case 404:
					callback(null, false); // Transaction doesn't exist.
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when beginning and commiting transaction.'), null);
			}
		});
};

/* ADVANCED FUNCTIONS ---------- */

/* Get all Relationship Types -------- */

Neo4j.prototype.readRelationshipTypes = function(callback) {
	var that = this;

	request
		.get(that.url + '/db/data/relationship/types')
		.set(this.header)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					callback(null, result.body);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when retrieving relationship types.'), null);
			}
		});
};

/* Get Relationships of a Node --------- */

var readRelationshipsOfNode = function(node_id, options, callback) {
	var that = this;

	if (typeof options === 'function') {
		callback = options;
	}

	var url = that.url + '/db/data/node/' + node_id + '/relationships/';

	// Set direction of relationships to retrieve.
	if (options.direction && (options.direction === 'in' || options.direction === 'out')) {
		url += options.direction;
	} else {
		url += 'all';
	}

	// Set types of relationships to retrieve.
	if (options.types && options.types.length >= 1) {
		url += '/' + encodeURIComponent(options.types.join('&'));
	}

	request
		.get(url)
		.set(this.header)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					that.addRelationshipIdForArray(result.body, callback);
					break;
				case 404:
					callback(null, false);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when retrieving relationships for node ' + node_id), null);
			}
		});
};
// Create aliases
Neo4j.prototype.readRelationshipsOfNode = readRelationshipsOfNode;
Neo4j.prototype.readAllRelationshipsOfNode = readRelationshipsOfNode;
Neo4j.prototype.readTypedRelationshipsOfNode = function(node_id, types, callback) {
	this.readRelationshipsOfNode(node_id, {types: types}, callback);
};
Neo4j.prototype.readIncomingRelationshipsOfNode = function(node_id, callback) {
	this.readRelationshipsOfNode(node_id, {direction: 'in'}, callback);
};
Neo4j.prototype.readOutgoingRelationshipsOfNode = function(node_id, callback) {
	this.readRelationshipsOfNode(node_id, {direction: 'out'}, callback);
};

/* Run Cypher Query -------- */

Neo4j.prototype.cypherQuery = function(query, params, include_stats, callback) {
	var that = this;
	var body = { query: query };
	if (params) {
		if (typeof params === 'function') {
			callback = params;
		} else {
			body['params'] = params;
		}
	}
	if (include_stats) {
		if (typeof include_stats === 'function') {
			callback = include_stats;
			include_stats = false;
		}
	}

	request
		.post(that.url + '/db/data/cypher' + (include_stats ? '?includeStats=true' : ''))
		.set(this.header)
		.set('Content-Type', 'application/json')
		.send(body)
    .on('error', callback)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					if (result.body && result.body.data.length >= 1) {
						var addIdsToColumnData = function(columnData, callback) {
							step(
								function addId() {
									var group = this.group();
									columnData.forEach(function(node) {
										that.addNodeId(node, group());
									});
								},
								function sumUp(err, nodes) {
									if (err) {
										throw err;
									} else {
										callback(null, nodes);
									}
								});
						};

						step(
							function eachColumn() {
								var group = this.group();
								result.body.data.forEach(function(columnResult) {
									addIdsToColumnData(columnResult, group());
								});
							},
							function sumUp(err, columns) {
								if (err) {
									throw err;
								} else {
									// flatten the array if only one variable is getting returned to make it more convenient.
									if (result.body.columns.length >= 2) {
										result.body.data = columns;
									} else {
										result.body.data = [].concat.apply([], columns);
									}
									callback(null, result.body);
								}
							});
					} else {
						callback(null, result.body);
					}
					break;
				case 404:
					callback(null, null);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when running the cypher query against neo4j.\n' + result.body.exception + ': ' + result.body.message), null);
			}
		});
};

/* Run Batch Queries -------- */

Neo4j.prototype.batchQuery = function(query, callback) {
	var that = this;

	request
		.post(that.url + '/db/data/batch')
		.set(this.header)
		.set('Content-Type', 'application/json')
		.send(query)
		.end(function(result) {
			switch(result.statusCode) {
				case 200:
					callback(null, result.body);
					break;
				case 404:
					callback(null, null);
					break;
				default:
					callback(new Error('HTTP Error ' + result.statusCode + ' when running the batch query against neo4j'), null);
			}
		});
};

/* HELPER METHODS --------- */

/* Extract node_id and add it as a property. */

Neo4j.prototype.addNodeId = function(node, callback) {
	if (node && node.self) {
		node.data._id = parseInt(node.self.match(/\/([0-9]+)$/)[1]);
		callback(null, node.data);
	} else {
		callback(null, node);
	}
};

/*	Extract the transaction id and adds it as an _id property. */

Neo4j.prototype.addTransactionId = function(node,  callback) {
	node._id = parseInt(node.commit.match(/\/transaction\/([0-9]+)\/commit$/)[1]);
	delete node.commit;
	callback(null, node);
};

/*	Extract start node id (_start), end node id (_end) and node id (_id) add it as a property. */

Neo4j.prototype.addRelationshipId = function(relationship, callback) {
	if (relationship.data) {
		relationship.data._start = parser.getNodeId(relationship.start);
		relationship.data._end = parser.getNodeId(relationship.end);
		relationship.data._id = parser.getRelationshipId(relationship.self);
		relationship.data._type = relationship.type;
		callback(null, relationship.data);
	} else {
		callback(new Error("Relationships data property doesn't exist.", null));
	}
};

/* Add relationship_id for an array of relationships */

Neo4j.prototype.addRelationshipIdForArray = function(relationships, callback) {
	var that = this;
	step(
		function process_relationships() {
			var group = this.group();
			relationships.forEach(function(relationship) {
				that.addRelationshipId(relationship, group());
			});
		},
		function sum_up(err, results) {
			if (err) {
				callback(err, null);
			} else {
				callback(null, results);
			}
		}
	);
};

/* Replace null values with an empty string */

Neo4j.prototype.replaceNullWithString = function(node_data, callback) {

	for (var key in node_data) {
		if (node_data.hasOwnProperty(key) && node_data[key] === null) {
			node_data[key] = '';
		}
	}

	return node_data;
};

/* Turn values that are objects themselves into strings. */

Neo4j.prototype.stringifyValueObjects = function(node_data, callback) {

	for (var key in node_data) {
		if (node_data.hasOwnProperty(key) && typeof node_data[key] === 'object') {
			node_data[key] = JSON.stringify(node_data[key]);
		}
	}

	return node_data;
};


text:
structure :user do

  basic :id, "The user's internal system ID", :type => Integer, :eg => 123
  basic :username, "The user's unique username", :type => String, :eg => "adamcooke"
  group :name do
    basic :first, "The user's first name", :type => String, :eg => "Adam", :source_attribute => :first_name
    basic :last, "The user's last name", :type => String, :eg => "Cooke", :source_attribute => :last_name
  end

  full :admin, "Is this user an administrator?", :type => :boolean
  full :age, "The user's age", :type => Integer, :doc => false
  full :created_at, "The timestamp the user was created", :type => :timestamp
  full :updated_at, "The timestamp the user was updated", :type => :timestamp

  expansion :pets, "All pets that belong to this user", :structure => :pet, :type => Array

  expansion :balance, "The user's balance", :type => Float, :eg => 12.50 do
    o.user.balance
  end

  expansion :hidden, "This is a hidden expansion", :doc => false do
    o.user.hidden
  end

  condition Proc.new { identity.admin? }, "Can only be accessed by API users with admin access" do
    # This value will only be provided to users who are accesing the API with
    # the permission to view
    full :support_pin, "The PIN this user needs to use to access support", :type => String, :eg => "4953"
  end

  condition :default => :anonymous do
    full :mask, "The unique mask that represents this user", :type => String, :eg => 'abc123abc123'
  end

end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
                  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                  xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
    <entity name="SSE\ICSSBundle\Entity\RecruitVisit" table="recruit_visit">
        <id name="id" type="integer" column="id">
            <generator strategy="IDENTITY"/>
        </id>
        <field name="visitAt" type="datetime" column="visit_at" nullable="true"/>
        <many-to-one field="recruit" target-entity="Recruit">
            <join-column name="recruit_id" referenced-column-name="id" on-delete="SET NULL"/>
        </many-to-one>
        <many-to-one field="student" target-entity="Student">
            <join-column name="student_id" referenced-column-name="id" on-delete="SET NULL"/>
        </many-to-one>
    </entity>
</doctrine-mapping>


text:
%% display channel locations
figure;

topoplot([],chanlocs, 'style', 'blank', 'electrodes', 'numpoint','efontsize',10,'electcolor','k','emarkersize',12,'hcolor','c');

%% visualize event stats from cnt files
for s=1:numel(subjects)
    subj = subjects{s};
    outpath = [outdir subj '\'];
    load([outpath 'batch1_summary.mat']);
    num_cnt_files = numel(cnt_stats.cntfnames);

    % display eventypes present in this cnt, and their corresponding frequencies
    disp([subj ' unique event types and their freqs: ']);

    for c = 1:num_cnt_files
        disp([cnt_stats.cntfnames{c} ':']);
        disp(['    srate: ' num2str(cnt_stats.srate{c})]);
        disp(['    time: ' num2str(cnt_stats.time{c})]);
        disp(['    nbchan: ' num2str(cnt_stats.nbchan{c})]);
        clear tmp;
        tmp(1,:) = cnt_stats.eventtypes{c};
        tmp(2,:) = cnt_stats.eventfreqs{c};
        disp(num2str(tmp));
    end
    close all;
end

%% visualize channel histograms
for s=1:numel(subjects)
    subj = subjects{s};
    outpath = [outdir subj '\'];
    load([outpath 'batch1_summary.mat']);
    num_cnt_files = numel(cnt_stats.cntfnames);
    % display chan histos - and indicate possible bad channels
    hh=figure('Name',subj,'position',[1000 717 554 204],'color',[1 1 1]);
    dim = ceil(num_cnt_files/4);
    for c = 1:num_cnt_files
        subplot(dim,4,c);
        bar(cnt_stats.chanhistomax{c});
        set(gca,'ylim',[-100 100],'xlim',[0 cnt_stats.nbchan{c}+1]);
        title(cnt_stats.cntfnames{c},'interpreter','none');
        axcopy(gcf);
    end
    set(hh,'position',[1000 717 554 204],'color',[1 1 1]);
    close all;
end

%% visualize ica and automatically detected ocular artifacts

%%% determine max num of comps across subjects
max_num_comps = 0;
for s=1:numel(subjects)
    subj = subjects{s};
    outpath = [outdir subj '\'];
    load([outpath 'batch1_summary.mat']);
    if(size(cnt_stats.mix_matrix,1) > max_num_comps)
        max_num_comps = size(cnt_stats.mix_matrix,1);
    end
end

%h=figure;
for s=1:numel(subjects)
    subj = subjects{s};
    outpath = [outdir subj '\'];
    load([outpath 'batch1_summary.mat']);
    winv = pinv(cnt_stats.mix_matrix);
    h=figure('Name',subj);
    %dim = ceil(sqrt(size(cnt_stats.mix_matrix,1)));
    for comp=1:size(cnt_stats.mix_matrix,1)
        subplot(s,max_num_comps,(s-1)*max_num_comps+comp);
        subplot(1,max_num_comps,comp);
        topoplot(winv(:,comp),chanlocs,'electrodes','off','numcontour',0);
        col = 'k'; if(ismember(comp,cnt_stats.rejcomps)), col = 'r'; end;
        simil = round(cnt_stats.similarity(comp) * 100)/100;
        simil_str = num2str(simil);
        title([simil_str([1:min(4,end)])],'color',col);
        if comp==1, ylabel(subj,'rotation',0,'visible','on'); end
        axcopy(gcf);
    end
    set(h,'Position',[1000 603 762 108],'color',[1 1 1]);
end
%set(h,'Position',[50 50 1000 1000],'color',[1 1 1]);


text:
A small set of mix tasks for creating mix commands that run npm commands.

## Features

* `mix npm SUBCOMMAND [ARGS]` is equivalent to `npm SUBCOMMAND ARGS`
* `mix npm.run SCRIPT [ARGS]` is equivalent to `npm run SCRIPT ARGS`

## Installation

If [available in Hex](https://hex.pm/docs/publish), the package can be installed
by adding `mix_npm` to your list of dependencies in `mix.exs`:

```elixir
def deps do
  [{:mix_npm, "~> 0.1.0"}]
end
```

Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc)
and published on [HexDocs](https://hexdocs.pm). Once published, the docs can
be found at [https://hexdocs.pm/mix_npm](https://hexdocs.pm/mix_npm).


text:
ComponentJS.ns("app.fw.root");
app.fw.root.model = ComponentJS.clazz({
    extend: app.fw.abstract.model,
    dynamics: {},
    protos: {

        create: function () {
            var self = this;
            self.base();
            cs(self).model({
                "global:command:resize": {value: false, valid: "boolean", autoreset: true},
                "event:windowResize": {value: false, valid: "boolean", autoreset: true}
            })
        }
    }
});


text:
package org.wso2.carbon.identity.application.authenticator.basicauth;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.identity.application.authentication.framework.AbstractApplicationAuthenticator;
import org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus;
import org.wso2.carbon.identity.application.authentication.framework.LocalApplicationAuthenticator;
import org.wso2.carbon.identity.application.authentication.framework.config.ConfigurationFacade;
import org.wso2.carbon.identity.application.authentication.framework.context.AuthenticationContext;
import org.wso2.carbon.identity.application.authentication.framework.exception.AuthenticationFailedException;
import org.wso2.carbon.identity.application.authentication.framework.exception.InvalidCredentialsException;
import org.wso2.carbon.identity.application.authentication.framework.exception.LogoutFailedException;
import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils;
import org.wso2.carbon.identity.application.authenticator.basicauth.internal.BasicAuthenticatorServiceComponent;
import org.wso2.carbon.identity.base.IdentityRuntimeException;
import org.wso2.carbon.identity.core.model.IdentityErrorMsgContext;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.core.UserCoreConstants;
import org.wso2.carbon.user.core.UserStoreException;
import org.wso2.carbon.user.core.UserStoreManager;
import org.wso2.carbon.user.core.util.UserCoreUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Username Password based Authenticator
 */
public class BasicAuthenticator extends AbstractApplicationAuthenticator
        implements LocalApplicationAuthenticator {

    private static final long serialVersionUID = 4438354156955223654L;
    private static final Log log = LogFactory.getLog(BasicAuthenticator.class);

    @Override
    public boolean canHandle(HttpServletRequest request) {
        String userName = request.getParameter(BasicAuthenticatorConstants.USER_NAME);
        String password = request.getParameter(BasicAuthenticatorConstants.PASSWORD);
        if (userName != null && password != null) {
            return true;
        }
        return false;
    }

    @Override
    public AuthenticatorFlowStatus process(HttpServletRequest request,
                                           HttpServletResponse response, AuthenticationContext context)
            throws AuthenticationFailedException, LogoutFailedException {

        if (context.isLogoutRequest()) {
            return AuthenticatorFlowStatus.SUCCESS_COMPLETED;
        } else {
            return super.process(request, response, context);
        }
    }

    @Override
    protected void initiateAuthenticationRequest(HttpServletRequest request,
                                                 HttpServletResponse response, AuthenticationContext context)
            throws AuthenticationFailedException {

        Map<String, String> parameterMap = getAuthenticatorConfig().getParameterMap();
        String showAuthFailureReason = null;
        if (parameterMap != null) {
            showAuthFailureReason = parameterMap.get("showAuthFailureReason");
            if (log.isDebugEnabled()) {
                log.debug("showAuthFailureReason has been set as : " + showAuthFailureReason);
            }
        }

        String loginPage = ConfigurationFacade.getInstance().getAuthenticationEndpointURL();
        String queryParams = context.getContextIdIncludedQueryParams();

        try {
            String retryParam = "";

            if (context.isRetrying()) {
                retryParam = "&authFailure=true&authFailureMsg=login.fail.message";
            }

            IdentityErrorMsgContext errorContext = IdentityUtil.getIdentityErrorMsg();
            IdentityUtil.clearIdentityErrorMsg();

            if (showAuthFailureReason != null && "true".equals(showAuthFailureReason)) {
                if (errorContext != null) {
                    if (log.isDebugEnabled()) {
                        log.debug("Identity error message context is not null");
                    }

                    String errorCode = errorContext.getErrorCode();
                    int remainingAttempts = errorContext.getMaximumLoginAttempts() - errorContext.getFailedLoginAttempts();

                    if (log.isDebugEnabled()) {
                        log.debug("errorCode : " + errorCode);
                        log.debug("username : " + request.getParameter(BasicAuthenticatorConstants.USER_NAME));
                        log.debug("remainingAttempts : " + remainingAttempts);
                    }

                    if (errorCode.equals(UserCoreConstants.ErrorCode.INVALID_CREDENTIAL)) {
                        retryParam = retryParam + BasicAuthenticatorConstants.ERROR_CODE + errorCode
                                + BasicAuthenticatorConstants.FAILED_USERNAME + URLEncoder.encode(request.getParameter(BasicAuthenticatorConstants.USER_NAME), BasicAuthenticatorConstants.UTF_8)
                                + "&remainingAttempts=" + remainingAttempts;
                        response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams))
                                + BasicAuthenticatorConstants.AUTHENTICATORS + getName() + ":" + BasicAuthenticatorConstants.LOCAL + retryParam);
                    } else if (errorCode.equals(UserCoreConstants.ErrorCode.USER_IS_LOCKED)) {
                        String redirectURL = loginPage.replace("login.do", "retry.do");
                        if (remainingAttempts == 0) {
                            redirectURL = response.encodeRedirectURL(redirectURL + ("?" + queryParams)) +
                                    BasicAuthenticatorConstants.ERROR_CODE + errorCode + BasicAuthenticatorConstants.FAILED_USERNAME +
                                    URLEncoder.encode(request.getParameter(BasicAuthenticatorConstants.USER_NAME), BasicAuthenticatorConstants.UTF_8) +
                                    "&remainingAttempts=0";
                        } else {
                            redirectURL = response.encodeRedirectURL(redirectURL + ("?" + queryParams)) +
                                    BasicAuthenticatorConstants.ERROR_CODE + errorCode + BasicAuthenticatorConstants.FAILED_USERNAME +
                                    URLEncoder.encode(request.getParameter(BasicAuthenticatorConstants.USER_NAME), BasicAuthenticatorConstants.UTF_8);
                        }
                        response.sendRedirect(redirectURL);

                    } else if (errorCode.equals(UserCoreConstants.ErrorCode.USER_DOES_NOT_EXIST)) {
                        retryParam = retryParam + BasicAuthenticatorConstants.ERROR_CODE + errorCode
                                + BasicAuthenticatorConstants.FAILED_USERNAME + URLEncoder.encode(request.getParameter(BasicAuthenticatorConstants.USER_NAME), BasicAuthenticatorConstants.UTF_8);
                        response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams))
                                + BasicAuthenticatorConstants.AUTHENTICATORS + getName() + ":" + BasicAuthenticatorConstants.LOCAL + retryParam);
                    }
                } else {
                    response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams))
                            + BasicAuthenticatorConstants.AUTHENTICATORS + getName() + ":" + BasicAuthenticatorConstants.LOCAL + retryParam);
                }
            } else {
                String errorCode = errorContext != null ? errorContext.getErrorCode() : null;
                if (errorCode != null && errorCode.equals(UserCoreConstants.ErrorCode.USER_IS_LOCKED)) {
                    String redirectURL = loginPage.replace("login.do", "retry.do");
                    redirectURL = response.encodeRedirectURL(redirectURL + ("?" + queryParams)) + BasicAuthenticatorConstants.FAILED_USERNAME + URLEncoder.encode(request.getParameter(BasicAuthenticatorConstants.USER_NAME), BasicAuthenticatorConstants.UTF_8);
                    response.sendRedirect(redirectURL);

                } else {
                    response.sendRedirect(response.encodeRedirectURL(loginPage + ("?" + queryParams))
                            + BasicAuthenticatorConstants.AUTHENTICATORS + getName() + ":" + BasicAuthenticatorConstants.LOCAL + retryParam);
                }
            }

        } catch (IOException e) {
            throw new AuthenticationFailedException(e.getMessage(), e);
        }
    }

    @Override
    protected void processAuthenticationResponse(HttpServletRequest request,
                                                 HttpServletResponse response, AuthenticationContext context)
            throws AuthenticationFailedException {

        String username = request.getParameter(BasicAuthenticatorConstants.USER_NAME);
        String password = request.getParameter(BasicAuthenticatorConstants.PASSWORD);

        boolean isAuthenticated;
        UserStoreManager userStoreManager;
        // Check the authentication
        try {
            int tenantId = IdentityTenantUtil.getTenantIdOfUser(username);
            UserRealm userRealm = BasicAuthenticatorServiceComponent.getRealmService().getTenantUserRealm(tenantId);
            if (userRealm != null) {
                userStoreManager = (UserStoreManager) userRealm.getUserStoreManager();
                isAuthenticated = userStoreManager.authenticate(MultitenantUtils.getTenantAwareUsername(username), password);
            } else {
                throw new AuthenticationFailedException("Cannot find the user realm for the given tenant: " + tenantId);
            }
        } catch (IdentityRuntimeException e) {
            if(log.isDebugEnabled()){
                log.debug("BasicAuthentication failed while trying to get the tenant ID of the user " + username, e);
            }
            throw new AuthenticationFailedException(e.getMessage(), e);
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            if(log.isDebugEnabled()){
                log.debug("BasicAuthentication failed while trying to authenticate", e);
            }
            throw new AuthenticationFailedException(e.getMessage(), e);
        }

        if (!isAuthenticated) {
            if (log.isDebugEnabled()) {
                log.debug("user authentication failed due to invalid credentials.");
            }

            throw new InvalidCredentialsException();
        }

        Map<String, Object> authProperties = context.getProperties();
        String tenantDomain = MultitenantUtils.getTenantDomain(username);

        if (authProperties == null) {
            authProperties = new HashMap<String, Object>();
            context.setProperties(authProperties);
        }

        //TODO: user tenant domain has to be an attribute in the AuthenticationContext
        authProperties.put("user-tenant-domain", tenantDomain);

        username = FrameworkUtils.prependUserStoreDomainToName(username);

        if (getAuthenticatorConfig().getParameterMap() != null) {
            String userNameUri = getAuthenticatorConfig().getParameterMap().get("UserNameAttributeClaimUri");
            if (userNameUri != null && userNameUri.trim().length() > 0) {
                boolean multipleAttributeEnable;
                String domain = UserCoreUtil.getDomainFromThreadLocal();
                if (domain != null && domain.trim().length() > 0) {
                    multipleAttributeEnable = Boolean.parseBoolean(userStoreManager.getSecondaryUserStoreManager(domain).
                            getRealmConfiguration().getUserStoreProperty("MultipleAttributeEnable"));
                } else {
                    multipleAttributeEnable = Boolean.parseBoolean(userStoreManager.
                            getRealmConfiguration().getUserStoreProperty("MultipleAttributeEnable"));
                }
                if (multipleAttributeEnable) {
                    try {
                        if (log.isDebugEnabled()) {
                            log.debug("Searching for UserNameAttribute value for user " + username +
                                    " for claim uri : " + userNameUri);
                        }
                        String usernameValue = userStoreManager.
                                getUserClaimValue(MultitenantUtils.getTenantAwareUsername(username), userNameUri, null);
                        if (usernameValue != null && usernameValue.trim().length() > 0) {
                            tenantDomain = MultitenantUtils.getTenantDomain(username);
                            usernameValue = FrameworkUtils.prependUserStoreDomainToName(usernameValue);
                            username = usernameValue + "@" + tenantDomain;
                            if (log.isDebugEnabled()) {
                                log.debug("UserNameAttribute is found for user. Value is :  " + username);
                            }
                        }
                    } catch (UserStoreException e) {
                        //ignore  but log in debug
                        if(log.isDebugEnabled()) {
                            log.debug("Error while retrieving UserNameAttribute for user : " + username, e);
                        }
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("MultipleAttribute is not enabled for user store domain : " + domain + " " +
                                "Therefore UserNameAttribute is not retrieved");
                    }
                }
            }
        }
        context.setSubject(AuthenticatedUser.createLocalAuthenticatedUserFromSubjectIdentifier(username));
        String rememberMe = request.getParameter("chkRemember");

        if (rememberMe != null && "on".equals(rememberMe)) {
            context.setRememberMe(true);
        }
    }

    @Override
    protected boolean retryAuthenticationEnabled() {
        return true;
    }

    @Override
    public String getContextIdentifier(HttpServletRequest request) {
        return request.getParameter("sessionDataKey");
    }

    @Override
    public String getFriendlyName() {
        return BasicAuthenticatorConstants.AUTHENTICATOR_FRIENDLY_NAME;
    }

    @Override
    public String getName() {
        return BasicAuthenticatorConstants.AUTHENTICATOR_NAME;
    }
}


text:
1. [Portable Server Prerequisites](#portable-server-prerequisites)
    1. [Build Prerequisites](#build-prerequisites)
    1. [Run-time Prerequisites](#run-time-prerequisites)
1. [Portable Server on Linux](#portable-server-on-linux)
    1. [Building on Linux](#building-on-linux)
    1. [Installing on Linux](#installing-on-linux)
    1. [Running on Linux](#running-on-linux)
1. [Portable Server on Windows](#portable-server-on-windows)
    1. [Building on Windows](#building-on-windows)
    1. [Installing on Windows](#installing-on-windows)
    1. [Running on Windows](#running-on-windows)
1. [Portable Server on Mac OS](#portable-server-on-mac-os)

# Portable Server Prerequisites

## Build Prerequisites:

    * Python 2.7
    * Python pexpect installed
    * Swig with support for Python (4.0.1 or later)
    * g++ (4.8 or later)

## Run-time prerequisites:

    * Python 2.7
    * Python tornado installed
    * Python Imaging Library (PIL) installed

#### On CentOS/RHEL 6:

    sudo yum -y install python27-pip
    sudo pip2.7 install tornado pillow

# Portable Server on Linux

## Building on Linux

Make sure you have Python, the `pexpect` Pip package, as well as `tornado`, and g++ installed. Swig is bundled for Linux.

### Getting a Build Environment

#### On Ubuntu:

    sudo apt-get install g++ python python-pexpect python-tornado libpython-dev python-psycopg2

#### On CentOS/RHEL 7:

    sudo yum -y install gcc-c++ python python-pip python-tornado python-psycopg2
    sudo pip install pexpect

#### On CentOS/RHEL 6:

If you're running an old version of a Red Hat distribution, such as Cent OS or RHEL 6, the packaged `g++` compiler will be too old.  Enable the EPEL package repository, and install `devtoolset2` to get a more recent compiler:

    sudo yum install devtoolset-2-toolchain
    sudo yum -y install ius-release
    sudo yum -y install gcc-c++ python27 python27-pip python27-devel
    sudo pip2.7 install tornado pexpect psycopg2-binary gitpython

### Building

Run

    earthenterprise/earth_enterprise/src/portableserver/build.py

The build script will produce a compressed archive with a name that looks like `earthenterprise/earth_enterprise/src/portableserver/build/portableserver-linux-5.1.3-20170412.tar.gz`. The build date part of the file name will change depending on the day you build.

You can install the built Portable Server from this `.tar.gz` archive.

To clean build files, run

    earthenterprise/earth_enterprise/src/portableserver/build.py --clean

## Installing on Linux

Portable Server is not currently packaged for Linux distributions by the GEE Open Source team. Instead, just extract the tarball generated in the [Building on Linux](#building-on-linux) step in a directory you want to run it from.  You could also create links, or start-up shell scripts for your convenience.

You need to have the Python interpreter and package dependencies listed in [Run-time Prerequisites](#run-time-prerequisites) set up and installed in order to run Portable Server.  If you carried out the [Building on Linux](#building-on-linux) step, you already have all of the required dependencies.

## Running on Linux

Change into the directory you extracted the built Portable Server tarball into (in the [Installing on Linux](#installing-on-linux) step).  Then, just start `server/portable_server.py`:

    1. cd portableserver-linux-5.1.3-20170412/server/ #(substituting your extracted directory)
    1. python portable_server.py

You can edit `portableserver-linux-5.1.3-20170412/server/portable.cfg` and `portableserver-linux-5.1.3-20170412/server/remote.cfg` for your configuration needs before starting the server.

# Portable Server on Windows

## Building on Windows

**Note:** It is important to ensure `g++` and `python` versions used are both 32 bit or both 64 bit.  Mixing them will lead to compilation/link errors which are not immediately obvious.

If you want to build a 64 bit version of portable server, you must install the 64 bit versions of g++ and python.

### Install a g++ Compiler

You can install [MinGW](https://sourceforge.net/projects/mingw-w64/) with a g++ compiler.  Ensure the architecture you select to install matches your desired build architecture.  If intending to distribute the build to other windows systems, be sure to select the `win` threads installation.  Compiling with g++ for posix threads will lead to additional run-time dependencies.

Make sure `g++` is set in your `PATH`.

### Install Swig with Python Support

1. Download a [Swig](http://www.swig.org/download.html) Zip for Windows.
2. Extract the Zip in a desired installation directory.
3. Add the installation directory you extracted to your `PATH`.

### Install Python

Download and install [Python](https://www.python.org/downloads/) the latest Python 2.7 package.  Ensure the python architecture matches your desired build architecture.

Once you have Python installed, make sure you have `pexpect` and `tornado` installed. E.g.:

    cd \Python27\Scripts
    pip install pexpect tornado

Add the directory you installed Python in to your `PATH`.

### Build Portable Server

Open a command prompt with `g++`, `swig` and `python` in your `PATH`.

E.g., on Windows your `PATH` may look like:

```
C:\swigwin-3.0.12;C:\Python27;C:\MinGW\bin;C:\Program Files\ . . .
```

Run

    python earthenterprise\earth_enterprise\src\portableserver\build.py

The build script will produce a compressed archive with a name that looks like `earthenterprise\earth_enterprise\src\portableserver\build\portableserver-windows-5.1.3-20170412.zip`. The build date part of the file name will change depending on the day you build.

You can install the built Portable Server from this Zip archive.

To clean build files, run

    python earthenterprise\earth_enterprise\src\portableserver\build.py --clean

## Installing on Windows

We do not currently provide a Windows installer for Portable Server. Instead, just extract the built Portable Server from the Zip archive generated in the [Building on Windows](#building-on-windows) step in a directory you want to run it from.

You need to have the Python interpreter and packages listed in [Run-time Prerequisites](#run-time-prerequisites) set up and installed in order to run Portable Server.  If you carried out the [Building on Windows](#building-on-windows) step, you already have the required dependencies.

## Running on Windows

Change into the directory you extracted the built Portable Server Zip archive into (in the [Installing on Windows](#installing-on-windows) step). Then, just start `server\portable_server.py`:

    1. cd portableserver-windows-5.1.3-20170412\server\ #(substituting your extracted directory)
    1. python portable_server.py

You can edit `portableserver-windows-5.1.3-20170412\server\portable.cfg` and `portableserver-windows-5.1.3-20170412\server\remote.cfg` for your configuration needs before starting the server.

# Portable Server on Mac OS

Currently, building and running Portable Server on Mac OS has not been tested.

Previous versions have run on Mac OS, and the `build.py` script has untested logic for running the Mac OS build commands.  However, at present, you'll have to fix any problems you run into on Mac OS.


text:
package cool.arch.monadicexceptions;

import java.io.IOException;
import java.util.function.ToDoubleBiFunction;

import cool.arch.monadicexceptions.ThrowableToDoubleBiFunction;

/**
 *
 */
public class ThrowableToDoubleBiFunctionTest extends AbstractLambdaTest<ThrowableToDoubleBiFunction<String, String>, ToDoubleBiFunction<String, String>> {

	/**
	 *
	 */
	@SuppressWarnings("boxing")
	public ThrowableToDoubleBiFunctionTest() {
		super(lambda -> lambda.applyAsDouble("1.5", "2.75") == (1.5 + 2.75), ThrowableToDoubleBiFunction::asToDoubleBiFunction, (t, u) -> {
			throw new IOException();
		} , (t, u) -> Double.valueOf(t) + Double.valueOf(u));
	}
}


text:
class Tweet;

class TwitterClient
{
public:
    TwitterClient();

    void fetchAuthorizationToken(std::function<void (QString)> completion);
    void fetchTweetsForUser(const QString &user, std::function<void (std::vector<Tweet>, QString)> completion);
    void fetchImageAtURL(const QString &imageURL, std::function<void (QImage)> completion);

    static QUrl createURL(const QString &urlString);

    TwitterClient(const TwitterClient &) = delete;
    TwitterClient &operator=(const TwitterClient &) = delete;

    TwitterClient(const TwitterClient &&) = delete;
    TwitterClient &operator=(const TwitterClient &&) = delete;

signals:

public slots:

private:
    std::unique_ptr<QNetworkAccessManager> manager;
    std::vector<QNetworkReply *> inFlightRequests;
};

#endif // TWITTERCLIENT_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SunokoLibrary.Web.GooglePlus.Primitive
{
    public class AttachedImageData : AttachedLink
    {
        public AttachedImageData(ContentType type, string title, string summary,
            Uri linkUrl, Uri faviconUrl, Uri originalThumbnailUrl, string thumbnailUrl, int thumbnailWidth,
            int thumbnailHeight, ImageData image, AlbumData album, Uri plusBaseUrl)
            : base(type, title, summary, linkUrl, faviconUrl, originalThumbnailUrl, thumbnailUrl, thumbnailWidth, thumbnailHeight)
        {
            Image = image;
            Album = album;
        }
        public readonly ImageData Image;
        public readonly AlbumData Album;
    }
}


text:
from SBaaS_base.postgresql_orm_base import *

class data_stage01_resequencing_histogram(Base):
    __tablename__ = 'data_stage01_resequencing_histogram'
    id = Column(Integer, Sequence('data_stage01_resequencing_histogram_id_seq'), primary_key=True)
    analysis_id = Column(String(500))
    feature_id = Column(String(500))
    feature_units = Column(String(50))
    bin = Column(Float)
    bin_width = Column(Float)
    frequency = Column(Integer)
    used_ = Column(Boolean);
    comment_ = Column(Text);

    __table_args__ = (
            UniqueConstraint('analysis_id','feature_id','feature_units','bin',),
            )
    def __init__(self,
                row_dict_I,
                ):
        self.bin_width=row_dict_I['bin_width'];
        self.frequency=row_dict_I['frequency'];
        self.used_=row_dict_I['used_'];
        self.comment_=row_dict_I['comment_'];
        self.feature_id=row_dict_I['feature_id'];
        self.analysis_id=row_dict_I['analysis_id'];
        self.bin=row_dict_I['bin'];
        self.feature_units=row_dict_I['feature_units'];

    def __set__row__(self,analysis_id_I,
        feature_id_I,
        feature_units_I,
        bin_I,
        bin_width_I,
        frequency_I,
        used__I,
        comment__I,):
        self.analysis_id=analysis_id_I
        self.feature_id=feature_id_I
        self.feature_units=feature_units_I
        self.bin=bin_I
        self.bin_width=bin_width_I
        self.frequency=frequency_I
        self.used_=used__I
        self.comment_=comment__I

    def __repr__dict__(self):
        return {'id':self.id,
                'analysis_id':self.analysis_id,
                'feature_id':self.feature_id,
                'feature_units':self.feature_units,
                'bin':self.bin,
                'bin_width':self.bin_width,
                'frequency':self.frequency,
                'used_':self.used_,
                'comment_':self.comment_,}

    def __repr__json__(self):
        return json.dumps(self.__repr__dict__())


text:
Configurable Types and Values
=============================

Asset Values
------------

You can assign descriptions for None, Low, Medium, and High asset values by selecting the Options / Asset Value value menu, and clicking on the Value to be updated.

Asset Types
------------

By default, CAIRIS databases are pre-defined with Information, Systems, Software, Hardware, and People asset types.

You can add a new asset type by selecting the Options / Asset Types menu and clicking on the Add button.  You should then enter an asset type name and description, before clicking the Create button.

Existing asset type name and descriptions can be modified by clicking on an asset type to be updated, making the required changes, and clicking on Update.

A selected asset type can be deleted by clicking on its delete button.  Although possible, we do not recommend deleting the standard asset types that come with CAIRIS.

If you are modelling a System of Systems, you may also benefit from using the asset type of *Systems - General*, used to reperesent organisations, groups, or social systems, and asset type *System of Systems* representing the combination of Independent Systems (collaborating to achieve a new combined purpose and goal).

Other Types
-----------

You can add a selection of types associated with risk and architectural models from the appropriate Options sub-menu by clicking on the Add button.  You should then enter a name, score, description, and -- where appropriate -- score and rationale before clicking on the Create button.

Existing values can be modified by clicking on the to be updated, making the required changes, and clicking the Update button.

A selected type can be deleted by clicking on its delete button.


text:
namespace LightMock
{
    using System;
    using System.Linq.Expressions;
    using System.Reflection;

    /// <summary>
    /// An <see cref="ExpressionVisitor"/> that replaces references to the
    /// <see cref="The{TValue}.IsAnyValue"/> with a <see cref="MethodCallExpression"/>
    /// that represents calling the <see cref="The{TValue}.Is"/> method.
    /// </summary>
    public class MatchExpressionRewriter : ExpressionVisitor
    {

        /// <summary>
        /// Replaces references to the <see cref="The{TValue}.IsAnyValue"/> with a <see cref="MethodCallExpression"/>
        /// that represents calling the <see cref="The{TValue}.Is"/> method.
        /// </summary>
        /// <param name="expression">The <see cref="LambdaExpression"/> to visit.</param>
        /// <returns><see cref="Expression"/>.</returns>
        public LambdaExpression Rewrite(LambdaExpression expression)
        {
            return (LambdaExpression)Visit(expression);
        }

        /// <summary>
        /// Replaces references to the <see cref="The{TValue}.IsAnyValue"/> with a <see cref="MethodCallExpression"/>
        /// that represents calling the <see cref="The{TValue}.Is"/> method.
        /// </summary>
        /// <param name="node">The <see cref="MemberExpression"/> to visit.</param>
        /// <returns><see cref="Expression"/>.</returns>
        protected override Expression VisitMember(MemberExpression node)
        {
            MemberInfo member = node.Member;

            if (RepresentsIsAnyValueProperty(member))
            {
                return CreateMethodCallExpression(member);
            }

            return base.VisitMember(node);
        }

        private static bool RepresentsIsAnyValueProperty(MemberInfo member)
        {
            return member.Name == "IsAnyValue";
        }

        private static Expression CreateMethodCallExpression(MemberInfo member)
        {
            var parameterExpression = Expression.Parameter(GetParameterType(member), "v");
            var trueConstantExpression = Expression.Constant(true, typeof(bool));
            LambdaExpression trueExpression = Expression.Lambda(trueConstantExpression, parameterExpression);
            MethodCallExpression methodCallExpression = Expression.Call(GetIsMethod(member), trueExpression);
            return methodCallExpression;
        }

        private static MethodInfo GetIsMethod(MemberInfo member)
        {
            // ReSharper disable once PossibleNullReferenceException
	        return member.DeclaringType.GetMethod("Is");
        }

        private static Type GetParameterType(MemberInfo member)
        {
            // ReSharper disable once PossibleNullReferenceException
	        return member.DeclaringType.GetGenericArguments()[0];
        }
    }
}


text:
class HoursController < ApplicationController
  before_action :set_exhibition
  before_action :set_hour, only: [:show, :edit, :update, :destroy]
  before_action do
    set_focus('hours')
  end

  def index
    @hours = Hour.all
  end

  def show

  end

  def new
    @hour = Hour.new
  end

  def edit
  end

  def update
    if @hour.update(hour_params)
      redirect_to @hour, notice: 'Schedule was successfully updated.'
    else
      render action: 'edit'
    end
  end

  def create
    @hour = Hour.new(hour_params)

    if @hour.save
      redirect_to @hour, notice: 'Schedule was successfully created.'
    else
      render action: 'new'
    end
  end

  def destroy
    @hour.destroy
    redirect_to action: :index
  end

    def hour_params
      params.require(:hour).permit(
            :start_schedule,
            :end_schedule,
            :sunday_start,
            :sunday_end,
            :monday_start,
            :monday_end,
            :tuesday_start,
            :tuesday_end,
            :wednesday_start,
            :wednesday_end,
            :thursday_start,
            :thursday_end,
            :friday_start,
            :friday_end,
            :saturday_start,
            :saturday_end
          )

    end

    private
      def set_hour
        @hour = Hour.find(params[:id])
      end
end


text:
<?php

/**
 * @file
 * Contains \Drupal\system\Tests\Theme\StableThemeTest.
 */

namespace Drupal\system\Tests\Theme;

use Drupal\simpletest\KernelTestBase;

/**
 * Tests the behavior of the Stable theme.
 *
 * @group Theme
 */
class StableThemeTest extends KernelTestBase {

  /**
   * Modules to install.
   *
   * @var array
   */
  public static $modules = ['system'];

  /**
   * The theme handler.
   *
   * @var \Drupal\Core\Extension\ThemeHandlerInterface
   */
  protected $themeHandler;

  /**
   * The theme manager.
   *
   * @var \Drupal\Core\Theme\ThemeManagerInterface
   */
  protected $themeManager;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->themeHandler = $this->container->get('theme_handler');
    $this->themeManager = $this->container->get('theme.manager');
  }

  /**
   * Ensures Stable is used by default when no base theme has been defined.
   */
  public function testStableIsDefault() {
    $this->themeHandler->install(['test_stable']);
    $this->config('system.theme')->set('default', 'test_stable')->save();
    $theme = $this->themeManager->getActiveTheme();
    /** @var \Drupal\Core\Theme\ActiveTheme $base_theme */
    $base_themes = $theme->getBaseThemes();
    $base_theme = reset($base_themes);
    $this->assertTrue($base_theme->getName() == 'stable', "Stable theme is the base theme if a theme hasn't decided to opt out.");
  }

  /**
   * Tests opting out of Stable by setting the base theme to false.
   */
  public function testWildWest() {
    $this->themeHandler->install(['test_wild_west']);
    $this->config('system.theme')->set('default', 'test_wild_west')->save();
    $theme = $this->themeManager->getActiveTheme();
    /** @var \Drupal\Core\Theme\ActiveTheme $base_theme */
    $base_themes = $theme->getBaseThemes();
    $this->assertTrue(empty($base_themes), 'No base theme is set when a theme has opted out of using Stable.');
  }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.guutong.guutongprimeface.connectdb.mapping;

import com.guutong.guutongprimeface.connectdb.annotation.Column;
import com.guutong.guutongprimeface.connectdb.util.ResultSetType;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author pornmongkon
 */
public class GenericAnnotationMapping {

    private static String firstChar2UpperCase(String str) {
        return str.substring(0, 1).toUpperCase() + str.substring(1);
    }

    private static Method getSetterMethodOfField(Object object, Field field) throws Exception {
        String setterName = "set" + firstChar2UpperCase(field.getName());
        return object.getClass().getDeclaredMethod(setterName, field.getType());
    }

    private static String getColumnName(Field field) {
        if (field.isAnnotationPresent(Column.class)) {
            return field.getAnnotation(Column.class).name();
        } else {
            return field.getName();
        }
    }

    private static <T> T transformResultReset(ResultSet resultSet, Class<T> clazz) throws Exception {
        T instance = clazz.newInstance();
        Field[] fields = clazz.getDeclaredFields();
        ResultSetType type = ResultSetType.wrap(resultSet);

        for (Field field : fields) {
            String columnName = getColumnName(field);
            Method method = getSetterMethodOfField(instance, field);
            method.invoke(instance, type.getValue(columnName, field.getType()));
        }

        return instance;
    }

    public static <T> List<T> fromResultSet(ResultSet resultSet, Class<T> clazz) throws Exception {
        List<T> list = new LinkedList<>();
        while (resultSet.next()) {
            list.add(transformResultReset(resultSet, clazz));
        }

        return list;
    }
}


text:
const _isString = require('lodash/isString');
const _isNumber = require('lodash/isNumber');
const _isNull = require('lodash/isNull');
const _isUndefined = require('lodash/isUndefined');

class ValidationUtils {

    static toInteger(input) {
        if (ValidationUtils.isEmpty(input))
            return undefined;

        var num = Number(input);
        if (!isNaN(num))
            num = parseInt(input);

        return isNaN(num) ? input : num;
    }

    static toFloat(input) {
        if (ValidationUtils.isEmpty(input))
            return undefined;

        var num = input;
        if(_isNumber(input)) {
            num = input.toString();
        }

        // Need to perform this regexp to avoid parseFloat() to convert xx. to xx
        if(/^\-?[0-9]+\.?[0-9]*$/.test(num)) {
            if(num.endsWith(".") || num.endsWith(".0")) {
                return num;
            } else {
                return parseFloat(num);
            }
        } else {
            return num;
        }
    }

    static toString(input) {
        if (ValidationUtils.isEmpty(input))
            return undefined;

        var string = input;
        if(_isString(string)) {
            string = input.toString();
        }
        return string;
    }

    static toBoolean(input) {
        return input === "true" || input === true;
    }

    static isEmpty(input) {
        return _isNull(input) || _isUndefined(input) || input === "";
    }

}

module.exports = ValidationUtils;


text:
package li.strolch.model.parameter;

import static java.util.stream.Collectors.joining;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;

import li.strolch.exception.StrolchException;
import li.strolch.utils.helper.StringHelper;

public abstract class AbstractListParameter<E> extends AbstractParameter<List<E>> implements ListParameter<E> {

	protected List<E> value;

	/**
	 * Empty constructor
	 */
	AbstractListParameter() {
		//
	}

	/**
	 * Default constructor
	 *
	 * @param id
	 * 		the id
	 * @param name
	 * 		the name
	 */
	AbstractListParameter(String id, String name) {
		super(id, name);
	}

	protected abstract void validateElement(E value);

	protected abstract String elementToString(E element);

	protected abstract List<E> parseString(String valueAsString);

	/**
	 * Validates that the value is legal. This is the case when it is not null in this implementation
	 *
	 * @param values
	 * 		the values to check for this parameter instance
	 *
	 * @throws StrolchException
	 * 		if the value is null
	 */
	protected void validateValue(List<E> values) throws StrolchException {
		if (values == null) {
			String msg = "Can not set null value on Parameter {0}"; //$NON-NLS-1$
			msg = MessageFormat.format(msg, getLocator());
			throw new StrolchException(msg);
		}

		values.forEach(this::validateElement);
	}

	/**
	 * Validates that the value is legal. This is the case when it is not null in this implementation
	 *
	 * @param values
	 * 		the values to check for this parameter instance
	 *
	 * @throws StrolchException
	 * 		if the value is null
	 */
	protected void validateValue(Collection<E> values) throws StrolchException {
		if (values == null) {
			String msg = "Can not set null value on Parameter {0}"; //$NON-NLS-1$
			msg = MessageFormat.format(msg, getLocator());
			throw new StrolchException(msg);
		}

		values.forEach(this::validateElement);
	}

	@Override
	public String getValueAsString() {
		if (this.value.isEmpty())
			return StringHelper.EMPTY;
		return this.value.stream().map(this::elementToString).collect(joining(", "));
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> getValue() {
		return new ArrayList<>(this.value);
	}

	@Override
	public E getValue(int index) {
		if (this.value.isEmpty() || this.value.size() < index)
			throw new IllegalStateException("No value at index " + index + " for " + getLocator());
		return this.value.get(index);
	}

	@Override
	public Stream<E> streamValues() {
		return this.value.stream();
	}

	@Override
	public void setValue(List<E> values) {
		assertNotReadonly();
		validateValue(values);
		this.value = new ArrayList<>(values);
	}

	@Override
	public void setValue(Collection<E> values) {
		assertNotReadonly();
		validateValue(values);
		this.value = new ArrayList<>(values);
	}

	@Override
	public void setValueFrom(Parameter<List<E>> parameter) {
		assertNotReadonly();
		this.value = new ArrayList<>(parameter.getValue());
	}

	@Override
	public void setValueFromString(String valueAsString) {
		setValue(parseString(valueAsString));
	}

	@Override
	public void addValue(E value) {
		assertNotReadonly();
		validateElement(value);
		this.value.add(value);
	}

	@Override
	public void addAllValues(List<E> values) {
		assertNotReadonly();
		for (E value : values) {
			validateElement(value);
			this.value.add(value);
		}
	}

	@Override
	public void addAllValuesIfNotContains(List<E> values) {
		assertNotReadonly();
		for (E value : values) {
			validateElement(value);
			if (!this.value.contains(value))
				this.value.add(value);
		}
	}

	@Override
	public boolean addValueIfNotContains(E value) {
		assertNotReadonly();
		validateElement(value);

		if (this.value.contains(value))
			return false;

		this.value.add(value);
		return true;
	}

	@Override
	public boolean removeValue(E value) {
		assertNotReadonly();
		return this.value.remove(value);
	}

	@Override
	public void clear() {
		assertNotReadonly();
		if (this.value == null)
			this.value = new ArrayList<>();
		else
			this.value.clear();
	}

	@Override
	public boolean isEmpty() {
		return this.value.isEmpty();
	}

	@Override
	public boolean isEqualTo(Parameter<List<E>> otherValue) {
		AbstractListParameter<E> other = (AbstractListParameter<E>) otherValue;
		return this.value.equals(other.value);
	}

	@Override
	public boolean isEqualTo(List<E> otherValue) {
		return this.value.equals(otherValue);
	}

	@Override
	public int size() {
		return this.value.size();
	}

	@Override
	public boolean contains(E value) {
		return this.value.contains(value);
	}

	@Override
	public boolean containsAll(List<E> values) {
		return this.value.containsAll(values);
	}
}


text:
package javax.servlet;

import java.util.ResourceBundle;

/**
 * @since Servlet 3.0
 * TODO SERVLET3 - Add comments
 */
public class HttpMethodConstraintElement extends HttpConstraintElement {

    // Can't inherit from HttpConstraintElement as API does not allow it
    private static final String LSTRING_FILE = "javax.servlet.LocalStrings";
    private static final ResourceBundle lStrings =
        ResourceBundle.getBundle(LSTRING_FILE);

    private final String methodName;

    public HttpMethodConstraintElement(String methodName) {
        if (methodName == null || methodName.length() == 0) {
            throw new IllegalArgumentException(lStrings.getString(
                    "httpMethodConstraintElement.invalidMethod"));
        }
        this.methodName = methodName;
    }

    public HttpMethodConstraintElement(String methodName,
            HttpConstraintElement constraint) {
        super(constraint.getEmptyRoleSemantic(),
                constraint.getTransportGuarantee(),
                constraint.getRolesAllowed());
        if (methodName == null || methodName.length() == 0) {
            throw new IllegalArgumentException(lStrings.getString(
                    "httpMethodConstraintElement.invalidMethod"));
        }
        this.methodName = methodName;
    }

    public String getMethodName() {
        return methodName;
    }
}