text:
#include "GraphConstraintUpdateFilter.h"
#include "brics_3d/core/Logger.h"
#include "brics_3d/core/HomogeneousMatrix44.h"
#include "brics_3d/util/Timer.h"
#include "SubGraphChecker.h"

namespace brics_3d {
namespace rsg {

const std::string GraphConstraintUpdateFilter::contraintKey = "rsg:agent_policy";

GraphConstraintUpdateFilter::GraphConstraintUpdateFilter(WorldModel* wm, UpdateMode mode) : mode(mode), wm(wm) {
	this->nameSpaceIdentifier = "unknown_namespace";
	assert(this->wm != 0);

	/* get initial constraints from root node */
	vector<Attribute> rootAttributes;
	wm->scene.getNodeAttributes(wm->getRootNodeId(), rootAttributes);
	getConstraintsFromAttributes(rootAttributes, this->constraints);

}

GraphConstraintUpdateFilter::~GraphConstraintUpdateFilter() {

}

bool GraphConstraintUpdateFilter::addNode(Id parentId, Id& assignedId,
		vector<Attribute> attributes, bool forcedId) {
	bool success = true;

	std::vector<GraphConstraint>::iterator it;
	for (it = constraints.begin(); it != constraints.end(); ++it) {
		if (!checkConstraint(*it, GraphConstraint::Node, 0, 0, 0, assignedId, attributes)) {
			LOG(DEBUG) << "GraphConstraintUpdateFilter::addNode is skipped because a constraint does not hold.";
			return false;
		}
	}

	/* Memorize last invocation */
	lastSendType[GraphConstraint::Node] = wm->now();
	lastSendType[GraphConstraint::Atom] = wm->now();

	/* Call _all_ observers  */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->addNode(parentId, assignedId, attributes, forcedId);
	}
	return success;
}

bool GraphConstraintUpdateFilter::addGroup(Id parentId, Id& assignedId,
		vector<Attribute> attributes, bool forcedId) {
	bool success = true;

	std::vector<GraphConstraint>::iterator it;
	for (it = constraints.begin(); it != constraints.end(); ++it) {
		if (!checkConstraint(*it, GraphConstraint::Group, 0, 0, 0, assignedId, attributes)) {
			LOG(DEBUG) << "GraphConstraintUpdateFilter::addGroup is skipped because a constraint does not hold.";
			return false;
		}
	}

	/* Memorize last invocation */
	lastSendType[GraphConstraint::Group] = wm->now();
	lastSendType[GraphConstraint::Atom] = wm->now();

	/* Call _all_ observers  */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->addGroup(parentId, assignedId, attributes, forcedId);
	}
	return success;
}

bool GraphConstraintUpdateFilter::addTransformNode(Id parentId, Id& assignedId,
		vector<Attribute> attributes,
		IHomogeneousMatrix44::IHomogeneousMatrix44Ptr transform,
		TimeStamp timeStamp, bool forcedId) {
	bool success = true;

	std::vector<GraphConstraint>::iterator it;
	for (it = constraints.begin(); it != constraints.end(); ++it) {
		if (!checkConstraint(*it, GraphConstraint::Transform, 0, 0, 0, assignedId, attributes)) {
			LOG(DEBUG) << "GraphConstraintUpdateFilter::addTransformNode is skipped because a constraint does not hold.";
			return false;
		}
	}

	/* Memorize last invocation */
	lastSendType[GraphConstraint::Transform] = wm->now();
	lastSendType[GraphConstraint::Atom] = wm->now();

	/* Call _all_ observers  */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->addTransformNode(parentId, assignedId, attributes, transform, timeStamp, forcedId);
	}
	return success;

}

bool GraphConstraintUpdateFilter::addUncertainTransformNode(Id parentId,
		Id& assignedId, vector<Attribute> attributes,
		IHomogeneousMatrix44::IHomogeneousMatrix44Ptr transform,
		ITransformUncertainty::ITransformUncertaintyPtr uncertainty,
		TimeStamp timeStamp, bool forcedId) {
	bool success = true;

	std::vector<GraphConstraint>::iterator it;
	for (it = constraints.begin(); it != constraints.end(); ++it) {
		if (!checkConstraint(*it, GraphConstraint::Transform, 0, 0, 0, assignedId, attributes)) {
			LOG(DEBUG) << "GraphConstraintUpdateFilter::addUncertainTransformNode is skipped because a constraint does not hold.";
			return false;
		}
	}

	/* Memorize last invocation */
	lastSendType[GraphConstraint::Transform] = wm->now();
	lastSendType[GraphConstraint::Atom] = wm->now();

	/* Call _all_ observers  */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->addUncertainTransformNode(parentId, assignedId, attributes, transform, uncertainty, timeStamp, forcedId);
	}
	return success;
}

bool GraphConstraintUpdateFilter::addGeometricNode(Id parentId, Id& assignedId,
		vector<Attribute> attributes, Shape::ShapePtr shape,
		TimeStamp timeStamp, bool forcedId) {
	bool success = true;

	GraphConstraint::Type shapeType;
	switch (shape->getShapeType()) {
		case Shape::Sphere:
			shapeType = GraphConstraint::Sphere;
			break;
		case Shape::Cylinder:
			shapeType = GraphConstraint::Cylinder;
			break;
		case Shape::Box:
			shapeType = GraphConstraint::Box;
			break;
		case Shape::Mesh:
			shapeType = GraphConstraint::Mesh;
			break;
		case Shape::PointCloud:
			shapeType = GraphConstraint::PointCloud;
			break;
		default:
			break;
	}

	double lod = -1.0;
	lodCalculator.calculateLOD(shape, lod);

	std::vector<GraphConstraint>::iterator it;
	for (it = constraints.begin(); it != constraints.end(); ++it) {
		if (!checkConstraint(*it, GraphConstraint::GeometricNode, 0, 0, lod, assignedId, attributes)) {
			LOG(DEBUG) << "GraphConstraintUpdateFilter::addGeometricNode is skipped because a constraint does not hold for GeometricNode.";
			return false;
		}
		if (!checkConstraint(*it, shapeType, 0, 0, lod, assignedId, attributes)) {
			LOG(DEBUG) << "GraphConstraintUpdateFilter::addGeometricNode is skipped because a constraint does not hold for Shape type " << shapeType << ".";
			return false;
		}
	}

	/* Memorize last invocation */
	lastSendType[shapeType] = wm->now();
	lastSendType[GraphConstraint::GeometricNode] = wm->now();
	lastSendType[GraphConstraint::Atom] = wm->now();

	/* Inform related observer(s) */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->addGeometricNode(parentId, assignedId, attributes, shape, timeStamp, forcedId);
	}
	return success;
}

bool GraphConstraintUpdateFilter::addRemoteRootNode(Id rootId, vector<Attribute> attributes) {
	bool success = true;

	/* THIS MUST NOT BE FILTERED */

	/* Call _all_ observers  */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->addRemoteRootNode(rootId, attributes);
	}

	return success;
}

bool GraphConstraintUpdateFilter::addConnection(Id parentId, Id& assignedId, vector<Attribute> attributes, vector<Id> sourceIds, vector<Id> targetIds, TimeStamp start, TimeStamp end, bool forcedId) {
	bool success = true;

	std::vector<GraphConstraint>::iterator it;
	for (it = constraints.begin(); it != constraints.end(); ++it) {
		if (!checkConstraint(*it, GraphConstraint::Connection, 0, 0, 0, assignedId, attributes)) {
			LOG(DEBUG) << "GraphConstraintUpdateFilter::addConnection is skipped because a constraint does not hold.";
			return false;
		}
	}

	/* Memorize last invocation */
	lastSendType[GraphConstraint::Connection] = wm->now();
	lastSendType[GraphConstraint::Atom] = wm->now();

	/* Call _all_ observers  */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->addConnection(parentId, assignedId, attributes, sourceIds, targetIds, start, end, forcedId);
	}
	return success;
}

bool GraphConstraintUpdateFilter::setNodeAttributes(Id id,
		vector<Attribute> newAttributes, TimeStamp timeStamp) {
	bool success = true;

	/* Check if new constraints are set via Attributes for the root node */
	if( id == wm->getRootNodeId()) {
		LOG(DEBUG) << "GraphConstraintUpdateFilter::setNodeAttributes: A change of root node attributes is detected. Updating graph constriants.";
		getConstraintsFromAttributes(newAttributes, this->constraints);
	}

	/* NOTE: here we check the _existing_ attributes to be consistent with other update functions. Not the new ones. */
	vector<Attribute> attributes;
	if(!wm->scene.getNodeAttributes(id, attributes)) {
		LOG(ERROR) << "GraphConstraintUpdateFilter:setNodeAttributes cannot query existing attributes for id " << id << " Skipping update.";
		return false;
	}

	std::vector<GraphConstraint>::iterator it;
	for (it = constraints.begin(); it != constraints.end(); ++it) {
		if (!checkConstraint(*it, GraphConstraint::Atom, 0, 0, 0, id, attributes)) { // assignedID?
			LOG(DEBUG) << "GraphConstraintUpdateFilter::setNodeAttributes is skipped because a constraint does not hold.";
			return false;
		}
	}

	/* Call _all_ observers  */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->setNodeAttributes(id, newAttributes, timeStamp);
	}
	return success;
}

bool GraphConstraintUpdateFilter::setTransform(Id id,
		IHomogeneousMatrix44::IHomogeneousMatrix44Ptr transform,
		TimeStamp timeStamp) {
	bool success = true;

	vector<Attribute> attributes;
	if(!wm->scene.getNodeAttributes(id, attributes)) {
		LOG(ERROR) << "semanticContextUpdateFilter:setTransform cannot query existing attributes for id " << id << " Skipping update.";
		return false;
	}

	std::vector<GraphConstraint>::iterator it;
	for (it = constraints.begin(); it != constraints.end(); ++it) {
		if (!checkConstraint(*it, GraphConstraint::TransformUpdate, 0, 0, 0, id, attributes)) { // assignedID?
			LOG(DEBUG) << "GraphConstraintUpdateFilter::setTransform is skipped because a constraint does not hold.";
			return false;
		}
	}

	/* Memorize last invocation */
	lastSendType[GraphConstraint::TransformUpdate] = wm->now();

	/* Inform related observer(s) */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->setTransform(id, transform, timeStamp);
	}
	return success;
}

bool GraphConstraintUpdateFilter::setUncertainTransform(Id id,
		IHomogeneousMatrix44::IHomogeneousMatrix44Ptr transform,
		ITransformUncertainty::ITransformUncertaintyPtr uncertainty,
		TimeStamp timeStamp) {
	bool success = true;

	vector<Attribute> attributes;
	if(!wm->scene.getNodeAttributes(id, attributes)) {
		LOG(ERROR) << "semanticContextUpdateFilter:setUncertainTransform cannot query existing attributes for id " << id << " Skipping update.";
		return false;
	}

	std::vector<GraphConstraint>::iterator it;
	for (it = constraints.begin(); it != constraints.end(); ++it) {
		if (!checkConstraint(*it, GraphConstraint::TransformUpdate, 0, 0, 0, id, attributes)) { // assignedID?
			LOG(DEBUG) << "GraphConstraintUpdateFilter::setUncertainTransform is skipped because a constraint does not hold.";
			return false;
		}
	}

	/* Memorize last invocation */
	lastSendType[GraphConstraint::TransformUpdate] = wm->now();

	/* Inform related observer(s) */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->setUncertainTransform(id, transform, uncertainty, timeStamp);
	}
	return success;
}

bool GraphConstraintUpdateFilter::deleteNode(Id id) {
	bool success = true;

	/*
	 *  This cannot be constrained, because we cannot make queries on it: it does not exist any more...
	 */

	/* Call _all_ observers  */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->deleteNode(id);
	}
	return success;
}

bool GraphConstraintUpdateFilter::addParent(Id id, Id parentId) {
	bool success = true;

	vector<Attribute> attributes;
	if(!wm->scene.getNodeAttributes(id, attributes)) {
		LOG(ERROR) << "semanticContextUpdateFilter:addParent cannot query existing attributes for id " << id << " Skipping update.";
		return false;
	}

	std::vector<GraphConstraint>::iterator it;
	for (it = constraints.begin(); it != constraints.end(); ++it) {
		if (!checkConstraint(*it, GraphConstraint::Atom, 0, 0, 0, id, attributes)) { // assignedID?
			LOG(DEBUG) << "GraphConstraintUpdateFilter::addParent is skipped because a constraint does not hold.";
			return false;
		}
	}

	/* Call _all_ observers  */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->addParent(id, parentId);
	}
	return success;
}

bool GraphConstraintUpdateFilter::removeParent(Id id, Id parentId) {
	bool success = true;

	vector<Attribute> attributes;
	if(!wm->scene.getNodeAttributes(id, attributes)) {
		LOG(ERROR) << "semanticContextUpdateFilter:removeParent cannot query existing attributes for id " << id << " Skipping update.";
		return false;
	}

	std::vector<GraphConstraint>::iterator it;
	for (it = constraints.begin(); it != constraints.end(); ++it) {
		if (!checkConstraint(*it, GraphConstraint::Atom, 0, 0, 0, id, attributes)) { // assignedID?
			LOG(DEBUG) << "GraphConstraintUpdateFilter::removeParent is skipped because a constraint does not hold.";
			return false;
		}
	}

	/* Call _all_ observers  */
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator;
	for (observerIterator = updateObservers.begin(); observerIterator != updateObservers.end(); ++observerIterator) {
		success &= (*observerIterator)->removeParent(id, parentId);
	}
	return success;
}

bool GraphConstraintUpdateFilter::attachUpdateObserver(
		ISceneGraphUpdateObserver* observer) {
	assert(observer != 0);
	updateObservers.push_back(observer);
	return true;
}

bool GraphConstraintUpdateFilter::detachUpdateObserver(
		ISceneGraphUpdateObserver* observer) {

	assert(observer != 0);
	std::vector<ISceneGraphUpdateObserver*>::iterator observerIterator = std::find(updateObservers.begin(), updateObservers.end(), observer);
    if (observerIterator!=updateObservers.end()) {
    	updateObservers.erase(observerIterator);
    	return true;
    }
    LOG(ERROR) << "Cannot detach update observer. Provided reference does not match with any in the observers list.";
	return false;
}

const string& GraphConstraintUpdateFilter::getNameSpaceIdentifier() const {
	return nameSpaceIdentifier;
}

void GraphConstraintUpdateFilter::setNameSpaceIdentifier(
		const string& nameSpaceIdentifier) {
	this->nameSpaceIdentifier = nameSpaceIdentifier;
	this->query =  "^"  + nameSpaceIdentifier + ":.*"; // wildcard = ^.*
}

bool GraphConstraintUpdateFilter::checkConstraint(GraphConstraint constraint,
		GraphConstraint::Type type, double frequencyInHz, double distanceInMeters,
		double lod, Id assignedId, vector<Attribute> attributes) {

	//GraphConstraint::Type type = GraphConstraint::Node;
	double allowedFrequencyInHz = 0.0;
	double allowedDistanceInMeters = 0.0;
	double allowedLod = 0.0;
	Id referenceNode;
	HomogeneousMatrix44::IHomogeneousMatrix44Ptr tf;
	SubGraphChecker subGraph(assignedId);
	bool isContainedIn = false;
	string query = "*";

	/*
	 * Does the constraint apply at all based on the SENDER or RECEIVER mode?
	 */
	switch (mode) {
		case SENDER:

			/* check if it applies to sender */
			if(constraint.action != GraphConstraint::SEND) {
				return true; // this constraint does not apply at all
				break;
			}
			break;

		case RECEIVER:

			/* check if it applies to sender */
			if(constraint.action != GraphConstraint::RECEIVE) {
				return true; // this constraint does not apply at all
				break;
			}
			break;

		default:
			LOG(ERROR) << "GraphConstraintUpdateFilter:checkConstraint is false because the I/O mode is undefined.";
			return false;
			break;
	}

	/*
	 * Continue with the actual constraint evaluation
	 */
	switch (constraint.nodeConstraint) {

		/* simple constraints first */
		case GraphConstraint::NONE:

			if( (constraint.qualifier == GraphConstraint::NO) && (constraint.type == type) ) {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint creation is false because no types " << type << " are allowed";
				return false;
			} else if( (constraint.qualifier == GraphConstraint::NO) && (constraint.type == GraphConstraint::Atom) ) {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint creation is false because no types " << GraphConstraint::Atom << " are allowed";
				return false;
			} else if( (constraint.qualifier == GraphConstraint::ONLY) && (constraint.type == GraphConstraint::Atom) ) {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint creation is true because all types, even " << type << " are allowed";
				return true;
			} else if( (constraint.qualifier == GraphConstraint::ONLY) && (constraint.type != type) ) {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint creation is false because only types " << type << " are allowed";
				return false;
			}

			break;

		/* complex constraints */
		/*
		 * (( with freq (<|=|>) [0-9]+ (Hz|kHz))|\
		 *  ( with lod (<|=|>) [0-9]+)|\
		 *  ( with dist (<|=|>) [0-9]+ (mm|cm|m|km) from (me|([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}))|\
		 *  ( from context [a-zA-Z0-9]+)|\
		 *  ( contained in ([a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}))
		 */
		case GraphConstraint::FREQUENCY:

			frequencyInHz = 1.0/(wm->now() - lastSendType[constraint.type]).getSeconds();
			allowedFrequencyInHz = Units::frequencyToHertz(constraint.value, constraint.freqUnit); // convert Hz to seconds.

			return checkComparision(constraint, type, frequencyInHz, allowedFrequencyInHz, "frequency");

			break;

		case GraphConstraint::LOD:

			// only applies to geometric nodes
			allowedLod = constraint.value;
			return checkComparision(constraint, type, lod, allowedLod, "lod");

			break;

		case GraphConstraint::DISTANCE:

			/* get reference node */
			if(constraint.isMe) {
				referenceNode = wm->getRootNodeId();
			} else {
				referenceNode = constraint.node;
			}

			/* compute distance */
			if(!wm->scene.getTransformForNode(assignedId, referenceNode, wm->now(), tf)) { // TODO find a way for to get the distance for non existing nodes (e.g. parent)
				LOG(WARNING) << "GraphConstraintUpdateFilter:checkConstraint is false because the distance between two nodes could not been derived.";
						return false;
			}
			HomogeneousMatrix44::matrixToDistance(tf, distanceInMeters); // in meters ?!?

			/* check it */
			allowedDistanceInMeters = Units::distanceToMeters(constraint.value, constraint.distUnit);
			return checkComparision(constraint, type, distanceInMeters, allowedDistanceInMeters, "distance");

			break;

		case GraphConstraint::CONTEXT:

			query =  "^"  + constraint.context + ":.*"; // wildcard = ^.*
			if(constraint.qualifier == GraphConstraint::ONLY) {

				if (attributeListContainsAttribute(attributes, Attribute(query, "*"))) {
					LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint is true because attributes contain (only) (" << constraint.context << ", *)";
					return true;
				} else {
					LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint is false because attributes do not contain (only) (" << constraint.context << ", *)";
					return false;
				}

			} else if (constraint.qualifier == GraphConstraint::NO) {

				if (attributeListContainsAttribute(attributes, Attribute(query, "*"))) {
					LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint is false because attributes contain (no) (" << constraint.context << ", *)";
					return false;
				} else {
					LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint is true because attributes do not contain (no) (" << constraint.context << ", *)";
					return true;
				}

			}

			break;

		case GraphConstraint::CONTAINMENT:

			/* get reference node */
			if(constraint.isMe) {
				referenceNode = wm->getRootNodeId();
			} else {
				referenceNode = constraint.node;
			}

			subGraph.reset(referenceNode); // NOTE: upwards traversal
			wm->scene.executeGraphTraverser(&subGraph, assignedId);
			isContainedIn = subGraph.nodeIsInSubGraph();

			if(constraint.qualifier == GraphConstraint::ONLY) {

				if (isContainedIn) {
					LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint is true because node is contained in " << referenceNode;
					return true;
				} else {
					LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint is false because node is not contained in " << referenceNode;
					return false;
				}

			} else if (constraint.qualifier == GraphConstraint::NO) {

				if (isContainedIn) {
					LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint is false because node is contained in " << referenceNode << " although it should not.";
					return false;
				} else {
					LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint is true because node is not contained in " << referenceNode << " as it should.";
					return true;
				}

			}

			break;

		case GraphConstraint::UNDEFINED_NODE_CONSTRAINT:

			LOG(DEBUG) << "GraphConstraintUpdateFilter:checkConstraint is false because the nodeConstraint is undefined. Do you actually mean NONE instead?";
			break;

		default:

			break;

	}

	return true;
}

bool GraphConstraintUpdateFilter::checkComparision(GraphConstraint constraint, GraphConstraint::Type type, double value, double allowedValue, string tag) {

	// NO
	if( 	((constraint.qualifier == GraphConstraint::NO) && (constraint.type == type)) ||
			((constraint.qualifier == GraphConstraint::NO) && (constraint.type == GraphConstraint::Atom)) ) {

		switch (constraint.comparision) {
		case GraphConstraint::EQ:
			if(value == allowedValue) {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is false because no types "
						<< constraint.type << " with " << tag <<" " << value << " == " << allowedValue <<" are allowed";
				return false;
			} else {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is true because types "
						<< constraint.type << " with " << tag <<" " << value << " == " << allowedValue <<" are allowed";
				return true;
			}

			break;

		case GraphConstraint::LT:
			if(value < allowedValue) {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is false because no types "
						<< constraint.type << " with " << tag <<" " << value << " < " << allowedValue <<" are allowed";
				return false;
			} else {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is true because types "
						<< constraint.type << " with " << tag <<" " << value << " > " << allowedValue <<" are allowed";
				return true;
			}

			break;

		case GraphConstraint::GT:
			if(value > allowedValue) {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is false because no types "
						<< constraint.type << " with " << tag <<" " << value << " > " << allowedValue <<" are allowed";
				return false;
			} else {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is true because types "
						<< constraint.type << " with " << tag <<" " << value << " < " << allowedValue <<" are allowed";
				return true;
			}

			break;

		case GraphConstraint::UNDEFINED_OPERATOR:
			LOG(ERROR) << "GraphConstraintUpdateFilter:checkComparision is false due to an undefined operator in a " << tag << " constraint.";
			return false;

		default:

			LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is true because types "
			<< constraint.type << " with " << tag <<" " << value << " of " << allowedValue <<" are allowed";
			return true;
		}

	// ONLY
	} else if( ((constraint.qualifier == GraphConstraint::ONLY) && (constraint.type == type)) ||
			    ((constraint.qualifier == GraphConstraint::ONLY) && (constraint.type == GraphConstraint::Atom)) ) {

		switch (constraint.comparision) {
		case GraphConstraint::EQ:
			if(value == allowedValue) {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is true because only types "
						<< constraint.type << " with " << tag <<" " << value << " == " << allowedValue <<" are allowed.";
				return true;
			}
			break;
		case GraphConstraint::LT:
			if(value < allowedValue) {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is true because only types "
						<< constraint.type << " with " << tag <<" " << value << " < " << allowedValue <<" are allowed.";
				return true;
			}

			break;
		case GraphConstraint::GT:
			if(value > allowedValue) {
				LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is true because only types "
						<< constraint.type << " with " << tag <<" " << value << " > " << allowedValue <<" are allowed.";
				return true;
			}
			break;

		case GraphConstraint::UNDEFINED_OPERATOR:
			LOG(ERROR) << "GraphConstraintUpdateFilter:checkComparision is false due to an undefined operator in a " << tag << " constraint.";
			return false;

		default:

			LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is false because types "
			<< constraint.type << " with " << tag <<" " << value << " of " << allowedValue <<" not allowed";
			return false;

		}

	} else if( (constraint.qualifier == GraphConstraint::ONLY) && (constraint.type != type)) { // ONLY and not the above cased
		LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is true because this type "
				<< type   << " is not considered in a this (ONLY) constraint "
				<< constraint.type << " with " << tag <<" " << value << " <|=|> " << allowedValue;
		return true;

	} else if( constraint.qualifier == GraphConstraint::NO) { // NO and not the above cased
		LOG(DEBUG) << "GraphConstraintUpdateFilter:checkComparision is true because this type "
				<< type   << " is not considered in a this (NO) constraint "
				<< constraint.type << " with " << tag <<" " << value << " <|=|> " << allowedValue;
		return true;
	}

	LOG(ERROR) << "GraphConstraintUpdateFilter:checkComparision is false because no other rule applied to type "
			<< constraint.type << " with " << tag <<" " << value << " <|=|> " << allowedValue;
	return false;
}

bool GraphConstraintUpdateFilter::getConstraintsFromAttributes(vector<Attribute> attributes, std::vector<GraphConstraint>& constraints) {

	vector<std::string> constraintModels;
	if(getValuesFromAttributeList(attributes, contraintKey, constraintModels)) {

		/* At least one found constraint. We do not know,
		 * if they are valid yet, but we assume the system
		 * is is supposed to try change its constraint set. */
		LOG(INFO) << "GraphConstraintUpdateFilter: Resetting graph constraints.";
		constraints.clear();

		std::vector<string>::iterator it;
		for (it = constraintModels.begin(); it != constraintModels.end(); ++it) {
			GraphConstraint c;
			if(c.parse(*it)) { // only put valid constraints
				constraints.push_back(c);
				LOG(INFO) << "GraphConstraintUpdateFilter:\t New graph constraints added: " << *it;
			} else {
				LOG(WARNING) << "GraphConstraintUpdateFilter:\t Invalid graph constraint: " << *it << " skipping it.";
			}
		}
	}

	return true;
}

} /* namespace rsg */
} /* namespace brics_3d */

/* EOF */


text:
#[=======================================================================[.rst:
FindHg
------

Extract information from a mercurial working copy.

The module defines the following variables:

::

   HG_EXECUTABLE - path to mercurial command line client (hg)
   HG_FOUND - true if the command line client was found
   HG_VERSION_STRING - the version of mercurial found

If the command line client executable is found the following macro is defined:

::

  HG_WC_INFO(<dir> <var-prefix>)

Hg_WC_INFO extracts information of a mercurial working copy
at a given location.  This macro defines the following variables:

::

  <var-prefix>_WC_CHANGESET - current changeset
  <var-prefix>_WC_REVISION - current revision

Example usage:

::

   find_package(Hg)
   if(HG_FOUND)
     message("hg found: ${HG_EXECUTABLE}")
     HG_WC_INFO(${PROJECT_SOURCE_DIR} Project)
     message("Current revision is ${Project_WC_REVISION}")
     message("Current changeset is ${Project_WC_CHANGESET}")
   endif()
#]=======================================================================]

find_program(HG_EXECUTABLE
  NAMES hg
  PATHS
    [HKEY_LOCAL_MACHINE\\Software\\TortoiseHG]
  PATH_SUFFIXES Mercurial
  DOC "hg command line client"
  )
mark_as_advanced(HG_EXECUTABLE)

if(HG_EXECUTABLE)
  set(_saved_lc_all "$ENV{LC_ALL}")
  set(ENV{LC_ALL} "C")

  set(_saved_language "$ENV{LANGUAGE}")
  set(ENV{LANGUAGE})

  execute_process(COMMAND ${HG_EXECUTABLE} --version
                  OUTPUT_VARIABLE hg_version
                  ERROR_QUIET
                  RESULT_VARIABLE hg_result
                  OUTPUT_STRIP_TRAILING_WHITESPACE)

  set(ENV{LC_ALL} ${_saved_lc_all})
  set(ENV{LANGUAGE} ${_saved_language})

  if(hg_result MATCHES "is not a valid Win32 application")
    set_property(CACHE HG_EXECUTABLE PROPERTY VALUE "HG_EXECUTABLE-NOTFOUND")
  endif()
  if(hg_version MATCHES "^Mercurial Distributed SCM \\(version ([0-9][^)]*)\\)")
    set(HG_VERSION_STRING "${CMAKE_MATCH_1}")
  endif()
  unset(hg_version)

  macro(HG_WC_INFO dir prefix)
    execute_process(COMMAND ${HG_EXECUTABLE} id -i -n
      WORKING_DIRECTORY ${dir}
      RESULT_VARIABLE hg_id_result
      ERROR_VARIABLE hg_id_error
      OUTPUT_VARIABLE ${prefix}_WC_DATA
      OUTPUT_STRIP_TRAILING_WHITESPACE)
    if(NOT ${hg_id_result} EQUAL 0)
      message(SEND_ERROR "Command \"${HG_EXECUTBALE} id -n\" in directory ${dir} failed with output:\n${hg_id_error}")
    endif()

    string(REGEX REPLACE "([0-9a-f]+)\\+? [0-9]+\\+?" "\\1" ${prefix}_WC_CHANGESET ${${prefix}_WC_DATA})
    string(REGEX REPLACE "[0-9a-f]+\\+? ([0-9]+)\\+?" "\\1" ${prefix}_WC_REVISION ${${prefix}_WC_DATA})
  endmacro(HG_WC_INFO)
endif()

include(${CMAKE_CURRENT_LIST_DIR}/FindPackageHandleStandardArgs.cmake)
find_package_handle_standard_args(Hg
                                  REQUIRED_VARS HG_EXECUTABLE
                                  VERSION_VAR HG_VERSION_STRING)

redpajama_set_name: RedPajamaGithub


text:
package com.airbnb.chancery.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class RateLimitStats {
	@JsonProperty
	int limit;
	@JsonProperty
	int remaining;

	@Data
	public static class Container {
		@JsonProperty
		RateLimitStats rate;
	}
}


text:
package com.trigital.cm;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

public class CORSFilter implements Filter {

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
                HttpServletRequest request= (HttpServletRequest) req;

                  response.setHeader("Access-Control-Allow-Origin", "*");
                  response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                  response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
                  response.setHeader("Access-Control-Expose-Headers", "x-requested-with"); chain.doFilter(req, res);
        }

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

describe "/tasks/new" do
  include TasksHelper

  before do
    login_and_assign
    assign(:task, FactoryGirl.build(:task))
    assign(:users, [ current_user ])
    assign(:bucket, Setting.task_bucket[1..-1] << [ "On Specific Date...", :specific_time ])
    assign(:category, Setting.unroll(:task_category))
  end

  it "should toggle empty message div if it exists" do
    render

    rendered.should include('crm.flick("empty", "toggle")')
  end

  describe "new task" do
    before { @task_with_time = Setting.task_calendar_with_time }
    after  { Setting.task_calendar_with_time = @task_with_time }

    it "create: should render [new] template into :create_task div" do
      params[:cancel] = nil
      render

      rendered.should have_rjs("create_task") do |rjs|
        with_tag("form[class=new_task]")
      end
      rendered.should include('crm.flip_form("create_task");')
    end
  end

  describe "cancel new task" do
    it "should hide [create task] form" do
      params[:cancel] = "true"
      render

      rendered.should_not have_rjs("create_task")
      rendered.should include('crm.flip_form("create_task");')
    end
  end

end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>base package — Nitro  documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="Nitro  documentation" href="index.html" />
    <link rel="next" title="Json module" href="nssrc.com.citrix.netscaler.nitro.resource.base.Json.html" />
    <link rel="prev" title="nitro_exception module" href="nssrc.com.citrix.netscaler.nitro.exception.nitro_exception.html" />

Navigation

          index

          next |

          previous |

Nitro  documentation »

base package¶

Subpackages¶

Json

base_resource

base_response

base_responses

configobjects

ipayload_formatter

login

loginchallengeresponse

logout

statobjects

Nitro exception Package

Base Package

Json

base_resource

base_response

base_responses

configobjects

ipayload_formatter

login

loginchallengeresponse

logout

statobjects

Service Package

Util Package

Config Package

Stat Package

Previous topic

nitro_exception module

Next topic

Json module

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

        © Copyright © 1999-2014 Citrix Systems, Inc. All Rights Reserved.
      Created using Sphinx 1.2.


text:
package com.flowpowered.commons;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class LogicUtil {
    /**
     * Removes duplicate values by using the objects' equals function<br> Note that this function does not use a Set, because no hashcode is used.
     *
     * @param input collection
     * @return the input collection
     */
    public static <T extends Collection<?>> T removeDuplicates(T input) {
        List<Object> unique = new ArrayList<>(input.size());
        for (Iterator<?> iter = input.iterator(); iter.hasNext(); ) {
            Object next = iter.next();
            if (unique.contains(next)) {
                iter.remove();
            } else {
                unique.add(next);
            }
        }
        return input;
    }

    /**
     * Checks if the object equals one of the other objects given
     *
     * @param object to check
     * @param objects to use equals against
     * @return True if one of the objects equal the object
     */
    public static <A, B> boolean equalsAny(A object, B... objects) {
        for (B o : objects) {
            if (bothNullOrEqual(o, object)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks if object a and b are both null or are equal
     *
     * @return if both null or equal
     */
    public static boolean bothNullOrEqual(Object a, Object b) {
        return (a == null || b == null) ? (a == b) : a.equals(b);
    }

    /**
     * Gets if a bit is set in an integer value
     *
     * @param value to get it of
     * @param bit to check
     * @return True if the bit is set
     */
    public static boolean getBit(int value, int bit) {
        return (value & bit) == bit;
    }

    /**
     * Sets a single bit in a byte value
     *
     * @param value to set a bit of
     * @param bit to set
     * @param state to enable or disable the bit
     * @return the resulting value
     */
    public static byte setBit(byte value, int bit, boolean state) {
        return (byte) setBit((int) value, bit, state);
    }

    /**
     * Sets a single bit in a short value
     *
     * @param value to set a bit of
     * @param bit to set
     * @param state to enable or disable the bit
     * @return the resulting value
     */
    public static short setBit(short value, int bit, boolean state) {
        return (short) setBit((int) value, bit, state);
    }

    /**
     * Sets a single bit in an integer value
     *
     * @param value to set a bit of
     * @param bit to set
     * @param state to enable or disable the bit
     * @return the resulting value
     */
    public static int setBit(int value, int bit, boolean state) {
        return state ? value | bit : value & ~bit;
    }
}


text:
#ifndef logging_h
#define logging_h

#ifdef _WIN32
 #pragma warning(push)
 #pragma warning(disable:4996 4717)
 #define fileno _fileno
 #define isatty _isatty
 #define lseek _lseek
 #ifdef _ftime
  #define ftime _ftime
 #endif
#endif

#ifdef unix
 #include <sys/types.h>
 #include <unistd.h>
 #include <stdlib.h>
#else
 #include <io.h>
 #include <comdef.h>
#endif
#include <stdio.h>
#include <sys/timeb.h>
#include <time.h>
#include <sstream>
#include <string>
#include <iostream>

template <class _LOGGER> class Logger {
 public:
  Logger() : fatal_(false) {}

  enum LogLevel {
    logFATAL = 0, logERROR, logWARN, logINFO, logDEBUG };

  ~Logger() {
    os_ << std::endl, _LOGGER::Log(os_.str(), fatal_);
    if (fatal_) {
      exit(EXIT_FAILURE);
    }
  }

  static void Level(const std::string& level) {
    if (Level() = logFATAL, level == "ERROR") {
      Level() = logERROR;
    } else if (level == "WARN" ) {
      Level() = logWARN;
    } else if (level == "INFO" ) {
      Level() = logINFO;
    } else if (level == "DEBUG") {
      Level() = logDEBUG;
    }
  }

  static LogLevel& Level() {
    static LogLevel level = logFATAL;  // off by default
    return level;
  }

  std::ostringstream& Stream(LogLevel level) {
    static char severity[] = { 'F', 'E', 'W', 'I', 'D' };
    os_ << severity[level] << Time();
    if (level == logFATAL)
      fatal_ = true, os_ << L"FATAL ";
    return os_;
  }

  static std::string Time() {
    struct timeb tb; ftime(&tb);

    char time[20];
    size_t length = strftime(time, sizeof(time), "%H:%M:%S:",
      localtime(reinterpret_cast<const time_t*>(&tb.time)));
    sprintf(time + length, "%03u ", tb.millitm);
    return time;
  }

 private:
  std::ostringstream os_;
  bool fatal_;
};

class LOG : public Logger<LOG> {
 public:
  static void File(const std::string& name, const char* openMode = "w") {
    const std::string& file = Name(name);
    if (file == "stdout") {
	  LOG::File() = stdout;
    } else if (file == "stderr") {
      LOG::File() = stderr;
    } else {
      LOG::File() = fopen(file.c_str(), openMode);
    }
  }

  static void Limit(off_t size) {
    LOG::Limit() = size;
  }

 private:
  static std::string& Name(const std::string& name) {
    static std::string file_name = "stdout";
    if (!name.empty())
      file_name.assign(name);
    return file_name;
  }

  static FILE*& File() {
    static FILE* file = stdout;
    return file;
  }

  static off_t& Limit() {
    static off_t size_limit = 0;
    return size_limit;
  }

  static void Log(const std::string& str, bool fatal) {
    if (fatal) Limit() = 0;

    FILE* output = File();
    if (output) {
      fwrite(str.data(), sizeof(char), str.size(), output);
      fflush(output);

      if (Limit() && !isatty(fileno(output))) {
        if (lseek(fileno(output), 0, SEEK_END) > Limit()) {
          fclose(output), File("");
        }
      }
    }

    if (fatal && !isatty(fileno(output))) {
      fputs(str.c_str(), stderr);
    }
  }

  friend class Logger<LOG>;
};

#ifdef _WIN32
 #pragma warning(pop)
#endif

#define LOG(LEVEL)                        \
  if (LOG::log ## LEVEL > LOG::Level()) ; \
  else LOG().Stream(LOG::log ## LEVEL) << __FILE__ << "(" << __LINE__ << ") " /* << stuff here */

#ifdef _WIN32
  #define LOGHR(LEVEL,HR) LOG( ## LEVEL) << HR<< " [" << (_bstr_t(_com_error((DWORD) HR).ErrorMessage())) << "]: "
#endif

#endif  // logging_h


text:
using System;
using System.Collections;
using System.Collections.Generic;

namespace Itenso.TimePeriod
{

	// ------------------------------------------------------------------------
	public class DateTimeSet : IDateTimeSet
	{

		// ----------------------------------------------------------------------
		public DateTimeSet()
		{
		} // DateTimeSet

		// ----------------------------------------------------------------------
		public DateTimeSet( IEnumerable<DateTime> moments )
		{
			AddAll( moments );
		} // DateTimeSet

		// ----------------------------------------------------------------------
		public DateTime this[ int index ]
		{
			get { return moments[ index ]; }
		} // this[]

		// ----------------------------------------------------------------------
		public DateTime? Min
		{
			get { return !IsEmpty ? moments[ 0 ] : (DateTime?)null; }
		} // Min

		// ----------------------------------------------------------------------
		public DateTime? Max
		{
			get { return !IsEmpty ? moments[ Count - 1 ] : (DateTime?)null; }
		} // Max

		// ----------------------------------------------------------------------
		public TimeSpan? Duration
		{
			get
			{
				DateTime? min = Min;
				DateTime? max = Max;
				return min.HasValue && max.HasValue ? max.Value - min.Value : (TimeSpan?)null;
			}
		} // Duration

		// ----------------------------------------------------------------------
		public bool IsEmpty
		{
			get { return Count == 0; }
		} // IsEmpty

		// ----------------------------------------------------------------------
		public bool IsMoment
		{
			get
			{
				TimeSpan? duration = Duration;
				return duration.HasValue && duration.Value == TimeSpan.Zero;
			}
		} // IsMoment

		// ----------------------------------------------------------------------
		public bool IsAnytime
		{
			get
			{
				DateTime? min = Min;
				DateTime? max = Max;
				return
					min.HasValue && min.Value == DateTime.MinValue &&
					max.HasValue && max.Value == DateTime.MaxValue;
			}
		} // IsAnytime

		// ----------------------------------------------------------------------
		public int Count
		{
			get { return moments.Count; }
		} // Count

		// ----------------------------------------------------------------------
		bool ICollection<DateTime>.IsReadOnly
		{
			get { return false; }
		} // ICollection<DateTime>.IsReadOnly

		// ----------------------------------------------------------------------
		public int IndexOf( DateTime moment )
		{
			return moments.IndexOf( moment );
		} // IndexOf

		// ----------------------------------------------------------------------
		public DateTime? FindPrevious( DateTime moment )
		{
			if ( IsEmpty )
			{
				return null;
			}

			for ( int i = Count - 1; i >= 0; i-- )
			{
				if ( moments[ i ] < moment )
				{
					return moments[ i ];
				}
			}

			return null;
		} // FindPrevious

		// ----------------------------------------------------------------------
		public DateTime? FindNext( DateTime moment )
		{
			if ( IsEmpty )
			{
				return null;
			}

			for ( int i = 0; i < Count; i++ )
			{
				if ( moments[ i ] > moment )
				{
					return moments[ i ];
				}
			}

			return null;
		} // FindNext

		// ----------------------------------------------------------------------
		public IEnumerator<DateTime> GetEnumerator()
		{
			return moments.GetEnumerator();
		} // GetEnumerator

		// ----------------------------------------------------------------------
		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		} // IEnumerable.GetEnumerator

		// ----------------------------------------------------------------------
		public bool Add( DateTime moment )
		{
			if ( Contains( moment ) )
			{
				return false;
			}

			for ( int i = 0; i < Count; i++ )
			{
				if ( moments[ i ] <= moment )
				{
					continue;
				}
				moments.Insert( i, moment );
				return true;
			}

			moments.Add( moment );
			return true;
		} // Add

		// ----------------------------------------------------------------------
		void ICollection<DateTime>.Add( DateTime moment )
		{
			Add( moment );
		} // Add

		// ----------------------------------------------------------------------
		public void AddAll( IEnumerable<DateTime> items )
		{
			if ( items == null )
			{
				throw new ArgumentNullException( "items" );
			}

			foreach ( DateTime item in items )
			{
				Add( item );
			}
		} // AddAll

		// ----------------------------------------------------------------------
		public IList<TimeSpan> GetDurations( int startIndex, int count )
		{
			if ( startIndex >= Count - 1 )
			{
				throw new ArgumentOutOfRangeException( "startIndex" );
			}
			if ( count <= 0 )
			{
				throw new ArgumentOutOfRangeException( "count" );
			}

			int endIndex = startIndex + count - 1;
			if ( endIndex >= Count - 1 )
			{
				endIndex = Count - 2;
			}

			List<TimeSpan> durations = new List<TimeSpan>();
			if ( endIndex >= startIndex )
			{
				for ( int i = startIndex; i <= endIndex; i++ )
				{
					durations.Add( this[ i + 1 ] - this[ i ] );
				}
			}
			return durations;
		} // GetDurations

		// ----------------------------------------------------------------------
		public void Clear()
		{
			moments.Clear();
		} // Clear

		// ----------------------------------------------------------------------
		public bool Contains( DateTime moment )
		{
			return moments.Contains( moment );
		} // Contains

		// ----------------------------------------------------------------------
		public void CopyTo( DateTime[] array, int arrayIndex )
		{
			moments.CopyTo( array, arrayIndex );
		} // CopyTo

		// ----------------------------------------------------------------------
		public bool Remove( DateTime moment )
		{
			return moments.Remove( moment );
		} // Remove

		// ----------------------------------------------------------------------
		public override bool Equals( object obj )
		{
			return moments.Equals( obj );
		} // Equals

		// ----------------------------------------------------------------------
		public override int GetHashCode()
		{
			return moments.GetHashCode();
		} // GetHashCode

		// ----------------------------------------------------------------------
		public override string ToString()
		{
			DateTime? min = Min;
			DateTime? max = Max;
			TimeSpan? duration = Duration;
			if ( !min.HasValue || !max.HasValue || !duration.HasValue )
			{
				return TimeFormatter.Instance.GetCollection( Count );
			}

			return TimeFormatter.Instance.GetCollectionPeriod( Count, min.Value, max.Value, duration.Value );
		} // ToString

		// ----------------------------------------------------------------------
		// members
		private readonly List<DateTime> moments = new List<DateTime>();

	} // class DateTimeSet

} // namespace Itenso.TimePeriod
// -- EOF -------------------------------------------------------------------


text:
package validate

import (
	"fmt"
	"net/netip"
	"reflect"
	"regexp"
	"strconv"
	"strings"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"sigs.k8s.io/yaml"

	"istio.io/istio/operator/pkg/apis/istio/v1alpha1"
	"istio.io/istio/operator/pkg/util"
	"istio.io/pkg/log"
)

var (
	scope = log.RegisterScope("validation", "API validation", 0)

	// alphaNumericRegexp defines the alpha numeric atom, typically a
	// component of names. This only allows lower case characters and digits.
	alphaNumericRegexp = match(`[a-z0-9]+`)

	// separatorRegexp defines the separators allowed to be embedded in name
	// components. This allow one period, one or two underscore and multiple
	// dashes.
	separatorRegexp = match(`(?:[._]|__|[-]*)`)

	// nameComponentRegexp restricts registry path component names to start
	// with at least one letter or number, with following parts able to be
	// separated by one period, one or two underscore and multiple dashes.
	nameComponentRegexp = expression(
		alphaNumericRegexp,
		optional(repeated(separatorRegexp, alphaNumericRegexp)))

	// domainComponentRegexp restricts the registry domain component of a
	// repository name to start with a component as defined by DomainRegexp
	// and followed by an optional port.
	domainComponentRegexp = match(`(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])`)

	// DomainRegexp defines the structure of potential domain components
	// that may be part of image names. This is purposely a subset of what is
	// allowed by DNS to ensure backwards compatibility with Docker image
	// names.
	DomainRegexp = expression(
		domainComponentRegexp,
		optional(repeated(literal(`.`), domainComponentRegexp)),
		optional(literal(`:`), match(`[0-9]+`)))

	// TagRegexp matches valid tag names. From docker/docker:graph/tags.go.
	TagRegexp = match(`[\w][\w.-]{0,127}`)

	// DigestRegexp matches valid digests.
	DigestRegexp = match(`[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}`)

	// NameRegexp is the format for the name component of references. The
	// regexp has capturing groups for the domain and name part omitting
	// the separating forward slash from either.
	NameRegexp = expression(
		optional(DomainRegexp, literal(`/`)),
		nameComponentRegexp,
		optional(repeated(literal(`/`), nameComponentRegexp)))

	// ReferenceRegexp is the full supported format of a reference. The regexp
	// is anchored and has capturing groups for name, tag, and digest
	// components.
	ReferenceRegexp = anchored(capture(NameRegexp),
		optional(literal(":"), capture(TagRegexp)),
		optional(literal("@"), capture(DigestRegexp)))

	// ObjectNameRegexp is a legal name for a k8s object.
	ObjectNameRegexp = match(`[a-z0-9.-]{1,254}`)
)

// validateWithRegex checks whether the given value matches the regexp r.
func validateWithRegex(path util.Path, val any, r *regexp.Regexp) (errs util.Errors) {
	valStr := fmt.Sprint(val)
	if len(r.FindString(valStr)) != len(valStr) {
		errs = util.AppendErr(errs, fmt.Errorf("invalid value %s: %v", path, val))
		printError(errs.ToError())
	}
	return errs
}

// validateStringList returns a validator function that works on a string list, using the supplied ValidatorFunc vf on
// each element.
func validateStringList(vf ValidatorFunc) ValidatorFunc {
	return func(path util.Path, val any) util.Errors {
		msg := fmt.Sprintf("validateStringList %v", val)
		if !util.IsString(val) {
			err := fmt.Errorf("validateStringList %s got %T, want string", path, val)
			printError(err)
			return util.NewErrs(err)
		}
		var errs util.Errors
		for _, s := range strings.Split(val.(string), ",") {
			errs = util.AppendErrs(errs, vf(path, strings.TrimSpace(s)))
			scope.Debugf("\nerrors(%d): %v", len(errs), errs)
			msg += fmt.Sprintf("\nerrors(%d): %v", len(errs), errs)
		}
		logWithError(errs.ToError(), msg)
		return errs
	}
}

// validatePortNumberString checks if val is a string with a valid port number.
func validatePortNumberString(path util.Path, val any) util.Errors {
	scope.Debugf("validatePortNumberString %v:", val)
	if !util.IsString(val) {
		return util.NewErrs(fmt.Errorf("validatePortNumberString(%s) bad type %T, want string", path, val))
	}
	if val.(string) == "*" || val.(string) == "" {
		return nil
	}
	intV, err := strconv.ParseInt(val.(string), 10, 32)
	if err != nil {
		return util.NewErrs(fmt.Errorf("%s : %s", path, err))
	}
	return validatePortNumber(path, intV)
}

// validatePortNumber checks whether val is an integer representing a valid port number.
func validatePortNumber(path util.Path, val any) util.Errors {
	return validateIntRange(path, val, 0, 65535)
}

// validateIPRangesOrStar validates IP ranges and also allow star, examples: "1.1.0.256/16,2.2.0.257/16", "*"
func validateIPRangesOrStar(path util.Path, val any) (errs util.Errors) {
	scope.Debugf("validateIPRangesOrStar at %v: %v", path, val)

	if !util.IsString(val) {
		err := fmt.Errorf("validateIPRangesOrStar %s got %T, want string", path, val)
		printError(err)
		return util.NewErrs(err)
	}

	if val.(string) == "*" || val.(string) == "" {
		return errs
	}

	return validateStringList(validateCIDR)(path, val)
}

// validateIntRange checks whether val is an integer in [min, max].
func validateIntRange(path util.Path, val any, min, max int64) util.Errors {
	k := reflect.TypeOf(val).Kind()
	var err error
	switch {
	case util.IsIntKind(k):
		v := reflect.ValueOf(val).Int()
		if v < min || v > max {
			err = fmt.Errorf("value %s:%v falls outside range [%v, %v]", path, v, min, max)
		}
	case util.IsUintKind(k):
		v := reflect.ValueOf(val).Uint()
		if int64(v) < min || int64(v) > max {
			err = fmt.Errorf("value %s:%v falls out side range [%v, %v]", path, v, min, max)
		}
	default:
		err = fmt.Errorf("validateIntRange %s unexpected type %T, want int type", path, val)
	}
	logWithError(err, "validateIntRange %s:%v in [%d, %d]?: ", path, val, min, max)
	return util.NewErrs(err)
}

// validateCIDR checks whether val is a string with a valid CIDR.
func validateCIDR(path util.Path, val any) util.Errors {
	var err error
	if !util.IsString(val) {
		err = fmt.Errorf("validateCIDR %s got %T, want string", path, val)
	} else {
		if _, err = netip.ParsePrefix(val.(string)); err != nil {
			err = fmt.Errorf("%s %s", path, err)
		}
	}
	logWithError(err, "validateCIDR (%s): ", val)
	return util.NewErrs(err)
}

func printError(err error) {
	if err == nil {
		scope.Debug("OK")
		return
	}
	scope.Debugf("%v", err)
}

// logWithError prints debug log with err message
func logWithError(err error, format string, args ...any) {
	msg := fmt.Sprintf(format, args...)
	if err == nil {
		msg += ": OK\n"
	} else {
		msg += fmt.Sprintf(": %v\n", err)
	}
	scope.Debug(msg)
}

// match compiles the string to a regular expression.
var match = regexp.MustCompile

// literal compiles s into a literal regular expression, escaping any regexp
// reserved characters.
func literal(s string) *regexp.Regexp {
	re := match(regexp.QuoteMeta(s))

	if _, complete := re.LiteralPrefix(); !complete {
		panic("must be a literal")
	}

	return re
}

// expression defines a full expression, where each regular expression must
// follow the previous.
func expression(res ...*regexp.Regexp) *regexp.Regexp {
	var s string
	for _, re := range res {
		s += re.String()
	}

	return match(s)
}

// optional wraps the expression in a non-capturing group and makes the
// production optional.
func optional(res ...*regexp.Regexp) *regexp.Regexp {
	return match(group(expression(res...)).String() + `?`)
}

// repeated wraps the regexp in a non-capturing group to get one or more
// matches.
func repeated(res ...*regexp.Regexp) *regexp.Regexp {
	return match(group(expression(res...)).String() + `+`)
}

// group wraps the regexp in a non-capturing group.
func group(res ...*regexp.Regexp) *regexp.Regexp {
	return match(`(?:` + expression(res...).String() + `)`)
}

// capture wraps the expression in a capturing group.
func capture(res ...*regexp.Regexp) *regexp.Regexp {
	return match(`(` + expression(res...).String() + `)`)
}

// anchored anchors the regular expression by adding start and end delimiters.
func anchored(res ...*regexp.Regexp) *regexp.Regexp {
	return match(`^` + expression(res...).String() + `$`)
}

// ValidatorFunc validates a value.
type ValidatorFunc func(path util.Path, i any) util.Errors

// UnmarshalIOP unmarshals a string containing IstioOperator as YAML.
func UnmarshalIOP(iopYAML string) (*v1alpha1.IstioOperator, error) {
	// Remove creationDate (util.UnmarshalWithJSONPB fails if present)
	mapIOP := make(map[string]any)
	if err := yaml.Unmarshal([]byte(iopYAML), &mapIOP); err != nil {
		return nil, err
	}
	// Don't bother trying to remove the timestamp if there are no fields.
	// This also preserves iopYAML if it is ""; we don't want iopYAML to be the string "null"
	if len(mapIOP) > 0 {
		un := &unstructured.Unstructured{Object: mapIOP}
		un.SetCreationTimestamp(metav1.Time{}) // UnmarshalIstioOperator chokes on these
		iopYAML = util.ToYAML(un)
	}
	iop := &v1alpha1.IstioOperator{}

	if err := yaml.UnmarshalStrict([]byte(iopYAML), iop); err != nil {
		return nil, fmt.Errorf("%s:\n\nYAML:\n%s", err, iopYAML)
	}
	return iop, nil
}

// ValidIOP validates the given IstioOperator object.
func ValidIOP(iop *v1alpha1.IstioOperator) error {
	errs := CheckIstioOperatorSpec(iop.Spec, false)
	return errs.ToError()
}

// compose path for slice s with index i
func indexPathForSlice(s string, i int) string {
	return fmt.Sprintf("%s[%d]", s, i)
}

// get validation function for specified path
func getValidationFuncForPath(validations map[string]ValidatorFunc, path util.Path) (ValidatorFunc, bool) {
	pstr := path.String()
	// fast match
	if !strings.Contains(pstr, "[") && !strings.Contains(pstr, "]") {
		vf, ok := validations[pstr]
		return vf, ok
	}
	for p, vf := range validations {
		ps := strings.Split(p, ".")
		if len(ps) != len(path) {
			continue
		}
		for i, v := range ps {
			if !matchPathNode(v, path[i]) {
				break
			}
			if i == len(ps)-1 {
				return vf, true
			}
		}
	}
	return nil, false
}

// check whether the pn path node match pattern.
// pattern may container '*', eg. [1] match [*].
func matchPathNode(pattern, pn string) bool {
	if !strings.Contains(pattern, "[") && !strings.Contains(pattern, "]") {
		return pattern == pn
	}
	if !strings.Contains(pn, "[") && !strings.Contains(pn, "]") {
		return false
	}
	indexPattern := pattern[strings.IndexByte(pattern, '[')+1 : strings.IndexByte(pattern, ']')]
	if indexPattern == "*" {
		return true
	}
	index := pn[strings.IndexByte(pn, '[')+1 : strings.IndexByte(pn, ']')]
	return indexPattern == index
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import django.contrib.gis.db.models.fields
import django.core.validators
import re

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Postcode',
            fields=[
                ('code', models.CharField(max_length=6, primary_key=True, validators=[django.core.validators.RegexValidator(re.compile('^[ABCEGHJKLMNPRSTVXY]\\d[ABCEGHJKLMNPRSTVWXYZ]\\d[ABCEGHJKLMNPRSTVWXYZ]\\d$', 32))], serialize=False)),
                ('centroid', django.contrib.gis.db.models.fields.PointField(blank=True, srid=4326, null=True)),
                ('city', models.CharField(max_length=100, blank=True)),
                ('province', models.CharField(max_length=2, blank=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='PostcodeConcordance',
            fields=[
                ('id', models.AutoField(primary_key=True, verbose_name='ID', serialize=False, auto_created=True)),
                ('boundary', models.TextField()),
                ('source', models.CharField(help_text='A description of the data source.', max_length=30)),
                ('code', models.ForeignKey(to='postcodes.Postcode')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AlterUniqueTogether(
            name='postcodeconcordance',
            unique_together=set([('code', 'boundary')]),
        ),
    ]


text:
package eu.verdelhan.bitraac.indicators;

import eu.verdelhan.bitraac.data.Period;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.Validate;

/**
 * Moving average convergence divergence (MACD) indicator.
 */
public class MACD implements Indicator<BigDecimal> {

    private ArrayList<Period> periods;

    private int shortTermEmaNbPeriods;

    /**
     * @param periods the list of periods
     * @param shortTermEmaNbPeriods the number of periods to use (i.e. the n last periods) for short term EMA computation (e.g. 12)
     * @param longTermEmaNbPeriods the number of periods to use (i.e. the n last periods) for long term EMA computation (e.g. 26)
     */
    public MACD(final List<Period> periods, int shortTermEmaNbPeriods, int longTermEmaNbPeriods) {
        Validate.noNullElements(periods, "List of periods is null or contains null periods");
        final int nbPeriods = periods.size();
        if (longTermEmaNbPeriods > nbPeriods) {
            throw new IllegalArgumentException("Not enough periods");
        }
        if (shortTermEmaNbPeriods > longTermEmaNbPeriods) {
            throw new IllegalArgumentException("Long term period count must be greater than short term period count");
        }
        this.periods = new ArrayList<Period>(periods.subList(nbPeriods - longTermEmaNbPeriods, nbPeriods));
        this.shortTermEmaNbPeriods = shortTermEmaNbPeriods;
    }

    /**
     * @return the MACD indicator
     */
    @Override
    public BigDecimal execute() {
        // Computing exponential moving averages
        BigDecimal shortTermEma = new EMA(periods, shortTermEmaNbPeriods).execute();
        BigDecimal longTermEma = new EMA(periods, periods.size()).execute();

        return shortTermEma.subtract(longTermEma);
    }
}


text:
module GooglePubsubEnhancer::Constants
    MAX_PULL_SIZE = proc do
        user_defined = ::ENV['GOOGLE_PUBSUB_ENHANCER_MAX_PULL_SIZE']
        pull_size = (user_defined || 100).to_i
        raise('GOOGLE_PUBSUB_ENHANCER_MAX_PULL_SIZE') if pull_size == 0
        pull_size
    end.call.freeze
end


text:
package com.linkedin.pinot.core.trace;

import java.util.concurrent.ConcurrentLinkedDeque;

public class TraceUtils {
    /**
     * Expects a TreeNode collection where each node points to its parent.
     * Builds the full tree and returns the root (which has to have a
     * null parent).
     */
    private static Trace linkToTree(Iterable<Trace> nodes) {
        Trace root = null;

        for (Trace node : nodes) {
            final Trace parent = node._parent;

            // try to detect the root node
            if (parent == null) {
                root = node;
            }
            // add this node to the parent's left slot if it's empty
            else {
                parent._children.add(node);
            }
        }

        return root;
    }

    /**
     * TODO: it is a malformed json, fix it.
     * @param deque
     * @return
     */
    public static String getTraceTree(ConcurrentLinkedDeque<Trace> deque) {
        StringBuilder sb = new StringBuilder();
        sb.append("\n");
        linkToTree(deque).getTraceTree(sb, 0);
        return sb.toString();
    }

    public static String getTraceString(ConcurrentLinkedDeque<Trace> deque) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        int cnt = 0;
        for (Trace trace: deque) {
            if (cnt > 0) {
                sb.append(", ");
            }
            sb.append(trace.toString());
            cnt += 1;
        }
        sb.append("]");
        return sb.toString();
    }
}


text:
import { Component } from '@angular/core';
import {RecipesService} from "./services/recipes.service";
import {Observable} from "rxjs";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public recipes:any=[]
  public options:any={}
  public tableMessages:any=[]
  public timer:any
  constructor(private recipesService:RecipesService){}
  ngOnInit(){
    this.options={
      debug: true,
      blankLabel: 'n/a',
      outer_form: 'both',
      add:{
        display:true,
        caption: 'both',// head, title, both
        show: false
      },
      editable: {
        display: true,
        show: true,
        delete: true,
        batch: false,
      },
      columns:[
        {
          name: "Nombre",
          type: 'string',
          validators:{
            required: false,
            min: 2,
            max: 50
          }
        },
        {
          calories: "Calorias",
          type: 'string',
          validators:{
            required: false,
            min: 2,
            pattern: "^(0|[1-9][0-9]*\w*kcal)$"
          }
        },
        {
          carbos: "Carbohidratos",
          type: 'string',
          validators:{
            required: false
          }
        },
        {
          favorites: "Favoritos",
          type: 'number',
          validators:{
            required: false,
            min: 0,
            max: 20
          }
        },
        {dressing: "Aderezo", type: 'boolean'}
      ]
    }
    this.recipesService
      .get('./assets/recipes.json')
      .then(result=>this.recipes=result)
      .catch(error => console.log(error))
  }
  toggleOption(option:any):void{
    option!=option
  }
  updateMesage(event:any){
    if(this.tableMessages.length>0){
      this.timer.unsubscribe()
    }
    this.tableMessages.push(event)
    this.timer=Observable.interval(3000).subscribe(() => {
      this.tableMessages=[]
      this.timer.unsubscribe()
    })
    console.log(event)
  }
}


text:
<?php

namespace SilverStripe\ContentReview\Extensions;

use Exception;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\ContentReview\Jobs\ContentReviewNotificationJob;
use SilverStripe\ContentReview\Models\ContentReviewLog;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\CompositeField;
use SilverStripe\Forms\DateField;
use SilverStripe\Forms\DateTimeField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldConfig_RecordEditor;
use SilverStripe\Forms\GridField\GridFieldDataColumns;
use SilverStripe\Forms\GridField\GridFieldSortableHeader;
use SilverStripe\Forms\HeaderField;
use SilverStripe\Forms\ListboxField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\OptionsetField;
use SilverStripe\Forms\ReadonlyField;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\DataExtension;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\FieldType\DBDate;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\ORM\SS_List;
use SilverStripe\Security\Group;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Security\PermissionProvider;
use SilverStripe\Security\Security;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\View\Requirements;
use Symbiote\QueuedJobs\DataObjects\QueuedJobDescriptor;
use Symbiote\QueuedJobs\Services\QueuedJobService;

/**
 * Set dates at which content needs to be reviewed and provide a report and emails to alert
 * to content needing review.
 *
 * @property string $ContentReviewType
 * @property int $ReviewPeriodDays
 * @property Date $NextReviewDate
 * @property string $LastEditedByName
 * @property string $OwnerNames
 *
 * @method DataList ReviewLogs()
 * @method DataList ContentReviewGroups()
 * @method DataList ContentReviewUsers()
 */
class SiteTreeContentReview extends DataExtension implements PermissionProvider
{
    /**
     * @var array
     */
    private static $db = [
        "ContentReviewType" => "Enum('Inherit, Disabled, Custom', 'Inherit')",
        "ReviewPeriodDays" => "Int",
        "NextReviewDate" => "Date",
        "LastEditedByName" => "Varchar(255)",
        "OwnerNames" => "Varchar(255)",
    ];

    /**
     * @var array
     */
    private static $defaults = [
        "ContentReviewType" => "Inherit",
    ];

    /**
     * @var array
     */
    private static $has_many = [
        "ReviewLogs" => ContentReviewLog::class,
    ];

    /**
     * @var array
     */
    private static $belongs_many_many = [
        "ContentReviewGroups" => Group::class,
        "ContentReviewUsers" => Member::class,
    ];

    /**
     * @var array
     */
    private static $schedule = [
        0 => "No automatic review date",
        1 => "1 day",
        7 => "1 week",
        30 => "1 month",
        60 => "2 months",
        91 => "3 months",
        121 => "4 months",
        152 => "5 months",
        183 => "6 months",
        365 => "12 months",
    ];

    /**
     * @return array
     */
    public static function get_schedule()
    {
        return Config::inst()->get(static::class, 'schedule');
    }

    /**
     * Takes a list of groups and members and return a list of unique member.
     *
     * @param SS_List $groups
     * @param SS_List $members
     *
     * @return ArrayList
     */
    public static function merge_owners(SS_List $groups, SS_List $members)
    {
        $contentReviewOwners = new ArrayList();

        if ($groups->count()) {
            $groupIDs = [];

            foreach ($groups as $group) {
                $familyIDs = $group->collateFamilyIDs();

                if (is_array($familyIDs)) {
                    $groupIDs = array_merge($groupIDs, array_values($familyIDs ?? []));
                }
            }

            array_unique($groupIDs ?? []);

            if (count($groupIDs ?? [])) {
                $groupMembers = DataObject::get(Member::class)
                    ->where("\"Group\".\"ID\" IN (" . implode(",", $groupIDs) . ")")
                    ->leftJoin("Group_Members", "\"Member\".\"ID\" = \"Group_Members\".\"MemberID\"")
                    /** @skipUpgrade */
                    ->leftJoin('Group', "\"Group_Members\".\"GroupID\" = \"Group\".\"ID\"");

                $contentReviewOwners->merge($groupMembers);
            }
        }

        $contentReviewOwners->merge($members);
        $contentReviewOwners->removeDuplicates();

        return $contentReviewOwners;
    }

    /**
     * @param FieldList $actions
     */
    public function updateCMSActions(FieldList $actions)
    {
        if (!$this->canBeReviewedBy(Security::getCurrentUser())) {
            return;
        }

        Requirements::css('silverstripe/contentreview:client/dist/styles/contentreview.css');
        Requirements::javascript('silverstripe/contentreview:client/dist/js/contentreview.js');

        $reviewTab = LiteralField::create('ContentReviewButton', $this->owner->renderWith(__CLASS__ . '_button'));
        $actions->insertAfter('MajorActions', $reviewTab);
    }

    /**
     * Returns false if the content review have disabled.
     *
     * @param SiteTree $page
     *
     * @return bool|DBDate
     */
    public function getReviewDate(SiteTree $page = null)
    {
        if ($page === null) {
            $page = $this->owner;
        }

        if ($page->obj('NextReviewDate')->exists()) {
            return $page->obj('NextReviewDate');
        }

        $options = $this->owner->getOptions();

        if (!$options) {
            return false;
        }

        if (!$options->ReviewPeriodDays) {
            return false;
        }

        // Failover to check on ReviewPeriodDays + LastEdited
        $nextReviewUnixSec = strtotime(' + ' . $options->ReviewPeriodDays . ' days', DBDatetime::now()->getTimestamp());
        $date = DBDate::create('NextReviewDate');
        $date->setValue($nextReviewUnixSec);
        return $date;
    }

    /**
     * Get the object that have the information about the content review settings. Either:
     *
     *  - a SiteTreeContentReview decorated object
     *  - the default SiteTree config
     *  - false if this page have it's content review disabled
     *
     * Will go through parents and root pages will use the site config if their setting is Inherit.
     *
     * @return bool|DataObject
     *
     * @throws Exception
     */
    public function getOptions()
    {
        if ($this->owner->ContentReviewType == "Custom") {
            return $this->owner;
        }

        if ($this->owner->ContentReviewType == "Disabled") {
            return false;
        }

        $page = $this->owner;

        // $page is inheriting it's settings from it's parent, find
        // the first valid parent with a valid setting
        while ($parent = $page->Parent()) {
            // Root page, use site config
            if (!$parent->exists()) {
                return SiteConfig::current_site_config();
            }

            if ($parent->ContentReviewType == "Custom") {
                return $parent;
            }

            if ($parent->ContentReviewType == "Disabled") {
                return false;
            }

            $page = $parent;
        }

        throw new Exception("This shouldn't really happen, as per usual developer logic.");
    }

    /**
     * @return string
     */
    public function getOwnerNames()
    {
        $options = $this->getOptions();

        $names = [];

        if (!$options) {
            return "";
        }

        foreach ($options->OwnerGroups() as $group) {
            $names[] = $group->getBreadcrumbs(" > ");
        }

        foreach ($options->OwnerUsers() as $group) {
            $names[] = $group->getName();
        }

        return implode(", ", $names);
    }

    /**
     * @return null|string
     */
    public function getEditorName()
    {
        $member = Security::getCurrentUser();

        if ($member) {
            return $member->getTitle();
        }

        return null;
    }

    /**
     * Get all Members that are Content Owners to this page. This includes checking group
     * hierarchy and adding any direct users.
     *
     * @return ArrayList
     */
    public function ContentReviewOwners()
    {
        return SiteTreeContentReview::merge_owners(
            $this->OwnerGroups(),
            $this->OwnerUsers()
        );
    }

    /**
     * @return ManyManyList
     */
    public function OwnerGroups()
    {
        return $this->owner->getManyManyComponents("ContentReviewGroups");
    }

    /**
     * @return ManyManyList
     */
    public function OwnerUsers()
    {
        return $this->owner->getManyManyComponents("ContentReviewUsers");
    }

    /**
     * @param FieldList $fields
     */
    public function updateSettingsFields(FieldList $fields)
    {
        if ($this->owner->hasMethod('displayContentReview') && !$this->owner->displayContentReview()) {
            return;
        }

        Requirements::javascript('silverstripe/contentreview:client/dist/js/contentreview.js');
        // Display read-only version only
        if (!Permission::check("EDIT_CONTENT_REVIEW_FIELDS")) {
            $schedule = self::get_schedule();
            $contentOwners = ReadonlyField::create(
                "ROContentOwners",
                _t(__CLASS__ . ".CONTENTOWNERS", "Content Owners"),
                $this->getOwnerNames()
            );
            $nextReviewAt = DateField::create(
                'RONextReviewDate',
                _t(__CLASS__ . ".NEXTREVIEWDATE", "Next review date"),
                $this->owner->NextReviewDate
            );

            if (!isset($schedule[$this->owner->ReviewPeriodDays])) {
                $reviewFreq = ReadonlyField::create(
                    "ROReviewPeriodDays",
                    _t(__CLASS__ . ".REVIEWFREQUENCY", "Review frequency"),
                    $schedule[0]
                );
            } else {
                $reviewFreq = ReadonlyField::create(
                    "ROReviewPeriodDays",
                    _t(__CLASS__ . ".REVIEWFREQUENCY", "Review frequency"),
                    $schedule[$this->owner->ReviewPeriodDays]
                );
            }

            $logConfig = GridFieldConfig::create()
                ->addComponent(Injector::inst()->create(GridFieldSortableHeader::class))
                ->addComponent($logColumns = Injector::inst()->create(GridFieldDataColumns::class));

            // Cast the value to the users preferred date format
            $logColumns->setFieldCasting([
                'Created' => DateTimeField::class . '->value',
            ]);

            $logs = GridField::create("ROReviewNotes", "Review Notes", $this->owner->ReviewLogs(), $logConfig);

            $optionsFrom = ReadonlyField::create(
                "ROType",
                _t(__CLASS__ . ".SETTINGSFROM", "Options are"),
                $this->owner->ContentReviewType
            );

            $fields->addFieldsToTab("Root.ContentReview", [
                $contentOwners,
                $nextReviewAt->performReadonlyTransformation(),
                $reviewFreq,
                $optionsFrom,
                $logs,
            ]);

            return;
        }

        $options = [];
        $options["Disabled"] = _t(__CLASS__ . ".DISABLE", "Disable content review");
        $options["Inherit"] = _t(__CLASS__ . ".INHERIT", "Inherit from parent page");
        $options["Custom"] = _t(__CLASS__ . ".CUSTOM", "Custom settings");

        $viewersOptionsField = OptionsetField::create(
            "ContentReviewType",
            _t(__CLASS__ . ".OPTIONS", "Options"),
            $options
        );

        $users = Permission::get_members_by_permission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_LeftAndMain', 'ADMIN']);

        $usersMap = $users->map("ID", "Title")->toArray();

        asort($usersMap);

        $userField = ListboxField::create("OwnerUsers", _t(__CLASS__ . ".PAGEOWNERUSERS", "Users"), $usersMap)
            ->addExtraClass('custom-setting')
            ->setAttribute("data-placeholder", _t(__CLASS__ . ".ADDUSERS", "Add users"))
            ->setDescription(_t(__CLASS__ . '.OWNERUSERSDESCRIPTION', 'Page owners that are responsible for reviews'));

        $groupsMap = [];

        foreach (Group::get() as $group) {
            $groupsMap[$group->ID] = $group->getBreadcrumbs(" > ");
        }
        asort($groupsMap);

        $groupField = ListboxField::create("OwnerGroups", _t(__CLASS__ . ".PAGEOWNERGROUPS", "Groups"), $groupsMap)
            ->addExtraClass('custom-setting')
            ->setAttribute("data-placeholder", _t(__CLASS__ . ".ADDGROUP", "Add groups"))
            ->setDescription(_t(__CLASS__ . ".OWNERGROUPSDESCRIPTION", "Page owners that are responsible for reviews"));

        $reviewDate = DateField::create("NextReviewDate", _t(__CLASS__ . ".NEXTREVIEWDATE", "Next review date"))
            ->setDescription(_t(__CLASS__ . ".NEXTREVIEWDATADESCRIPTION", "Leave blank for no review"));

        $reviewFrequency = DropdownField::create(
            "ReviewPeriodDays",
            _t(__CLASS__ . ".REVIEWFREQUENCY", "Review frequency"),
            self::get_schedule()
        )
            ->addExtraClass('custom-setting')
            ->setDescription(_t(
                __CLASS__ . ".REVIEWFREQUENCYDESCRIPTION",
                "The review date will be set to this far in the future whenever the page is published"
            ));

        $notesField = GridField::create(
            "ReviewNotes",
            "Review Notes",
            $this->owner->ReviewLogs(),
            GridFieldConfig_RecordEditor::create()
        );

        $fields->addFieldsToTab("Root.ContentReview", [
            HeaderField::create('ContentReviewHeader', _t(__CLASS__ . ".REVIEWHEADER", "Content review"), 2),
            $viewersOptionsField,
            CompositeField::create(
                $userField,
                $groupField,
                $reviewDate,
                $reviewFrequency
            )->addExtraClass("review-settings"),
            ReadonlyField::create(
                "ROContentOwners",
                _t(__CLASS__ . ".CONTENTOWNERS", "Content Owners"),
                $this->getOwnerNames()
            ),
            $notesField,
        ]);
    }

    /**
     * Creates a ContentReviewLog and connects it to this Page.
     *
     * @param Member $reviewer
     * @param string $message
     */
    public function addReviewNote(Member $reviewer, $message)
    {
        $reviewLog = ContentReviewLog::create();
        $reviewLog->Note = $message;
        $reviewLog->ReviewerID = $reviewer->ID;
        $this->owner->ReviewLogs()->add($reviewLog);
    }

    /**
     * Advance review date to the next date based on review period or set it to null
     * if there is no schedule. Returns true if date was required and false is content
     * review is 'off'.
     *
     * @return bool
     */
    public function advanceReviewDate()
    {
        $nextDateTimestamp = false;
        $options = $this->getOptions();

        if ($options && $options->ReviewPeriodDays) {
            $nextDateTimestamp = strtotime(
                ' + ' . $options->ReviewPeriodDays . ' days',
                DBDatetime::now()->getTimestamp()
            );

            $this->owner->NextReviewDate = DBDate::create()->setValue($nextDateTimestamp)->Format(DBDate::ISO_DATE);
            $this->owner->write();
        }

        if ($options && $options->ReviewPeriodDays == 0) {
            $this->owner->NextReviewDate = null;
            $this->owner->write();
        }

        return (bool)$nextDateTimestamp;
    }

    /**
     * Check if a review is due by a member for this owner.
     *
     * @param Member $member
     *
     * @return bool
     */
    public function canBeReviewedBy(Member $member = null)
    {
        if (!$this->owner->obj('NextReviewDate')->exists()) {
            return false;
        }

        if ($this->owner->obj('NextReviewDate')->InFuture()) {
            return false;
        }

        $options = $this->getOptions();

        if (!$options) {
            return false;
        }

        if (!$options
            // Options can be a SiteConfig with different extension applied
            || (!$options->hasExtension(__CLASS__)
                && !$options->hasExtension(ContentReviewDefaultSettings::class))
        ) {
            return false;
        }

        if ($options->OwnerGroups()->count() == 0 && $options->OwnerUsers()->count() == 0) {
            return false;
        }

        if (!$member) {
            return true;
        }

        // Check whether this user is allowed to review the content of the page.
        if ($this->owner->hasMethod("canReviewContent") && !$this->owner->canReviewContent($member)) {
            return false;
        }

        if ($member->inGroups($options->OwnerGroups())) {
            return true;
        }

        if ($options->OwnerUsers()->find("ID", $member->ID)) {
            return true;
        }

        return false;
    }

    /**
     * Set the review data from the review period, if set.
     */
    public function onBeforeWrite()
    {
        // Only update if DB fields have been changed
        $changedFields = $this->owner->getChangedFields(true, 2);
        if ($changedFields) {
            $this->owner->LastEditedByName = $this->owner->getEditorName();
            $this->owner->OwnerNames = $this->owner->getOwnerNames();
        }

        // If the user changed the type, we need to recalculate the review date.
        if ($this->owner->isChanged("ContentReviewType", 2)) {
            if ($this->owner->ContentReviewType == "Disabled") {
                $this->setDefaultReviewDateForDisabled();
            } elseif ($this->owner->ContentReviewType == "Custom") {
                $this->setDefaultReviewDateForCustom();
            } else {
                $this->setDefaultReviewDateForInherited();
            }
        }

        // Ensure that a inherited page always have a next review date
        if ($this->owner->ContentReviewType == "Inherit" && !$this->owner->NextReviewDate) {
            $this->setDefaultReviewDateForInherited();
        }

        // We need to update all the child pages that inherit this setting. We can only
        // change children after this record has been created, otherwise the stageChildren
        // method will grab all pages in the DB (this messes up unit testing)
        if (!$this->owner->exists()) {
            return;
        }

        // parent page change its review period
        // && !$this->owner->isChanged('ContentReviewType', 2)
        if ($this->owner->isChanged('ReviewPeriodDays', 2)) {
            $nextReviewUnixSec = strtotime(
                ' + ' . $this->owner->ReviewPeriodDays . ' days',
                DBDatetime::now()->getTimestamp()
            );
            $this->owner->NextReviewDate = DBDate::create()->setValue($nextReviewUnixSec)->Format('y-MM-dd');
        }
    }

    private function setDefaultReviewDateForDisabled()
    {
        $this->owner->NextReviewDate = null;
    }

    protected function setDefaultReviewDateForCustom()
    {
        // Don't overwrite existing value
        if ($this->owner->NextReviewDate) {
            return;
        }

        $this->owner->NextReviewDate = null;
        $nextDate = $this->getReviewDate();

        if (is_object($nextDate)) {
            $this->owner->NextReviewDate = $nextDate->getValue();
        } else {
            $this->owner->NextReviewDate = $nextDate;
        }
    }

    protected function setDefaultReviewDateForInherited()
    {
        // Don't overwrite existing value
        if ($this->owner->NextReviewDate) {
            return;
        }

        $options = $this->getOptions();
        $nextDate = null;

        if ($options instanceof SiteTree) {
            $nextDate = $this->getReviewDate($options);
        } elseif ($options instanceof SiteConfig) {
            $nextDate = $this->getReviewDate();
        }

        if (is_object($nextDate)) {
            $this->owner->NextReviewDate = $nextDate->getValue();
        } else {
            $this->owner->NextReviewDate = $nextDate;
        }
    }

    /**
     * Provide permissions to the CMS.
     *
     * @return array
     */
    public function providePermissions()
    {
        return [
            "EDIT_CONTENT_REVIEW_FIELDS" => [
                "name"     => "Set content owners and review dates",
                "category" => _t("SilverStripe\\Security\\Permission.CONTENT_CATEGORY", "Content permissions"),
                "sort"     => 50,
            ],
        ];
    }

    /**
     * If the queued jobs module is installed, queue up the first job for 9am tomorrow morning
     * (by default).
     */
    public function requireDefaultRecords()
    {
        if (class_exists(ContentReviewNotificationJob::class)) {
            // Ensure there is not already a job queued
            if (QueuedJobDescriptor::get()->filter("Implementation", ContentReviewNotificationJob::class)->first()) {
                return;
            }

            $nextRun = Injector::inst()->create(ContentReviewNotificationJob::class);
            $runHour = Config::inst()->get(ContentReviewNotificationJob::class, "first_run_hour");
            $firstRunTime = date(
                "Y-m-d H:i:s",
                mktime($runHour ?? 0, 0, 0, date("m"), date("d") + 1, date("y"))
            );

            singleton(QueuedJobService::class)->queueJob(
                $nextRun,
                $firstRunTime
            );

            DB::alteration_message(sprintf("Added ContentReviewNotificationJob to run at %s", $firstRunTime));
        }
    }
}


text:
A site using materializecss focused on posting artists for others to listen to.
Working on optimizing


text:
// $Id$

#ifndef __DEMENTIAKM_H_VERSION__
#define __DEMENTIAKM_H_VERSION__ 100

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif

#include "drvcommon.h"
#include "drvversion.h"
#include "../Common/IOCTLCodes.h"

#define DEVICE_NAME			"\\Device\\DementiaKM"
#define SYMLINK_NAME		"\\DosDevices\\DementiaKM"
PRESET_UNICODE_STRING(usDeviceName, DEVICE_NAME);
PRESET_UNICODE_STRING(usSymlinkName, SYMLINK_NAME);

#endif // __DEMENTIAKM_H_VERSION__


text:
NoFlo UI ChangeLog
==================

## 0.1.5 (git master)

* Added support for [viewing component source code](https://github.com/noflo/noflo-ui/issues/223) for library components. Requires runtime-level support

## 0.1.4 (2014 May 9)

* No changes, just version bump for Chrome app

## 0.1.3 (2014 May 8)

* Added examples to home screen
* Added support for `int` and `date` inport types in Node Inspector
* Fixed IndexedDB initialization issue with Chrome Apps
* `connect` events are also shown now in the edge logs

## 0.1.1 (2014 May 6)

* We now get the GitHub token, Flowhub plan, and user information through a single API call
* Added some anonymized usage metrics to help guide development
* Undo/redo are now disabled when there is no history in that direction

## 0.0.8 (2014 May 1)

* Project creation now requires login

## 0.0.7 (2014 April 29)

* Made CHANGES.md


text:
#include <common.h>
#include <netdev.h>
#include <asm/io.h>
#include <asm/arch/systimer.h>
#include <asm/arch/sysctrl.h>
#include <asm/arch/wdt.h>
#include "../drivers/mmc/arm_pl180_mmci.h"

static ulong timestamp;
static ulong lastdec;

static struct wdt *wdt_base = (struct wdt *)WDT_BASE;
static struct systimer *systimer_base = (struct systimer *)SYSTIMER_BASE;
static struct sysctrl *sysctrl_base = (struct sysctrl *)SCTL_BASE;

static void flash__init(void);
static void vexpress_timer_init(void);
DECLARE_GLOBAL_DATA_PTR;

#if defined(CONFIG_SHOW_BOOT_PROGRESS)
void show_boot_progress(int progress)
{
	printf("Boot reached stage %d\n", progress);
}
#endif

static inline void delay(ulong loops)
{
	__asm__ volatile ("1:\n"
		"subs %0, %1, #1\n"
		"bne 1b" : "=r" (loops) : "0" (loops));
}

int board_init(void)
{
	gd->bd->bi_boot_params = LINUX_BOOT_PARAM_ADDR;
	gd->bd->bi_arch_number = MACH_TYPE_VEXPRESS;
	gd->flags = 0;

	icache_enable();
	flash__init();
	vexpress_timer_init();

	return 0;
}

int board_eth_init(bd_t *bis)
{
	int rc = 0;
#ifdef CONFIG_SMC911X
	rc = smc911x_initialize(0, CONFIG_SMC911X_BASE);
#endif
	return rc;
}

int cpu_mmc_init(bd_t *bis)
{
	int rc = 0;
#ifdef CONFIG_ARM_PL180_MMCI
	rc = arm_pl180_mmci_init();
#endif
	return rc;
}

static void flash__init(void)
{
	/* Setup the sytem control register to allow writing to flash */
	writel(readl(&sysctrl_base->scflashctrl) | VEXPRESS_FLASHPROG_FLVPPEN,
	       &sysctrl_base->scflashctrl);
}

int dram_init(void)
{
	gd->ram_size =
		get_ram_size((long *)CONFIG_SYS_SDRAM_BASE, PHYS_SDRAM_1_SIZE);
	return 0;
}

void dram_init_banksize(void)
{
	gd->bd->bi_dram[0].start = PHYS_SDRAM_1;
	gd->bd->bi_dram[0].size =
			get_ram_size((long *)PHYS_SDRAM_1, PHYS_SDRAM_1_SIZE);
	gd->bd->bi_dram[1].start = PHYS_SDRAM_2;
	gd->bd->bi_dram[1].size =
			get_ram_size((long *)PHYS_SDRAM_2, PHYS_SDRAM_2_SIZE);
}

int timer_init(void)
{
	return 0;
}

/*
 * Start timer:
 *    Setup a 32 bit timer, running at 1KHz
 *    Versatile Express Motherboard provides 1 MHz timer
 */
static void vexpress_timer_init(void)
{
	/*
	 * Set clock frequency in system controller:
	 *   VEXPRESS_REFCLK is 32KHz
	 *   VEXPRESS_TIMCLK is 1MHz
	 */
	writel(SP810_TIMER0_ENSEL | SP810_TIMER1_ENSEL |
	       SP810_TIMER2_ENSEL | SP810_TIMER3_ENSEL |
	       readl(&sysctrl_base->scctrl), &sysctrl_base->scctrl);

	/*
	 * Set Timer0 to be:
	 *   Enabled, free running, no interrupt, 32-bit, wrapping
	 */
	writel(SYSTIMER_RELOAD, &systimer_base->timer0load);
	writel(SYSTIMER_RELOAD, &systimer_base->timer0value);
	writel(SYSTIMER_EN | SYSTIMER_32BIT | \
	       readl(&systimer_base->timer0control), \
	       &systimer_base->timer0control);

	reset_timer_masked();
}

/* Use the ARM Watchdog System to cause reset */
void reset_cpu(ulong addr)
{
	writeb(WDT_EN, &wdt_base->wdogcontrol);
	writel(WDT_RESET_LOAD, &wdt_base->wdogload);
	while (1)
		;
}

/*
 * Delay x useconds AND perserve advance timstamp value
 *     assumes timer is ticking at 1 msec
 */
void __udelay(ulong usec)
{
	ulong tmo, tmp;

	tmo = usec / 1000;
	tmp = get_timer(0);	/* get current timestamp */

	/*
	 * If setting this forward will roll time stamp	then
	 * reset "advancing" timestamp to 0 and set lastdec value
	 * otherwise set the advancing stamp to the wake up time
	 */
	if ((tmo + tmp + 1) < tmp)
		reset_timer_masked();
	else
		tmo += tmp;

	while (get_timer_masked() < tmo)
		; /* loop till wakeup event */
}

ulong get_timer(ulong base)
{
	return get_timer_masked() - base;
}

void reset_timer_masked(void)
{
	lastdec = readl(&systimer_base->timer0value) / 1000;
	timestamp = 0;
}

ulong get_timer_masked(void)
{
	ulong now = readl(&systimer_base->timer0value) / 1000;

	if (lastdec >= now) {	/* normal mode (non roll) */
		timestamp += lastdec - now;
	} else {		/* count down timer overflowed */
		/*
		 * nts = ts + ld - now
		 * ts = old stamp, ld = time before passing through - 1
		 * now = amount of time after passing though - 1
		 * nts = new "advancing time stamp"
		 */
		timestamp += lastdec + SYSTIMER_RELOAD - now;
	}
	lastdec = now;

	return timestamp;
}

void lowlevel_init(void)
{
}

ulong get_board_rev(void){
	return readl((u32 *)SYS_ID);
}


text:
namespace mojo {
namespace core {
namespace ports {

class Port;
class PortLocker;

class COMPONENT_EXPORT(MOJO_CORE_PORTS) PortRef {
 public:
  ~PortRef();
  PortRef();
  PortRef(const PortName& name, scoped_refptr<Port> port);

  PortRef(const PortRef& other);
  PortRef(PortRef&& other);

  PortRef& operator=(const PortRef& other);
  PortRef& operator=(PortRef&& other);

  const PortName& name() const { return name_; }

  bool is_valid() const { return !!port_; }

 private:
  friend class PortLocker;

  Port* port() const { return port_.get(); }

  PortName name_;
  scoped_refptr<Port> port_;
};

}  // namespace ports
}  // namespace core
}  // namespace mojo

#endif  // MOJO_CORE_PORTS_PORT_REF_H_


text: import './src/styles/theme.css'