text:
using namespace Halley;

String ScriptVariable::getLargeLabel(const ScriptGraphNode& node) const
{
	return node.getSettings()["variable"].asString("");
}

String ScriptVariable::getShortDescription(const World* world, const ScriptGraphNode& node, const ScriptGraph& graph, GraphPinId elementIdx) const
{
	return node.getSettings()["scope"].asString("local") + ":" + node.getSettings()["variable"].asString("");
}

gsl::span<const IScriptNodeType::PinType> ScriptVariable::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 2>{ PinType{ ET::WriteDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Output } };
	return data;
}

Vector<IScriptNodeType::SettingType> ScriptVariable::getSettingTypes() const
{
	return {
		SettingType{ "scope", "Halley::ScriptVariableScope", Vector<String>{"local"} },
		SettingType{ "variable", "Halley::String", Vector<String>{""} }
	};
}

std::pair<String, Vector<ColourOverride>> ScriptVariable::getNodeDescription(const ScriptGraphNode& node, const World* world, const ScriptGraph& graph) const
{
	auto str = ColourStringBuilder(true);
	str.append("Variable ");
	str.append(node.getSettings()["scope"].asString("local") + ":" + node.getSettings()["variable"].asString(""), parameterColour);
	return str.moveResults();
}

ConfigNode ScriptVariable::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pinN) const
{
	const auto& vars = environment.getVariables(getScope(node));
	return ConfigNode(vars.getVariable(node.getSettings()["variable"].asString("")));
}

void ScriptVariable::doSetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pinN, ConfigNode data) const
{
	auto& vars = environment.getVariables(getScope(node));
	vars.setVariable(node.getSettings()["variable"].asString(""), std::move(data));
}

ConfigNode ScriptVariable::doGetDevConData(ScriptEnvironment& environment, const ScriptGraphNode& node) const
{
	const auto& vars = environment.getVariables(getScope(node));
	return ConfigNode(vars.getVariable(node.getSettings()["variable"].asString("")));
}

ScriptVariableScope ScriptVariable::getScope(const ScriptGraphNode& node) const
{
	return fromString<ScriptVariableScope>(node.getSettings()["scope"].asString("local"));
}

String ScriptLiteral::getLargeLabel(const ScriptGraphNode& node) const
{
	const auto& val = getConfigNode(node);
	const auto& str = val.asString("");
	if (val.getType() == ConfigNodeType::String) {
		return "\"" + str + "\"";
	} else if (val.getType() == ConfigNodeType::Undefined) {
		return "null";
	}
	return str;
}

String ScriptLiteral::getShortDescription(const World* world, const ScriptGraphNode& node, const ScriptGraph& graph, GraphPinId elementIdx) const
{
	return getLargeLabel(node);
}

gsl::span<const IScriptNodeType::PinType> ScriptLiteral::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 1>{ PinType{ ET::ReadDataPin, PD::Output } };
	return data;
}

Vector<IScriptNodeType::SettingType> ScriptLiteral::getSettingTypes() const
{
	return { SettingType{ "value", "Halley::String", Vector<String>{"0"} } };
}

std::pair<String, Vector<ColourOverride>> ScriptLiteral::getNodeDescription(const ScriptGraphNode& node, const World* world, const ScriptGraph& graph) const
{
	auto data = getConfigNode(node);

	auto str = ColourStringBuilder(false);
	bool quoting = false;
	if (data.getType() == ConfigNodeType::Int) {
		str.append("Int ");
	} else if (data.getType() == ConfigNodeType::Float) {
		str.append("Float ");
	} else if (data.getType() == ConfigNodeType::Float2) {
		str.append("Vector2f ");
	} else if (data.getType() != ConfigNodeType::Undefined) {
		str.append("String ");
		str.append("\"", parameterColour);
		quoting = true;
	}

	str.append(data.asString(), parameterColour);
	if (quoting) {
		str.append("\"", parameterColour);
	}
	return str.moveResults();
}

ConfigNode ScriptLiteral::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pinN) const
{
	return getConfigNode(node);
}

ConfigNode ScriptLiteral::getConfigNode(const ScriptGraphNode& node) const
{
	const auto& value = node.getSettings()["value"].asString("");
	if (value == "null") {
		return ConfigNode();
	}

	if (value.startsWith("(") && value.endsWith(")")) { // well this is hacky
		const auto string = value.mid(1, value.length() - 2);
		const auto strings = string.split(",");
		if (strings.size() == 2 && strings[0].isNumber() && strings[1].isNumber()) {
			return ConfigNode(Vector2f(strings[0].toFloat(), strings[1].toFloat()));
		}
	}

	if (value.isNumber()) {
		if (value.isInteger()) {
			return ConfigNode(value.toInteger());
		} else {
			return ConfigNode(value.toFloat());
		}
	}
	return ConfigNode(value);
}

String ScriptColourLiteral::getLargeLabel(const ScriptGraphNode& node) const
{
	return node.getSettings()["value"].asString("#FFFFFF");
}

String ScriptColourLiteral::getShortDescription(const World* world, const ScriptGraphNode& node, const ScriptGraph& graph, GraphPinId elementIdx) const
{
	return getLargeLabel(node);
}

gsl::span<const IScriptNodeType::PinType> ScriptColourLiteral::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 1>{ PinType{ ET::ReadDataPin, PD::Output } };
	return data;
}

Vector<IScriptNodeType::SettingType> ScriptColourLiteral::getSettingTypes() const
{
	return { SettingType{ "value", "Halley::Colour4f", Vector<String>{"#FFFFFF"} } };
}

std::pair<String, Vector<ColourOverride>> ScriptColourLiteral::getNodeDescription(const ScriptGraphNode& node, const World* world, const ScriptGraph& graph) const
{
	auto str = ColourStringBuilder(false);
	str.append("Colour");
	return str.moveResults();
}

ConfigNode ScriptColourLiteral::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pinN) const
{
	return ConfigNode(node.getSettings()["value"].asString("#FFFFFF"));
}

String ScriptComparison::getLargeLabel(const ScriptGraphNode& node) const
{
	return node.getSettings()["operator"].asString("==");
}

String ScriptComparison::getShortDescription(const World* world, const ScriptGraphNode& node, const ScriptGraph& graph, GraphPinId elementIdx) const
{
	auto a = getConnectedNodeName(world, node, graph, 0);
	auto b = getConnectedNodeName(world, node, graph, 1);
	auto op = getLargeLabel(node);
	return addParentheses(std::move(a)) + " " + op + " " + addParentheses(std::move(b));
}

gsl::span<const IScriptNodeType::PinType> ScriptComparison::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 3>{ PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Output } };
	return data;
}

Vector<IScriptNodeType::SettingType> ScriptComparison::getSettingTypes() const
{
	return { SettingType{ "operator", "Halley::MathRelOp", Vector<String>{"=="} } };
}

std::pair<String, Vector<ColourOverride>> ScriptComparison::getNodeDescription(const ScriptGraphNode& node, const World* world, const ScriptGraph& graph) const
{
	auto str = ColourStringBuilder(true);
	str.append("True if ");
	str.append(addParentheses(getConnectedNodeName(world, node, graph, 0)), parameterColour);
	str.append(" ");
	str.append(node.getSettings()["operator"].asString("=="), parameterColour);
	str.append(" ");
	str.append(addParentheses(getConnectedNodeName(world, node, graph, 1)), parameterColour);
	return str.moveResults();
}

ConfigNode ScriptComparison::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pinN) const
{
	const auto a = readDataPin(environment, node, 0);
	const auto b = readDataPin(environment, node, 1);
	const auto typeA = a.getType();
	const auto typeB = b.getType();
	const auto op = fromString<MathRelOp>(node.getSettings()["operator"].asString("=="));

	bool result = false;
	if (typeA == ConfigNodeType::EntityId || typeB == ConfigNodeType::EntityId) {
		result = MathOps::compare(op, a.asInt64(0), b.asInt64(0));
	} else if (typeA == ConfigNodeType::String || typeB == ConfigNodeType::String) {
		result = MathOps::compare(op, a.asString(""), b.asString(""));
	} else if (typeA == ConfigNodeType::Float || typeB == ConfigNodeType::Float) {
		result = MathOps::compare(op, a.asFloat(0), b.asFloat(0));
	} else if (typeA == ConfigNodeType::Int64 || typeB == ConfigNodeType::Int64) {
		result = MathOps::compare(op, a.asInt64(0), b.asInt64(0));
	} else if (typeA == ConfigNodeType::Int || typeB == ConfigNodeType::Int) {
		result = MathOps::compare(op, a.asInt(0), b.asInt(0));
	} else {
		Logger::logError("ScriptComparison node can't compare types " + toString(typeA) + " and " + toString(typeB));
	}

	return ConfigNode(result);
}

String ScriptArithmetic::getLargeLabel(const ScriptGraphNode& node) const
{
	return node.getSettings()["operator"].asString("+");
}

String ScriptArithmetic::getShortDescription(const World* world, const ScriptGraphNode& node, const ScriptGraph& graph, GraphPinId elementIdx) const
{
	auto a = getConnectedNodeName(world, node, graph, 0);
	auto b = getConnectedNodeName(world, node, graph, 1);
	auto op = getLargeLabel(node);

	if (op[0] >= 'a' && op[0] <= 'z') {
		// If starts with a lower case letter, assume it's in function form
		return op + "(" + a + ", " + b + ")";
	} else {
		// Otherwise, assume infix form
		return addParentheses(std::move(a)) + " " + op + " " + addParentheses(std::move(b));
	}
}

gsl::span<const IScriptNodeType::PinType> ScriptArithmetic::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 3>{ PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Output } };
	return data;
}

Vector<IScriptNodeType::SettingType> ScriptArithmetic::getSettingTypes() const
{
	return { SettingType{ "operator", "Halley::MathOp", Vector<String>{"+"} } };
}

std::pair<String, Vector<ColourOverride>> ScriptArithmetic::getNodeDescription(const ScriptGraphNode& node, const World* world, const ScriptGraph& graph) const
{
	auto str = ColourStringBuilder(true);
	str.append("Returns ");
	str.append(getShortDescription(world, node, graph, 0), parameterColour);
	return str.moveResults();
}

ConfigNode ScriptArithmetic::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pin_n) const
{
	const auto a = readDataPin(environment, node, 0);
	const auto b = readDataPin(environment, node, 1);
	const auto op = fromString<MathOp>(node.getSettings()["operator"].asString("+"));

	const auto type = ConfigNode::getPromotedType(std::array<ConfigNodeType, 2>{ a.getType(), b.getType() }, true);

	if (type == ConfigNodeType::String) {
		if (op == MathOp::Add) {
			return ConfigNode(a.asString("") + b.asString(""));
		} else {
			Logger::logError("Attempting to perform illegal op " + toString(op) + " with string types.");
			return ConfigNode();
		}
	} else if (type == ConfigNodeType::Float) {
		return ConfigNode(MathOps::apply(op, a.asFloat(0), b.asFloat(0)));
	} else if (type == ConfigNodeType::Int64) {
		return ConfigNode(MathOps::apply(op, a.asInt64(0), b.asInt64(0)));
	} else if (type == ConfigNodeType::Int) {
		return ConfigNode(MathOps::apply(op, a.asInt(0), b.asInt(0)));
	} else {
		Logger::logError("ScriptComparison node can't perform arithmetic with types " + toString(a.getType()) + " and " + toString(b.getType()));
		return ConfigNode();
	}
}

String ScriptValueOr::getShortDescription(const World* world, const ScriptGraphNode& node, const ScriptGraph& graph, GraphPinId elementIdx) const
{
	auto a = getConnectedNodeName(world, node, graph, 0);
	auto b = getConnectedNodeName(world, node, graph, 1);
	return addParentheses(std::move(a)) + " ?? " + addParentheses(std::move(b));
}

gsl::span<const IScriptNodeType::PinType> ScriptValueOr::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 3>{ PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Output } };
	return data;
}

std::pair<String, Vector<ColourOverride>> ScriptValueOr::getNodeDescription(const ScriptGraphNode& node, const World* world, const ScriptGraph& graph) const
{
	auto str = ColourStringBuilder(true);
	str.append("Returns ");
	str.append(getConnectedNodeName(world, node, graph, 0), parameterColour);
	str.append(" if defined, otherwise ");
	str.append(getConnectedNodeName(world, node, graph, 1), parameterColour);
	return str.moveResults();
}

ConfigNode ScriptValueOr::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pinN) const
{
	auto a = readDataPin(environment, node, 0);
	if (a.getType() != ConfigNodeType::Undefined) {
		return a;
	} else {
		return readDataPin(environment, node, 1);
	}
}

Vector<IScriptNodeType::SettingType> ScriptLerp::getSettingTypes() const
{
	return {
		SettingType{ "from", "float", Vector<String>{"0"} },
		SettingType{ "to", "float", Vector<String>{"1"} },
	};
}

gsl::span<const IScriptNodeType::PinType> ScriptLerp::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 2>{ PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Output } };
	return data;
}

std::pair<String, Vector<ColourOverride>> ScriptLerp::getNodeDescription(const ScriptGraphNode& node, const World* world, const ScriptGraph& graph) const
{
	auto str = ColourStringBuilder(true);
	str.append("Returns lerp(");
	str.append(toString(node.getSettings()["from"].asFloat(0)), parameterColour);
	str.append(", ");
	str.append(toString(node.getSettings()["to"].asFloat(1)), parameterColour);
	str.append(", ");
	str.append(getConnectedNodeName(world, node, graph, 0), parameterColour);
	str.append(")");
	return str.moveResults();
}

String ScriptLerp::getShortDescription(const World* world, const ScriptGraphNode& node, const ScriptGraph& graph, GraphPinId element_idx) const
{
	const auto from = node.getSettings()["from"].asFloat(0);
	const auto to = node.getSettings()["to"].asFloat(1);
	return "lerp(" + toString(from) + ", " + toString(to) + ", " + getConnectedNodeName(world, node, graph, 0) + ")";
}

ConfigNode ScriptLerp::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pin_n) const
{
	const auto from = node.getSettings()["from"].asFloat(0);
	const auto to = node.getSettings()["to"].asFloat(1);
	const auto t = readDataPin(environment, node, 0).asFloat(0);
	return ConfigNode(lerp(from, to, t));
}

gsl::span<const IScriptNodeType::PinType> ScriptAdvanceTo::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 9>{
		PinType{ ET::FlowPin, PD::Input },
		PinType{ ET::FlowPin, PD::Output },
		PinType{ ET::FlowPin, PD::Output },
		PinType{ ET::FlowPin, PD::Output },
		PinType{ ET::FlowPin, PD::Output },
		PinType{ ET::FlowPin, PD::Output },
		PinType{ ET::ReadDataPin, PD::Input },
		PinType{ ET::ReadDataPin, PD::Input },
		PinType{ ET::WriteDataPin, PD::Output }
	};
	return data;
}

std::pair<String, Vector<ColourOverride>> ScriptAdvanceTo::getPinDescription(const ScriptGraphNode& node, PinType element, GraphPinId elementIdx) const
{
	if (elementIdx == 1) {
		return { "Flow output.", {} };
	} else if (elementIdx == 2) {
		return { "Flow output if target is reached.", {} };
	} else if (elementIdx == 3) {
		return { "Flow output if target is not reached.", {} };
	} else if (elementIdx == 4) {
		return { "Flow output if variable was modified.", {} };
	} else if (elementIdx == 5) {
		return { "Flow output if variable was not modified.", {} };
	} else if (elementIdx == 6) {
		return { "Target value", {} };
	} else if (elementIdx == 7) {
		return { "Increment value", {} };
	} else if (elementIdx == 8) {
		return { "Variable being modified", {} };
	}
	return ScriptNodeTypeBase<void>::getPinDescription(node, element, elementIdx);
}

std::pair<String, Vector<ColourOverride>> ScriptAdvanceTo::getNodeDescription(const ScriptGraphNode& node, const World* world, const ScriptGraph& graph) const
{
	auto str = ColourStringBuilder(true);
	str.append("Advance ");
	str.append(getConnectedNodeName(world, node, graph, 8), parameterColour);
	str.append(" towards ");
	str.append(getConnectedNodeName(world, node, graph, 6), parameterColour);
	str.append(" by ");
	str.append(getConnectedNodeName(world, node, graph, 7), parameterColour);
	return str.moveResults();
}

namespace {
	template <typename T>
	std::tuple<T, bool, bool> advanceWithFlags(T a, T b, T inc)
	{
		const bool modified = !(a == b);
		const T c = advance<T>(a, b, inc);
		const bool reached = c == b;
		return { c, modified, reached };
	}
}

IScriptNodeType::Result ScriptAdvanceTo::doUpdate(ScriptEnvironment& environment, Time time, const ScriptGraphNode& node) const
{
	const auto target = readDataPin(environment, node, 6);
	const auto amount = readDataPin(environment, node, 7);
	const auto var = readDataPin(environment, node, 8);

	const auto type = ConfigNode::getPromotedType(std::array<ConfigNodeType, 3>{ var.getType(), target.getType(), amount.getType() }, true);
	bool modified = false;
	bool reached = false;

	if (type == ConfigNodeType::Float) {
		float v;
		std::tie(v, modified, reached) = advanceWithFlags(var.asFloat(0), target.asFloat(0), amount.asFloat(0));
		//Logger::logDev("AdvanceTo(" + toString(node.getId()) + "): " + toString(var.asFloat(0)) + " -> " + toString(v) + " | modified=" + toString(modified) + ", reached=" + toString(reached));
		writeDataPin(environment, node, 8, ConfigNode(v));
	} else if (type == ConfigNodeType::Int) {
		int v;
		std::tie(v, modified, reached) = advanceWithFlags(var.asInt(0), target.asInt(0), amount.asInt(0));
		writeDataPin(environment, node, 8, ConfigNode(v));
	} else if (type == ConfigNodeType::Int64) {
		int64_t v;
		std::tie(v, modified, reached) = advanceWithFlags(var.asInt64(0), target.asInt64(0), amount.asInt64(0));
		writeDataPin(environment, node, 8, ConfigNode(v));
	} else {
		Logger::logError("Cannot advance variable of type " + toString(type));
	}

	constexpr uint8_t normalOutPinMask = 1 << 0;
	constexpr uint8_t reachedOutPinMask = 1 << 1;
	constexpr uint8_t notReachedOutPinMask = 1 << 2;
	constexpr uint8_t modifiedOutPinMask = 1 << 3;
	constexpr uint8_t notModifiedOutPinMask = 1 << 4;
	return Result(ScriptNodeExecutionState::Done, 0, (normalOutPinMask) | (reached ? reachedOutPinMask : notReachedOutPinMask) | (modified ? modifiedOutPinMask : notModifiedOutPinMask));
}

String ScriptSetVariable::getLabel(const ScriptGraphNode& node) const
{
	if (!node.getPin(2).hasConnection()) {
		return toString(node.getSettings()["defaultValue"].asFloat(0));
	}
	return "";
}

gsl::span<const IScriptNodeType::PinType> ScriptSetVariable::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 4>{ PinType{ ET::FlowPin, PD::Input }, PinType{ ET::FlowPin, PD::Output }, PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::WriteDataPin, PD::Output } };
	return data;
}

Vector<IScriptNodeType::SettingType> ScriptSetVariable::getSettingTypes() const
{
	return { SettingType{ "defaultValue", "float", Vector<String>{"0"} } };
}

std::pair<String, Vector<ColourOverride>> ScriptSetVariable::getNodeDescription(const ScriptGraphNode& node, const World* world, const ScriptGraph& graph) const
{
	auto label = getLabel(node);

	auto str = ColourStringBuilder(true);
	str.append(getConnectedNodeName(world, node, graph, 3), parameterColour);
	str.append(" := ");
	str.append(label.isEmpty() ? getConnectedNodeName(world, node, graph, 2) : label, parameterColour);
	return str.moveResults();
}

IScriptNodeType::Result ScriptSetVariable::doUpdate(ScriptEnvironment& environment, Time time, const ScriptGraphNode& node) const
{
	auto data = node.getPin(2).hasConnection() ? readDataPin(environment, node, 2) : ConfigNode(node.getSettings()["defaultValue"].asFloat(0));
	writeDataPin(environment, node, 3, std::move(data));
	return Result(ScriptNodeExecutionState::Done);
}

ScriptHoldVariableData::ScriptHoldVariableData(const ConfigNode& node)
{
	prevValue = ConfigNode(node["prevValue"]);
}

ConfigNode ScriptHoldVariableData::toConfigNode(const EntitySerializationContext& context)
{
	ConfigNode::MapType result;
	result["prevValue"] = ConfigNode(prevValue);
	return result;
}

String ScriptHoldVariable::getLabel(const ScriptGraphNode& node) const
{
	if (!node.getPin(2).hasConnection()) {
		if (!node.getPin(3).hasConnection()) {
			return toString(node.getSettings()["defaultValue"].asInt(0)) + " -> " + toString(node.getSettings()["defaultPrevValue"].asInt(0));
		} else {
			return toString(node.getSettings()["defaultValue"].asInt(0));
		}
	}
	return "";
}

gsl::span<const IScriptNodeType::PinType> ScriptHoldVariable::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 5>{ PinType{ ET::FlowPin, PD::Input }, PinType{ ET::FlowPin, PD::Output }, PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::WriteDataPin, PD::Output } };
	return data;
}

Vector<IScriptNodeType::SettingType> ScriptHoldVariable::getSettingTypes() const
{
	return {
		SettingType{ "defaultValue", "int", Vector<String>{"0"} },
		SettingType{ "defaultPrevValue", "int", Vector<String>{"0"} },
	};
}

std::pair<String, Vector<ColourOverride>> ScriptHoldVariable::getNodeDescription(const ScriptGraphNode& node, const World* world, const ScriptGraph& graph) const
{
	const auto label1 = !node.getPin(2).hasConnection() ? toString(node.getSettings()["defaultValue"].asInt(0)) : "";
	const auto label2 = !node.getPin(3).hasConnection() ? toString(node.getSettings()["defaultPrevValue"].asInt(0)) : "";

	auto str = ColourStringBuilder(true);
	str.append(getConnectedNodeName(world, node, graph, 4), parameterColour);
	str.append(" := ");
	str.append(label1.isEmpty() ? getConnectedNodeName(world, node, graph, 2) : label1, parameterColour);
	str.append(", then ");
	str.append(getConnectedNodeName(world, node, graph, 4), parameterColour);
	str.append(" := ");
	str.append(label2.isEmpty() ? getConnectedNodeName(world, node, graph, 3) : label2, parameterColour);
	return str.moveResults();
}

void ScriptHoldVariable::doInitData(ScriptHoldVariableData& data, const ScriptGraphNode& node, const EntitySerializationContext& context, const ConfigNode& nodeData) const
{
}

IScriptNodeType::Result ScriptHoldVariable::doUpdate(ScriptEnvironment& environment, Time time, const ScriptGraphNode& node,ScriptHoldVariableData& curData) const
{
	auto prevData = node.getPin(3).hasConnection() ? readDataPin(environment, node, 3) : ConfigNode(node.getSettings()["defaultPrevValue"].asInt(0));
	curData.prevValue = std::move(prevData);

	auto data = node.getPin(2).hasConnection() ? readDataPin(environment, node, 2) : ConfigNode(node.getSettings()["defaultValue"].asInt(0));
	writeDataPin(environment, node, 4, std::move(data));
	return Result(ScriptNodeExecutionState::Done);
}

void ScriptHoldVariable::doDestructor(ScriptEnvironment& environment, const ScriptGraphNode& node, ScriptHoldVariableData& curData) const
{
	writeDataPin(environment, node, 4, std::move(curData.prevValue));
}

Vector<IGraphNodeType::SettingType> ScriptEntityIdToData::getSettingTypes() const
{
	return {
		SettingType{ "readRaw", "bool", Vector<String>{"true"} },
	};
}

gsl::span<const IScriptNodeType::PinType> ScriptEntityIdToData::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 2>{ PinType{ ET::TargetPin, PD::Input }, PinType{ ET::ReadDataPin, PD::Output } };
	return data;
}

String ScriptEntityIdToData::getShortDescription(const World* world, const ScriptGraphNode& node, const ScriptGraph& graph, GraphPinId elementIdx) const
{
	return getConnectedNodeName(world, node, graph, 0);
}

std::pair<String, Vector<ColourOverride>> ScriptEntityIdToData::getNodeDescription(const ScriptGraphNode& node, const World* world,	const ScriptGraph& graph) const
{
	if (node.getSettings()["readRaw"].asBool(true)) {
		return { "Convert EntityId to data. Using readRaw function.", {} };
	}
	return { "Convert EntityId to data. Using read function which returns entity to which the script is attached to, if input is invalid.", {} };
}

ConfigNode ScriptEntityIdToData::doGetData(ScriptEnvironment& environment, const ScriptGraphNode& node, size_t pinN) const
{
	if (node.getSettings()["readRaw"].asBool(true)) {
		return ConfigNode(EntityIdHolder{ readRawEntityId(environment, node, 0).value });
	}
	return ConfigNode(EntityIdHolder{ readEntityId(environment, node, 0).value });
}

gsl::span<const IScriptNodeType::PinType> ScriptDataToEntityId::getPinConfiguration(const ScriptGraphNode& node) const
{
	using ET = ScriptNodeElementType;
	using PD = GraphNodePinDirection;
	const static auto data = std::array<PinType, 2>{ PinType{ ET::ReadDataPin, PD::Input }, PinType{ ET::TargetPin, PD::Output } };
	return data;
}

String ScriptDataToEntityId::getShortDescription(const World* world, const ScriptGraphNode& node, const ScriptGraph& graph, GraphPinId elementIdx) const
{
	return getConnectedNodeName(world, node, graph, 0);
}

std::pair<String, Vector<ColourOverride>> ScriptDataToEntityId::getNodeDescription(const ScriptGraphNode& node, const World* world,	const ScriptGraph& graph) const
{
	return { "Convert data to EntityId.", {} };
}

EntityId ScriptDataToEntityId::doGetEntityId(ScriptEnvironment& environment, const ScriptGraphNode& node, GraphPinId pinN) const
{
	const auto data = readDataPin(environment, node, 0);
	EntityId result;
	result.value = data.asEntityId({}).value;
	return result;
}


text:
require 'rails_helper'
require 'bh/core_ext/rails/form_for_helper'
include Bh::Rails::Helpers

describe 'form_for' do
  let(:bh) { RailsView.new }
  let(:protect_against_forgery?) { false }
  attr_accessor :output_buffer
  let(:form) { form_for(:object, options.merge(url: '/')) {} }
  let(:options) { {} }

  specify 'by default, does not apply Bootstrap attributes to the form' do
    expect(form).not_to include 'role="form"'
  end

  specify 'wrapped in navbar, applies Bootstrap attributes of a navbar form' do
    bh.navbar { expect(form).to include 'role="form"' }
    bh.navbar { expect(form).to include 'class="navbar-form"' }
  end

  specify 'wrapped in nav, surrounds the form in a
 item' do
    bh.nav { expect(form).to match %r{^
<form.+?</form>
$} }
  end

  describe 'with layout: :horizontal' do
    let(:options) { {layout: :horizontal} }

    specify 'applies Bootstrap attributes of an horizontal form' do
      expect(form).to include 'role="form"'
      expect(form).to include 'class="form-horizontal"'
    end
  end

  describe 'with layout: :inline' do
    let(:options) { {layout: :inline} }

    specify 'applies Bootstrap attributes of an inline form' do
      expect(form).to include 'role="form"'
      expect(form).to include 'class="form-inline"'
    end
  end

  describe 'with any other value for :layout' do
    let(:options) { {layout: :basic} }

    specify 'applies Bootstrap attributes of a basic form' do
      expect(form).to include 'role="form"'
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<resources>
    <string name="songhay_app_name">Songhay for AnySoftKeyboard</string>
</resources>


text:
module Spinach
  module FileReporter
    module Reporter
      module GemDescription
        class << self
          def to_s
            <<-EOF
            This is a console and file reporter for spinach. It works like output reporter of
            spinach and add a file reporter of the errors to a file
            EOF
          end
        end
      end
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta property="og:image" content="https://scontent.xx.fbcdn.net/t31.0-8/c0.0.851.315/p851x315/13603588_111343879300293_8256170681376996907_o.jpg" />
    <title>BroNacho</title>
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/style.css">
    <link href='https://fonts.googleapis.com/css?family=Roboto+Condensed' rel='stylesheet' type='text/css'>

Home

About

Contact

BroNacho

Welcome to BroNacho!

Here at BroNacho, we bring you the most reliable compatability website out there. What more do you need to know about a person than if they're your BroNacho? What you put on your nachos matters, and it matters to other people, too. Here at BroNacho we have made your undiscovered bromances our top priority. So look no further, wait no longer, and find your BroNacho today!

      <form id="form">

Let's get started! What's your name?

        <input type="text" name="name" id="userName">

 <input id="button" type="submit" value="Find my BroNacho">

      </form>


text:
require 'spec_helper'

include Serverspec::Helper::Properties

describe 'Properties Helper' do
  before :all do
    set_property :role => 'proxy'
  end
  subject { property }
  it { should include :role => 'proxy' }
end


text:
using System.Reflection;
using System.Runtime.CompilerServices;

// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.

[assembly: AssemblyTitle("ShoppingBasket.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Furious Solutions")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Chris Cartlidge")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.

[assembly: AssemblyVersion("1.0.*")]

// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.

//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]


text:
layout: page
title: Pink Technologies Trade Fair
date: 2016-05-24
author: Paul Bradley
tags: weekly links, java
status: published
summary: Interdum et malesuada fames ac.
banner: images/banner/office-01.jpg
booking:
  startDate: 07/13/2019
  endDate: 07/17/2019
  ctyhocn: SYRCRHX
  groupCode: PTTF
published: true
---
Vestibulum sit amet lacinia dui. Cras et scelerisque lorem, a tincidunt odio. Quisque euismod mattis leo convallis varius. Pellentesque aliquet suscipit nisl eu congue. Quisque non dolor ut est ullamcorper aliquet. Nam purus risus, faucibus malesuada ante at, egestas eleifend sapien. Nulla consequat urna arcu, lacinia interdum enim posuere non. Nullam ultricies lacus varius cursus pulvinar. Etiam viverra sem in sapien rhoncus sodales. Pellentesque pulvinar eleifend ipsum eget elementum.

* Maecenas egestas nulla in nisl lacinia fringilla
* Sed molestie mi ac scelerisque sollicitudin
* Nullam in metus ornare, malesuada magna vel, sodales neque
* Vivamus tristique lectus sed vehicula luctus.

Aliquam iaculis interdum laoreet. In nec ultrices erat. Etiam dictum velit nisi, eu feugiat magna porttitor pellentesque. Sed at sapien nec purus fringilla blandit in nec est. Aenean facilisis lorem a nisl elementum, non blandit erat rhoncus. Cras sit amet lacinia tortor. Quisque elementum quam eget diam ultrices, non gravida eros iaculis.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ombrophila microsperma Henn.

### Remarks
null


text:
MatchingScore.com is the web site and formula that we are using to calculate quality of our applications in VietnamWorks.

* Change /server/settings.json.dist to /server/settings.json and issue 'meteor --settings server/settings.json' to start
* Debug level: 1: show less; 2: show all


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>ReviewRepository | anvireco</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					anvireco

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"app/data/ReviewRepository"

					ReviewRepository

Class ReviewRepository

Review Repository class.

author

Mario Juez mario@mjuez.com

Hierarchy

						AbstractRepository<IReviewEntity, ReviewDocument>

								ReviewRepository

Implements

IRepository<IReviewEntity, ReviewDocument>

IReviewRepository

Index

Constructors

constructor

Properties

COLLECTION_<wbr>NAME

RESULTS_<wbr>PER_<wbr>PAGE

Accessors

model

Methods

_num<wbr>Pages

convert<wbr>ToEntity

convert<wbr>ToEntity<wbr>Array

count

create

find<wbr>ById

find<wbr>ByPull<wbr>Id

find<wbr>ByRepository

find<wbr>One

num<wbr>Pages

remove

retrieve

update

update<wbr>Filter

Constructors

constructor

new <wbr>Review<wbr>Repository(model?: Model<ReviewDocument>): ReviewRepository

Overrides AbstractRepository.constructor

Defined in app/data/ReviewRepository.ts:41

Class constructor.
									Creates the repository using the collection name and the Review schema.

Parameters

Optional model: Model<ReviewDocument>

Optional mongoose model dependency injection.

Returns ReviewRepository

Properties

Static COLLECTION_<wbr>NAME

COLLECTION_<wbr>NAME: "review" = "review"

Defined in app/data/ReviewRepository.ts:41

MongoDB collection name.

Static RESULTS_<wbr>PER_<wbr>PAGE

RESULTS_<wbr>PER_<wbr>PAGE: number = 100

Inherited from AbstractRepository.RESULTS_PER_PAGE

Defined in app/data/AbstractRepository.ts:17

Maximum results per page (100).

Accessors

model

get model(): Model<ReviewDocument>

Inherited from AbstractRepository.model

Defined in app/data/AbstractRepository.ts:44

Gets the Mongoose Model.

Returns Model<ReviewDocument>

the mongoose model.

Methods

Protected _num<wbr>Pages

_num<wbr>Pages(filter: Object, startingFrom: number, where: string): Promise<number>

Inherited from AbstractRepository._numPages

Defined in app/data/AbstractRepository.ts:154

Counts the number of pages given a filter, and
									a starting from value.

Parameters

filter: Object

filtering options.

startingFrom: number

starting from value.

where: string

field where start from.

Returns Promise<number>

number of pages.

Protected convert<wbr>ToEntity

convert<wbr>ToEntity(document: ReviewDocument): IReviewEntity

Overrides AbstractRepository.convertToEntity

Defined in app/data/ReviewRepository.ts:84

Parameters

document: ReviewDocument

Returns IReviewEntity

Protected convert<wbr>ToEntity<wbr>Array

convert<wbr>ToEntity<wbr>Array(documentArray: ReviewDocument[]): IReviewEntity[]

Overrides AbstractRepository.convertToEntityArray

Defined in app/data/ReviewRepository.ts:88

Parameters

documentArray: ReviewDocument[]

Returns IReviewEntity[]

count

count(filter?: Object): Query<number>

Implementation of IReviewRepository.count

Inherited from AbstractRepository.count

Defined in app/data/AbstractRepository.ts:102

Counts the number of entities in database
									given an optional filter.

Parameters

Default value filter: Object = {}

Optional filtering options.

Returns Query<number>

the number of entities.

create

create(item: IReviewEntity): Promise<IReviewEntity>

Implementation of IReviewRepository.create

Inherited from AbstractRepository.create

Defined in app/data/AbstractRepository.ts:54

Creates an item into database.

Parameters

item: IReviewEntity

Item to create.

Returns Promise<IReviewEntity>

the created item.

find<wbr>ById

find<wbr>ById(id: number): Promise<IReviewEntity>

Implementation of IReviewRepository.findById

Defined in app/data/ReviewRepository.ts:67

Retrieves a review given its GitHub id.

Parameters

id: number

Review GitHub id.

Returns Promise<IReviewEntity>

a promise that returns a review entity if resolved.

find<wbr>ByPull<wbr>Id

find<wbr>ByPull<wbr>Id(id: number, page?: number, startingFrom?: number): Promise<IReviewEntity[]>

Implementation of IReviewRepository.findByPullId

Defined in app/data/ReviewRepository.ts:57

Retrieves a list of reviews of a pull request given its GitHub id.

Parameters

id: number

Pull Request GitHub id.

Default value page: number = 1

Default value startingFrom: number = 0

Returns Promise<IReviewEntity[]>

a promise that returns a list of review entities if resolved.

find<wbr>ByRepository

find<wbr>ByRepository(name: string, owner: string, page?: number, startingFrom?: number): Promise<IReviewEntity[]>

Implementation of IReviewRepository.findByRepository

Defined in app/data/ReviewRepository.ts:71

Parameters

name: string

owner: string

Default value page: number = 1

Default value startingFrom: number = 0

Returns Promise<IReviewEntity[]>

find<wbr>One

find<wbr>One(filter: Object): Promise<IReviewEntity>

Implementation of IReviewRepository.findOne

Inherited from AbstractRepository.findOne

Defined in app/data/AbstractRepository.ts:85

Retrieves a single entity from database.

Parameters

filter: Object

filtering options.

Returns Promise<IReviewEntity>

one entity.

num<wbr>Pages

num<wbr>Pages(filter?: Object, startingFrom?: number): Promise<number>

Implementation of IReviewRepository.numPages

Overrides AbstractRepository.numPages

Defined in app/data/ReviewRepository.ts:80

Parameters

Default value filter: Object = {}

Default value startingFrom: number = 0

Returns Promise<number>

remove

remove(filter?: Object): Promise<void>

Implementation of IReviewRepository.remove

Inherited from AbstractRepository.remove

Defined in app/data/AbstractRepository.ts:111

Removes elements that match a filter from database.

Parameters

Default value filter: Object = {}

filtering options.

Returns Promise<void>

retrieve

retrieve(__namedParameters?: object): Promise<IReviewEntity[]>

Inherited from AbstractRepository.retrieve

Defined in app/data/AbstractRepository.ts:126

Retrieves elements from database given a list of
									retrieving options like filtering, sorting...

Parameters

Default value __namedParameters: object = {}

filter: Object

page: number

select: string

starting<wbr>From: number

where: string

sort: object

id: number

Returns Promise<IReviewEntity[]>

an array of entities.

update

update(item: IReviewEntity): Promise<number>

Implementation of IReviewRepository.update

Inherited from AbstractRepository.update

Defined in app/data/AbstractRepository.ts:70

Updates an item.

Parameters

item: IReviewEntity

Item with updated data.

Returns Promise<number>

number of rows affected.

Protected update<wbr>Filter

update<wbr>Filter(item: IReviewEntity): Object

Overrides AbstractRepository.updateFilter

Defined in app/data/ReviewRepository.ts:92

Parameters

item: IReviewEntity

Returns Object

						Globals

						"app/data/<wbr>Review<wbr>Repository"

						Review<wbr>Repository

								constructor

								COLLECTION_<wbr>NAME

								RESULTS_<wbr>PER_<wbr>PAGE

								model

								_num<wbr>Pages

								convert<wbr>ToEntity

								convert<wbr>ToEntity<wbr>Array

								count

								create

								find<wbr>ById

								find<wbr>ByPull<wbr>Id

								find<wbr>ByRepository

								find<wbr>One

								num<wbr>Pages

								remove

								retrieve

								update

								update<wbr>Filter

						IReview<wbr>Repository

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text: Successfully News is updated.


text:
package com.tectonica.jonix.onix3;

import com.tectonica.jonix.common.JPU;
import com.tectonica.jonix.common.ListOfOnixDataComposite;
import com.tectonica.jonix.common.ListOfOnixDataCompositeWithKey;
import com.tectonica.jonix.common.ListOfOnixElement;
import com.tectonica.jonix.common.OnixComposite.OnixSuperComposite;
import com.tectonica.jonix.common.codelist.RecordSourceTypes;
import com.tectonica.jonix.common.codelist.SupplierIdentifierTypes;
import com.tectonica.jonix.common.struct.JonixSupplierIdentifier;
import com.tectonica.jonix.common.struct.JonixWebsite;

import java.io.Serializable;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DO NOT EDIT MANUALLY
 */

/**
 *
Supplier composite

 *

 * A group of data elements which together identify a specific supplier. Mandatory in each occurrence of the
 * <SupplyDetail> composite, and not repeatable.
 *

 *

 *

 * Reference name
 * <tt><Supplier></tt>
 *

 *

 * Short tag
 * <tt><supplier></tt>
 *

 *

 * Cardinality
 * 1
 *

 *

 *

 * This tag may be included in the following composites:
 *

 *
<{@link SupplyDetail}>

 *

 *

 * Possible placements within ONIX message:
 *

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link ProductSupply} ⯈ {@link SupplyDetail} ⯈ {@link Supplier}

 *

 */
public class Supplier implements OnixSuperComposite, Serializable {
    private static final long serialVersionUID = 1L;

    public static final String refname = "Supplier";
    public static final String shortname = "supplier";

    /////////////////////////////////////////////////////////////////////////////////
    // ATTRIBUTES
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * (type: dt.DateOrDateTime)
     */
    public String datestamp;

    /**
     * (type: dt.NonEmptyString)
     */
    public String sourcename;

    public RecordSourceTypes sourcetype;

    /////////////////////////////////////////////////////////////////////////////////
    // CONSTRUCTION
    /////////////////////////////////////////////////////////////////////////////////

    private boolean initialized;
    private final boolean exists;
    private final org.w3c.dom.Element element;
    public static final Supplier EMPTY = new Supplier();

    public Supplier() {
        exists = false;
        element = null;
        initialized = true; // so that no further processing will be done on this intentionally-empty object
    }

    public Supplier(org.w3c.dom.Element element) {
        exists = true;
        initialized = false;
        this.element = element;
        datestamp = JPU.getAttribute(element, "datestamp");
        sourcename = JPU.getAttribute(element, "sourcename");
        sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype"));
    }

    @Override
    public void _initialize() {
        if (initialized) {
            return;
        }
        initialized = true;

        JPU.forElementsOf(element, e -> {
            final String name = e.getNodeName();
            switch (name) {
                case SupplierRole.refname:
                case SupplierRole.shortname:
                    supplierRole = new SupplierRole(e);
                    break;
                case SupplierIdentifier.refname:
                case SupplierIdentifier.shortname:
                    supplierIdentifiers = JPU.addToList(supplierIdentifiers, new SupplierIdentifier(e));
                    break;
                case SupplierName.refname:
                case SupplierName.shortname:
                    supplierName = new SupplierName(e);
                    break;
                case TelephoneNumber.refname:
                case TelephoneNumber.shortname:
                    telephoneNumbers = JPU.addToList(telephoneNumbers, new TelephoneNumber(e));
                    break;
                case FaxNumber.refname:
                case FaxNumber.shortname:
                    faxNumbers = JPU.addToList(faxNumbers, new FaxNumber(e));
                    break;
                case EmailAddress.refname:
                case EmailAddress.shortname:
                    emailAddresss = JPU.addToList(emailAddresss, new EmailAddress(e));
                    break;
                case Website.refname:
                case Website.shortname:
                    websites = JPU.addToList(websites, new Website(e));
                    break;
                default:
                    break;
            }
        });
    }

    /**
     * @return whether this tag (<Supplier> or <supplier>) is explicitly provided in the ONIX XML
     */
    @Override
    public boolean exists() {
        return exists;
    }

    @Override
    public org.w3c.dom.Element getXmlElement() {
        return element;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // MEMBERS
    /////////////////////////////////////////////////////////////////////////////////

    private SupplierRole supplierRole = SupplierRole.EMPTY;

    /**
     *

     * An ONIX code identifying the role of the supplier in relation to the product, eg Publisher, Publisher's
     * exclusive distributor, etc. Mandatory in each occurrence of the <Supplier> composite, and
     * non-repeating.
     *

     * Jonix-Comment: this field is required
     */
    public SupplierRole supplierRole() {
        _initialize();
        return supplierRole;
    }

    private ListOfOnixDataCompositeWithKey<SupplierIdentifier, JonixSupplierIdentifier,
        SupplierIdentifierTypes> supplierIdentifiers = ListOfOnixDataCompositeWithKey.emptyKeyed();

    /**
     *

     * A group of data elements which together specify an identifier of the supplier in accordance with a specified
     * scheme, and repeatable to allow different types of supplier identifier to be included without defining additional
     * data elements. Optional, but each occurrence of the <Supplier> composite must carry either at
     * least one supplier identifier, or a <SupplierName>, or both.
     *

     * Jonix-Comment: this list is required to contain at least one item
     */
    public ListOfOnixDataCompositeWithKey<SupplierIdentifier, JonixSupplierIdentifier, SupplierIdentifierTypes>
        supplierIdentifiers() {
        _initialize();
        return supplierIdentifiers;
    }

    private SupplierName supplierName = SupplierName.EMPTY;

    /**
     *

     * The name of a supply source from which the product may be ordered by a trade customer. Optional and
     * non-repeating; required if no supplier identifier is sent.
     *

     * Jonix-Comment: this field is optional
     */
    public SupplierName supplierName() {
        _initialize();
        return supplierName;
    }

    private ListOfOnixElement<TelephoneNumber, String> telephoneNumbers = ListOfOnixElement.empty();

    /**
     *

     * A telephone number of a supply source from which the product may be ordered by a trade customer. Optional and
     * repeatable. Deprecated in this context, in favor of providing contact details in the <SupplyContact>
     * composite.
     *

     * Jonix-Comment: this list may be empty
     */
    public ListOfOnixElement<TelephoneNumber, String> telephoneNumbers() {
        _initialize();
        return telephoneNumbers;
    }

    private ListOfOnixElement<FaxNumber, String> faxNumbers = ListOfOnixElement.empty();

    /**
     *

     * A fax number of a supply source from which the product may be ordered by a trade customer. Optional and
     * repeatable. Deprecated in this context, in favor of providing contact details in the <SupplyContact>
     * composite.
     *

     * Jonix-Comment: this list may be empty
     */
    public ListOfOnixElement<FaxNumber, String> faxNumbers() {
        _initialize();
        return faxNumbers;
    }

    private ListOfOnixElement<EmailAddress, String> emailAddresss = ListOfOnixElement.empty();

    /**
     *

     * An e-mail address for a supply source from which the product may be ordered by a trade customer. Optional and
     * repeatable. Deprecated in this context, in favor of providing contact details in the <SupplyContact>
     * composite.
     *

     * Jonix-Comment: this list may be empty
     */
    public ListOfOnixElement<EmailAddress, String> emailAddresss() {
        _initialize();
        return emailAddresss;
    }

    private ListOfOnixDataComposite<Website, JonixWebsite> websites = ListOfOnixDataComposite.empty();

    /**
     *

     * An optional group of data elements which together identify and provide a pointer to a website which is related to
     * the organization identified in an occurrence of the <Supplier> composite. Repeatable in order to provide
     * links to multiple websites.
     *

     * Jonix-Comment: this list may be empty
     */
    public ListOfOnixDataComposite<Website, JonixWebsite> websites() {
        _initialize();
        return websites;
    }
}


text:
{% extends "base.html" %}

{% block content %}

Edit User

{% include 'flash.html' %}

    <form class="form-horizontal" action="" method="post" name="edit">
        {{form.hidden_tag()}}

            Nickname:

                {{ form.nickname(maxlength = 64, class = "span4") }}
                {% for error in form.errors.nickname %}
                    [{{error}}]

                {% endfor %}

            First name:

                {{ form.first_name(maxlength = 64, class = "span4") }}
                {% for error in form.errors.first_name %}
                    [{{error}}]

                {% endfor %}

            Last name:

                {{ form.last_name(maxlength = 64, class = "span4") }}
                {% for error in form.errors.last_name %}
                    [{{error}}]

                {% endfor %}

            Brief Bio:

                {{ form.about_me(cols = 64, rows = 4, class = "span4") }}
                {% for error in form.errors.about_me %}
                    [{{error}}]

                {% endfor %}

            Is active? (don't delete users, mark them as inactive)

                {{ form.is_active() }}
                {% for error in form.errors.is_active %}
                    [{{error}}]

                {% endfor %}

            RFID Access?

                {{ form.rfid_access() }}
                {% for error in form.errors.rfid_access %}
                    [{{error}}]

                {% endfor %}

            RFID Tag:

                {{ form.rfid_tag(cols = 20, rows = 1, class = "span4") }}
                {% for error in form.errors.rfid_tag %}
                    [{{error}}]

                {% endfor %}

                <input class="btn btn-primary" type="submit" value="Save Changes">

    </form>

</form>
{% endblock %}


text:
package org.jetbrains.plugins.groovy.refactoring.introduce.field;

import com.intellij.psi.PsiType;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier;
import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceContext;
import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceDialog;

/**
* @author Maxim.Medvedev
*/
class IntroduceFieldTestHandler extends GrIntroduceFieldHandler {

  private boolean myIsStatic;
  private boolean myRemoveLocal;
  private boolean myDeclareFinal;
  private GrIntroduceFieldSettings.Init myInitializeIn;
  private boolean replaceAll;
  private PsiType mySelectedType;

  IntroduceFieldTestHandler(boolean isStatic,
                            boolean removeLocal,
                            boolean declareFinal,
                            GrIntroduceFieldSettings.Init initializeIn,
                            boolean replaceAll,
                            PsiType selectedType) {
    myIsStatic = isStatic;
    myRemoveLocal = removeLocal;
    myDeclareFinal = declareFinal;
    myInitializeIn = initializeIn;
    this.replaceAll = replaceAll;
    mySelectedType = selectedType;
  }

  @Override
  protected GrIntroduceDialog<GrIntroduceFieldSettings> getDialog(GrIntroduceContext context) {
    return new GrIntroduceDialog<GrIntroduceFieldSettings>() {
      @Override
      public GrIntroduceFieldSettings getSettings() {
        return new GrIntroduceFieldSettings() {
          @Override
          public boolean declareFinal() {
            return myDeclareFinal;
          }

          @Override
          public Init initializeIn() {
            return myInitializeIn;
          }

          @Override
          public String getVisibilityModifier() {
            return GrModifier.PACKAGE_LOCAL;
          }

          @Override
          public boolean isStatic() {
            return myIsStatic;
          }

          @Override
          public boolean removeLocalVar() {
            return myRemoveLocal;
          }

          @Override
          public String getName() {
            return "f";
          }

          @Override
          public boolean replaceAllOccurrences() {
            return replaceAll;
          }

          @Override
          public PsiType getSelectedType() {
            return mySelectedType;
          }
        };
      }

      @Override
      public void show() {
      }

      @Override
      public boolean isOK() {
        return true;
      }
    };
  }
}


text:
/* eslint-env jest */
import reducer, * as Confirm from 'redux/confirm';

describe('Confirm actions', () => {
  it('should create action to show confirm', () => {
    const onConfirm = () => ({});
    const expected = {
      type: Confirm.SHOW_CONFIRMATION,
      payload: {
        text: 'Confirm?',
        onConfirm,
      },
    };

    expect(Confirm.showConfirmation({
      text: 'Confirm?',
      onConfirm,
    })).toEqual(expected);
  });

  it('should create action to hide confirm', () => {
    const expected = {
      type: Confirm.HIDE_CONFIRMATION,
      payload: {},
    };

    expect(Confirm.hideConfirmation()).toEqual(expected);
  });
});

describe('Confirm reducer', () => {
  it('should return the initial state', () => {
    expect(
      reducer(undefined, {})
    ).toEqual(Confirm.initialState);
  });

  it('should handle SHOW_CONFIRM', () => {
    const onConfirm = () => ({});

    const action = {
      type: Confirm.SHOW_CONFIRMATION,
      payload: {
        text: 'Confirm?',
        onConfirm,
      },
    };

    const expected = {
      ...Confirm.initialState,
      isVisible: true,
      text: 'Confirm?',
      onConfirm,
    };

    expect(
      reducer(Confirm.initialState, action)
    ).toEqual(expected);
  });

  it('should handle HIDE_CONFIRM', () => {
    const onConfirm = () => ({});

    const initialState = {
      ...Confirm.initialState,
      isVisible: true,
      text: 'Confirm?',
      onConfirm,
    };

    const action = {
      type: Confirm.HIDE_CONFIRMATION,
      payload: {},
    };

    expect(
      reducer(initialState, action)
    ).toEqual(Confirm.initialState);
  });
});


text:
download_mapping_windows = {
    "https://github.com/nlohmann/json/releases/download/v3.2.0/json.hpp" : "../../Common/Lib/Ext/json/json-3.2.0/single_include/nlohmann"
}
download_mapping_linux = {
    "https://github.com/nlohmann/json/releases/download/v3.2.0/json.hpp" : "../../Common/Lib/Ext/json/json-3.2.0/single_include/nlohmann"
}

# Some repos are only hosted on github - these are defined with an absolute URL based here
github_root = "https://github.com/GPUOpen-Tools/"

# repositories.
git_mapping = {
}

github_mapping = {
 # Lib.
    "common-lib-amd-ADL"                  : ["Common/Lib/AMD/ADL",               "master"],
    "common-lib-amd-APPSDK-3.0"           : ["Common/Lib/AMD/APPSDK",            "master"],
    "common-lib-ext-Boost-1.59"           : ["Common/Lib/Ext/Boost",             "master"],
    "common-lib-ext-WindowsKits"          : ["Common/Lib/Ext/Windows-Kits",      "master"],
    "common-lib-ext-tinyxml2-5.0.1"       : ["Common/Lib/Ext/tinyxml2",          "master"],
    "cxxopts"                             : ["Common/Lib/Ext/cxxopts",           "master"],
    "volk"                                : ["Common/Lib/Ext/volk",              "master"],
 # Src.
    "common-src-ADLUtil"                  : ["Common/Src/ADLUtil",               "master"],
    "common-src-DynamicLibraryModule"     : ["Common/Src/DynamicLibraryModule",  "master"],
    "common-src-TSingleton"               : ["Common/Src/TSingleton",            "master"],
    "common-src-Miniz"                    : ["Common/Src/Miniz",                 "master"],
    "update_check_api"                    : ["Common/Src/update_check_api",      "v2.0.0"],
    "common-src-DeviceInfo"               : ["Common/Src/DeviceInfo",            "rga-v2.6"],
 # QtCommon.
    "QtCommon"                            : ["QtCommon",                         "rga-2.5"],
}


text:
package main

import (
	"bytes"
	"encoding/gob"
	"io/ioutil"
	"os"
	"path"
)

// Saver persists any game state that needs to be remembered between one
// game session and the next. Saver needs to be public and visible for
// the encoding package.
type Saver struct {
	File       string // Save file name.
	Kbinds     []int  // Key bindings.
	X, Y, W, H int    // Window location.
	Mute       bool   // True if the game is muted.
	Full       bool   // True if the game is fullscreen.
}

// newSaver creates default persistent application state. The directory
// is platform specific and specified by:
//    osx  : see saver_darwin.go
//    win  : see saver_windows.go
//    lin  : FUTURE
func newSaver() *Saver {
	s := &Saver{}
	s.Kbinds = []int{}
	dir := s.directoryLocation()
	if err := os.MkdirAll(dir, 0755); err != nil {
		dir = ""
	}
	s.File = path.Join(dir, "bampf.save")
	return s
}

// persistBindings saves the new keybindings, while preserving the other
// information.
func (s *Saver) persistBindings(keys []int) {
	s.restore()
	s.Kbinds = keys
	s.persist()
}

// persistWindow saves the new window location and size, while preserving
// the other information.
func (s *Saver) persistWindow(x, y, w, h int, fullScreen bool) {
	s.restore()
	s.Full = fullScreen
	if !s.Full {
		// only save dimensions when not full screen.
		s.X, s.Y, s.W, s.H = x, y, w, h
	}
	s.persist()
}

// persistMute saves the mute preference while preserving
// the other information.
func (s *Saver) persistMute(isMuted bool) {
	s.restore()
	s.Mute = isMuted
	s.persist()
}

// persist is called to record any user preferences. This is expected
// to be called when a user preference changes.
func (s *Saver) persist() {
	data := &bytes.Buffer{}
	enc := gob.NewEncoder(data) // saves
	if err := enc.Encode(s); err == nil {
		if err = ioutil.WriteFile(s.File, data.Bytes(), 0644); err != nil {
			logf("Failed to save game state: %s", err)
		}
	} else {
		logf("Failed to encode game state: %s", err)
	}
}

// restore reads persisted information from disk. It handles the case where
// a previous restore file doesn't exist.
func (s *Saver) restore() {
	if bites, err := ioutil.ReadFile(s.File); err == nil {
		data := bytes.NewBuffer(bites)
		dec := gob.NewDecoder(data)
		if err := dec.Decode(s); err != nil {
			logf("Failed to restore game state. %s", err)
		}
	}
}

// reset clears the saved file.
func (s *Saver) reset() {
	os.Remove(s.File)
}


text:
class WXDLLIMPEXP_CORE wxPanel : public wxPanelBase
{
public:
    wxPanel() { }

    wxPanel(wxWindow *parent,
            wxWindowID winid = wxID_ANY,
            const wxPoint& pos = wxDefaultPosition,
            const wxSize& size = wxDefaultSize,
            long style = wxTAB_TRAVERSAL | wxNO_BORDER,
            const wxString& name = wxPanelNameStr)
    {
        Create(parent, winid, pos, size, style, name);
    }

    virtual bool IsCanvasWindow() const { return true; }

#if WXWIN_COMPATIBILITY_2_8
    wxDEPRECATED_CONSTRUCTOR(
    wxPanel(wxWindow *parent,
            int x, int y, int width, int height,
            long style = wxTAB_TRAVERSAL | wxNO_BORDER,
            const wxString& name = wxPanelNameStr)
    {
        Create(parent, wxID_ANY, wxPoint(x, y), wxSize(width, height), style, name);
    }
    )
#endif // WXWIN_COMPATIBILITY_2_8

private:
    wxDECLARE_DYNAMIC_CLASS_NO_COPY(wxPanel);
};

#endif // _WX_UNIV_PANEL_H_


text:
template <class T>
class graph{
    public:
        graph():top(0),length(0){
            std::cout << "[Hello world! I am a new graph on address "<<this<<"]"<<std::endl;
        }
        ~graph(){
            this->free_();
            std::cout << "[Goodbye cruel world! I was a graph on address "<<this<<"]"<<std::endl;
        }
        void vertex_push(T value){
            std::cout << "[PUSH_VERTEX]";
            vertex<T>* next = this->top;
            vertex<T>* prev = NULL;
            std::size_t position = 1;
            while(next){
                prev = next;
                position++;
                if(prev && prev->next)
                    next = (*prev)++;
                else
                    next = NULL;
            }
            this->vertex_push_(prev, value);
            std::cout << " position::[" << position << "]::value::[" << value <<"] ";
            std::cout << "prev::["<<prev<<"]" << std::endl;
        }
        void edge_push(T element, T connection){
            if(this->top){
                vertex<T>* iterator = this->top;
                vertex<T>* start = NULL;
                vertex<T>* end = NULL;
                while(iterator){
                    if(iterator->value == element)
                        start = iterator;
                    if(iterator->value == connection)
                        end = iterator;
                    iterator = (*iterator)++;
                }
                if(start && end){
                    this->edge_push(start, end);
                }else{
                    this->free_();
                    throw std::invalid_argument("cannot push the edge");
                }
            }
        }
        void edge_push(vertex<T>* element, vertex<T>* connection){
            std::cout << "[PUSH_EDGE] vertex address::[" << element << "]-->[" << connection <<"] "<< std::endl;
            if(this->top){
                if(!element->edges){
                    this->edge_push_(element, connection);
                }else{
                    edge<T>* next = element->edges;
                    edge<T>* prev = NULL;
                    while(next){
                        prev = next;
                        if(next->connects_to == connection){
                            std::cout<< "[ERROR]::[THE CONNECTION ALREADY EXISTS]"<<std::endl;
                            return;
                        }
                        else if(prev && prev->next)
                            next = (*prev)++;
                        else
                            next = NULL;
                    }
                    this->edge_push_(prev, connection);
                }
            }else{
                this->free_();
                throw std::invalid_argument("cannot push the edge");
            }
        }
        void print(){
            if(this->top){
                std::cout<<"=========================="<<std::endl;
                std::cout<<"[PRINT] graph length::["<<this->length<<"]"<<std::endl;
                const vertex<T>* iterator;
                for(iterator=this->top; iterator; iterator=(*iterator)++){
                    std::cout<<"vertex address::["<<iterator<<"], value::["<<iterator->value<<"]"<< std::endl;
                    this->edge_print(iterator);
                }
            }
        }
        void edge_print(const vertex<T>* element){
            if(element->edges){
                const edge<T>* iterator;
                for(iterator=element->edges; iterator; iterator=(*iterator)++){
                    std::cout<<"edge address::["<<iterator<<"]-->["<<iterator->connects_to<<"]::value::["<<iterator->connects_to->value<<"]"<<std::endl;
                }
            }
        }
        bool* is_reachable(T source, T destination){
            if(this->top){
                vertex<T>* iterator = this->top;
                vertex<T>* start = NULL;
                vertex<T>* end = NULL;
                while(iterator){
                    iterator->visited = false;
                    if(iterator->value == source){
                        start = iterator;
                        //std::cout<<"[START] address::["<<start<<"]::value::["<<start->value<<"]"<< std::endl;
                    }
                    if(iterator->value == destination){
                        end = iterator;
                        //std::cout<<"[END] address::["<<end<<"]::value::["<<end->value<<"]"<< std::endl;
                    }
                    iterator = (*iterator)++;
                }
                if(start && end){
                    return (this->is_reachable_(start, end))
                    std::cout<<"[IS_REACHABLE] ["<<source<<"]-->["<<destination<<"]"<<std::endl;
                }else{
                    return false;
                }
            }
        }
    private:
        void vertex_push_(vertex<T>* prev, T value){
            vertex<T>* tmp = new vertex<T>(value, NULL, NULL);
            this->length++;
            if(!prev)
                this->top = tmp;
            else
                prev->next = tmp;
        }
        void edge_push_(vertex<T>* element, vertex<T>* connection){
            element->edges = new edge<T>(connection, NULL);
        }
        void edge_push_(edge<T>* element, vertex<T>* connection){
            edge<T>* tmp = new edge<T>(connection, NULL);
            element->next = tmp;
        }
        bool is_reachable_(vertex<T>* source, vertex<T>* destination){
            if(source->visited)
                return false;
            else if(source == destination)
                return true;
            source->visited = true;
            if(source->edges){
                edge<T>* iterator = source->edges;
                while(iterator){
                    //std::cout<<"[ITERATOR]::["<<iterator->connects_to<<"]::[VALUE]::["<<iterator->connects_to->value<<"] [DESTINATION]::["<<destination<<"]"<<std::endl;
                    if(this->is_reachable_(iterator->connects_to, destination))
                        return true;
                    iterator = (*iterator)++;
                }
            }
            return false;
        }
        void free_(){
            vertex<T>* next = this->top;
            vertex<T>* prev = NULL;
            std::cout<<"=========================="<<std::endl;
            std::cout << "[FREE_GRAPH] length::[" << this->length << "]" << std::endl;
            while(next){
                std::cout << "[FREE] vertex address::["<<next<<"]::value::["<<next->value<<"]"<< std::endl;
                prev = next;
                this->edge_free_(prev);
                if(prev && prev->next)
                    next = (*prev)++;
                else
                    next = NULL;
                delete prev;
                std::cout << "freed!" << std::endl;
            }
            this->length=0;
        }
        void edge_free_(vertex<T>* element){
            if(element->edges){
                edge<T>* next = element->edges;
                edge<T>* prev = NULL;
                while(next){
                    std::cout << "[FREE] edge address::[" << next << "] "<< std::endl;
                    prev = next;
                    if(prev && prev->next)
                        next = (*prev)++;
                    else
                        next = NULL;
                    delete prev;
                }
            }
        }
        std::size_t length;
        vertex<T>* top;
};
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>io.dropwizard.metrics</groupId>
        <artifactId>metrics-parent</artifactId>
        <version>4.0.0-SNAPSHOT</version>
    </parent>

    <artifactId>metrics-json</artifactId>
    <name>Jackson Integration for Metrics</name>
    <packaging>bundle</packaging>
    <description>
        A set of Jackson modules which provide serializers for most Metrics classes.
    </description>

    <dependencies>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-core</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>io.dropwizard.metrics</groupId>
            <artifactId>metrics-healthchecks</artifactId>
            <version>${project.version}</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>
</project>


text:
struct Foo {
  Foo();
  Foo(int);
  Foo(int, int);
  ~Foo();
};

struct Bar {
  Bar();
};

struct FooBar {
  FooBar();
  Foo f;
};

template <typename T>
void qux() {
  T(42);
}

template <typename T>
struct TFoo {
  TFoo(T);
  ~TFoo();
};

Foo f();

struct Ctor {
  Ctor(int);
  Ctor() {
    Ctor(0); // TODO: warn here.
  }
};

void test() {
  Foo(42);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object?
// CHECK-FIXES: Foo give_me_a_name(42);
  Foo(23, 42);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object?
// CHECK-FIXES: Foo give_me_a_name(23, 42);
  Foo();
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object?
// CHECK-FIXES: Foo give_me_a_name;
  TFoo<int>(23);
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object?
// CHECK-FIXES: TFoo<int> give_me_a_name(23);

  FooBar();
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: object destroyed immediately after creation; did you mean to name the object?
// CHECK-FIXES: FooBar give_me_a_name;

  Bar();
  f();
  qux<Foo>();

#define M Foo();
  M

  {
    Foo();
  }
  Foo();
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd">
<!-- Copyright © 1991-2014 Unicode, Inc.
CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/)
For terms of use, see http://www.unicode.org/copyright.html
-->
<ldml>
	<identity>
		<version number="$Revision: 11072 $"/>
		<generation date="$Date: 2014-12-04 15:58:51 -0800 (Thu, 04 Dec 2014) $"/>
		<language type="nmz"/>
		<script type="Latn"/>
	</identity>
	<layout>
		<orientation>
			<characterOrder>left-to-right</characterOrder>
			<lineOrder>top-to-bottom</lineOrder>
		</orientation>
	</layout>
	<characters>
		<exemplarCharacters draft="unconfirmed">[ʹ a á à b d e ɛ f g {g\u0308} {gb} {gw} h ɦ i j k {kp} {kw} l m n {n\u0308} {ny} ŋ {ŋ\u0308} {ŋm} o ɔ r s t u v w y]</exemplarCharacters>
		<exemplarCharacters type="auxiliary" draft="unconfirmed">[c p q x z]</exemplarCharacters>
		<exemplarCharacters type="index" draft="unconfirmed">[A B D E Ɛ F G {Gb} {Gw} H Ĥ I J K {Kp} {Kw} L M N {Ny} Ŋ {Ŋm} O Ɔ R S T U V W Y]</exemplarCharacters>
	</characters>
</ldml>


text:
/**
 * @file
 * @author Jernej Kovacic
 *
 * An internal header file, it should not be included directly.
 * @headername{ChiSquareDist.h}
 *
 * Declaration and implementation of functions within the namespace
 * ChiSquareDist that perform various chi-squared distribution related
 * operations, such as calculation of upper and lower tail
 * probabilities and quantiles, probability distribution function, etc.
 */

/*
 * More details about the Chi-squared distribution:
 * https://en.wikipedia.org/wiki/Chi-squared_distribution
 */

#ifndef _MATH_CHISQUAREDISTGENERIC_HPP_
#define _MATH_CHISQUAREDISTGENERIC_HPP_

#include <cmath>
#include <algorithm>

#include "../settings/probdist_settings.h"

#include "util/NumericUtil.hpp"
#include "specfun/SpecFunGeneric.hpp"
#include "exception/SpecFunException.hpp"
#include "exception/StatisticsException.hpp"

namespace math
{

/**
 * @brief A namespace with functions that perform
 * various chi-squared distribution related operations, such as
 * calculation of upper and lower tail probabilities and
 * quantiles, probability distribution function, etc.
 */
namespace ChiSquareDist
{

namespace __private
{

/*
 * Checks the validity of arguments 'x' (must be greater than or equal
 * to 0) and 'df' (must be strictly greater than 0).
 *
 * @param x - value to check
 * @param df - degrees of freedom to check
 *
 * @throw StatisticsException if any argument is invalid.
 */
template <typename F>
void __checkParams(const F& x, const F& df)
{
    if ( x < static_cast<F>(0) )
    {
        throw math::StatisticsException(math::StatisticsException::INVALID_ARG);
    }

    if (df < math::NumericUtil::getEPS<F>() )
    {
        throw math::StatisticsException(math::StatisticsException::INVALID_DF);
    }
}

}  // namespace math::ChiSquareDist::__private

/**
 * Value of the chi-square distribution's probability distribution
 * function (pdf) for the given 'x'.
 *
 * @param x - value to be calculated its probability distribution function
 * @param df - degrees of freedom
 *
 * @return pdf(x, df)
 *
 * @throw StatisticsException if any argument is invalid
 */
template <typename F>
F pdf(
	  const F& x,
	  const F& df
	)
{
    /*
     * Probability density function of the chi-squared distribution:
     *
     *               1          -df/2    df/2 - 1    -x/2
     *   pdf = ------------- * 2      * x         * e
     *          gamma(df/2)
     *
     */

    // sanity check:
    math::ChiSquareDist::__private::__checkParams<F>(x, df);

    const F df2 = df / static_cast<F>(2);
    return std::pow(static_cast<F>(2), -df2) * std::pow(x, df2 - static_cast<F>(1) ) *
           std::exp(-x / static_cast<F>(2)) / math::SpecFun::gamma<F>(df2);
}

/**
 * Probability that a value is greater or smaller (depending on 'lowerTail')
 * than the given value 'x' for the specified chi-squared distribution.
 *
 * @param x - value
 * @param df - degrees of freedom
 * @param lowerTail - if true, returns P(X<x), otherwise P(X>x) (default: true)
 *
 * @return P(X<x) if 'lowerTail' equals true, P(X>x) if 'lowerTail' equals false
 *
 * @throw StatisticsException if any argument is invalid
 */
template <typename F>
F prob(
	  const F& x,
	  const F& df,
	  const bool lowerTail = true
   )
{
    /*
     * The 'cdf' represents probability that a value from the chi-squared
     * distribution is smaller than a specified value 'x' and can be
     * expressed as:
     *
     *           /  df    x  \
     *   cdf = P | ----, --- |
     *           \   2    2  /
     *
     * where P(a,x) denotes the regularized lowered incomplete gamma function,
     * implemented in the namespace math::SpecFun.
     *
     * For the upper tail probability ( P(X>x) ) just return the complement
     * of the lower tail probability: 1 - cdf(x)
     */

    // sanity check
    math::ChiSquareDist::__private::__checkParams<F>(x, df);

    try
    {
        // Tolerance for the algorithm that evaluates the incomplete gamma function:
        const F TOL = static_cast<F>(PROBDIST_PROB_TOL_NUM) /
                      static_cast<F>(PROBDIST_PROB_TOL_DEN);

        const F cdf = math::SpecFun::incGammaLowerReg<F>(
              df / static_cast<F>(2), x / static_cast<F>(2), TOL);

        // the return value depends on 'lowerTail':
        return ( true==lowerTail ? cdf : static_cast<F>(1)-cdf );
    }
    catch ( const math::SpecFunException& sfex )
    {
        throw math::StatisticsException::OPERATION_FAILED;
    }
}

/**
 * Probability in the chi-squared distribution with the specified
 * degrees of freedom that 'x' is greater than 'a' and less  than 'b'
 * (or vice versa if b<a).
 *
 * @note 'a' and 'b' are interchangeable, the result's sign will
 *       not change in this case.
 *
 * @param a - lower limit of the interval
 * @param b - upper limit of the interval
 * @param df - degrees of freedom
 *
 * @return P(a<X<b) or P(b<X<a)
 *
 * @throw StatisticsException if any argument is invalid
 */
template <typename F>
F probInt(
	  const F& a,
	  const F& b,
	  const F& df
	)
{
    /*
     *              b
     *              /
     *   P(a<X<b) = | pdf(t) dt  =  cdf(b) - cdf(a)
     *              /
     *              a
     */

    // Sanity check will be performed by prob()

    const F from = std::min(a, b);
    const F to = std::max(a, b);

    return math::ChiSquareDist::prob<F>(to, df, true) -
           math::ChiSquareDist::prob<F>(from, df, true);
}

/**
 * Quantile function for the chi-squared distribution with the specified
 * number of degrees of freedom.
 *
 * If 'lowerTail' equals true, it returns such 'x' that P(X<x) = p
 * If 'lowerTail' equals false, it returns such 'x' that P(X>x) = p
 *
 * @param p - probability (must be greater than 0 and less than 1)
 * @param df - degrees of freedom
 * @param lowerTail - if true, returns q(X<x), otherwise q(X>x) (default: true)
 *
 * @return x: P(X<x) if 'lowerTail' equals true, x: P(X>x) if 'lowerTail' equals false
 *
 * @throw StatisticsException if any argument is invalid
 */
template <typename F>
F quant(
	  const F& p,
	  const F& df,
	  const bool lowerTail = true
	)
{
    // sanity check
    math::ChiSquareDist::__private::__checkParams<F>(static_cast<F>(1), df);
    if ( p <= math::NumericUtil::getEPS<F>() ||
         p >= static_cast<F>(1) - math::NumericUtil::getEPS<F>() )
    {
        throw math::StatisticsException(math::StatisticsException::INVALID_PROBABILTY);
    }

    /*
     * Quantile is a value of 'x' that solves the nonlinear equation:
     *
     *   cdf(x) = p
     *
     * If the cumulative density function is expressed as:
     *
     *                      /  df    x  \
     *   cdf(df,x) = p =  P | ----, --- |
     *                      \   2    2  /
     *
     * the following expression for 'x' can be derived quickly:
     *
     *            -1 /  df     \
     *   x = 2 * P   | ----, p |
     *               \   2     /
     */

    try
    {
        // The actual probability in the expressions above depends on 'lowerTail':
        const F P = (true==lowerTail ? p : static_cast<F>(1)-p);

        // Tolerance for the algorithm that evaluates pInv():)
        const F TOL = static_cast<F>(PROBDIST_PROB_TOL_NUM) /
                      static_cast<F>(PROBDIST_PROB_TOL_DEN);

        return math::SpecFun::incGammaLowerRegInv<F>(df / static_cast<F>(2), P, TOL) *
               static_cast<F>(2);
    }
    catch ( const math::SpecFunException& sfex )
    {
        /*
         * The validity of 'p' is checked beforehand.
         * Although very unlikely, it is theoretically possible that
         * the algorithm to evaluate incGammaLowerRegInv will
         * not converge.
         */
        throw math::StatisticsException(math::StatisticsException::OPERATION_FAILED);
    }
}

}  // namespace ChiSquareDist

}  // namespace math

#endif  // _MATH_CHISQUAREDISTGENERIC_HPP_


text:
import pandas as pd
import shutil, os
import os.path as osp
import torch
import numpy as np
from dgl.data.utils import load_graphs, save_graphs, Subset
import dgl
from ogb.utils.url import decide_download, download_url, extract_zip
from ogb.io.read_graph_dgl import read_graph_dgl

class DglGraphPropPredDataset(object):
    '''Adapted from https://docs.dgl.ai/en/latest/_modules/dgl/data/chem/csv_dataset.html#CSVDataset'''
    def __init__(self, name, root = 'dataset', meta_dict = None):
        '''
            - name (str): name of the dataset
            - root (str): root directory to store the dataset folder

            - meta_dict: dictionary that stores all the meta-information about data. Default is None,
                    but when something is passed, it uses its information. Useful for debugging for external contributers.
        '''

        self.name = name ## original name, e.g., ogbg-molhiv

        if meta_dict is None:
            self.dir_name = '_'.join(name.split('-'))

            # check if previously-downloaded folder exists.
            # If so, use that one.
            if osp.exists(osp.join(root, self.dir_name + '_dgl')):
                self.dir_name = self.dir_name + '_dgl'

            self.original_root = root
            self.root = osp.join(root, self.dir_name)

            master = pd.read_csv(os.path.join(os.path.dirname(__file__), 'master.csv'), index_col = 0)
            if not self.name in master:
                error_mssg = 'Invalid dataset name {}.\n'.format(self.name)
                error_mssg += 'Available datasets are as follows:\n'
                error_mssg += '\n'.join(master.keys())
                raise ValueError(error_mssg)
            self.meta_info = master[self.name]

        else:
            self.dir_name = meta_dict['dir_path']
            self.original_root = ''
            self.root = meta_dict['dir_path']
            self.meta_info = meta_dict

        # check version
        # First check whether the dataset has been already downloaded or not.
        # If so, check whether the dataset version is the newest or not.
        # If the dataset is not the newest version, notify this to the user.
        if osp.isdir(self.root) and (not osp.exists(osp.join(self.root, 'RELEASE_v' + str(self.meta_info['version']) + '.txt'))):
            print(self.name + ' has been updated.')
            if input('Will you update the dataset now? (y/N)\n').lower() == 'y':
                shutil.rmtree(self.root)

        self.download_name = self.meta_info['download_name'] ## name of downloaded file, e.g., tox21

        self.num_tasks = int(self.meta_info['num tasks'])
        self.eval_metric = self.meta_info['eval metric']
        self.task_type = self.meta_info['task type']
        self.num_classes = self.meta_info['num classes']
        self.binary = self.meta_info['binary'] == 'True'

        super(DglGraphPropPredDataset, self).__init__()

        self.pre_process()

    def pre_process(self):
        processed_dir = osp.join(self.root, 'processed')
        raw_dir = osp.join(self.root, 'raw')
        pre_processed_file_path = osp.join(processed_dir, 'dgl_data_processed')

        if self.task_type == 'subtoken prediction':
            target_sequence_file_path = osp.join(processed_dir, 'target_sequence')

        if os.path.exists(pre_processed_file_path):

            if self.task_type == 'subtoken prediction':
                self.graphs, _ = load_graphs(pre_processed_file_path)
                self.labels = torch.load(target_sequence_file_path)

            else:
                self.graphs, label_dict = load_graphs(pre_processed_file_path)
                self.labels = label_dict['labels']

        else:
            ### check download
            if self.binary:
                # npz format
                has_necessary_file = osp.exists(osp.join(self.root, 'raw', 'data.npz'))
            else:
                # csv file
                has_necessary_file = osp.exists(osp.join(self.root, 'raw', 'edge.csv.gz'))

            ### download
            if not has_necessary_file:
                url = self.meta_info['url']
                if decide_download(url):
                    path = download_url(url, self.original_root)
                    extract_zip(path, self.original_root)
                    os.unlink(path)
                    # delete folder if there exists
                    try:
                        shutil.rmtree(self.root)
                    except:
                        pass
                    shutil.move(osp.join(self.original_root, self.download_name), self.root)
                else:
                    print('Stop download.')
                    exit(-1)

            ### preprocess
            add_inverse_edge = self.meta_info['add_inverse_edge'] == 'True'

            if self.meta_info['additional node files'] == 'None':
                additional_node_files = []
            else:
                additional_node_files = self.meta_info['additional node files'].split(',')

            if self.meta_info['additional edge files'] == 'None':
                additional_edge_files = []
            else:
                additional_edge_files = self.meta_info['additional edge files'].split(',')

            graphs = read_graph_dgl(raw_dir, add_inverse_edge = add_inverse_edge, additional_node_files = additional_node_files, additional_edge_files = additional_edge_files, binary=self.binary)

            if self.task_type == 'subtoken prediction':
                # the downloaded labels are initially joined by ' '
                labels_joined = pd.read_csv(osp.join(raw_dir, 'graph-label.csv.gz'), compression='gzip', header = None).values
                # need to split each element into subtokens
                labels = [str(labels_joined[i][0]).split(' ') for i in range(len(labels_joined))]

                print('Saving...')
                save_graphs(pre_processed_file_path, graphs)
                torch.save(labels, target_sequence_file_path)

                ### load preprocessed files
                self.graphs, _ = load_graphs(pre_processed_file_path)
                self.labels = torch.load(target_sequence_file_path)

            else:
                if self.binary:
                    labels = np.load(osp.join(raw_dir, 'graph-label.npz'))['graph_label']
                else:
                    labels = pd.read_csv(osp.join(raw_dir, 'graph-label.csv.gz'), compression='gzip', header = None).values

                has_nan = np.isnan(labels).any()

                if 'classification' in self.task_type:
                    if has_nan:
                        labels = torch.from_numpy(labels).to(torch.float32)
                    else:
                        labels = torch.from_numpy(labels).to(torch.long)
                else:
                    labels = torch.from_numpy(labels).to(torch.float32)

                print('Saving...')
                save_graphs(pre_processed_file_path, graphs, labels={'labels': labels})

                ### load preprocessed files
                self.graphs, label_dict = load_graphs(pre_processed_file_path)
                self.labels = label_dict['labels']

    def get_idx_split(self, split_type = None):
        if split_type is None:
            split_type = self.meta_info['split']

        path = osp.join(self.root, 'split', split_type)

        # short-cut if split_dict.pt exists
        if os.path.isfile(os.path.join(path, 'split_dict.pt')):
            return torch.load(os.path.join(path, 'split_dict.pt'))

        train_idx = pd.read_csv(osp.join(path, 'train.csv.gz'), compression='gzip', header = None).values.T[0]
        valid_idx = pd.read_csv(osp.join(path, 'valid.csv.gz'), compression='gzip', header = None).values.T[0]
        test_idx = pd.read_csv(osp.join(path, 'test.csv.gz'), compression='gzip', header = None).values.T[0]

        return {'train': torch.tensor(train_idx, dtype = torch.long), 'valid': torch.tensor(valid_idx, dtype = torch.long), 'test': torch.tensor(test_idx, dtype = torch.long)}

    def __getitem__(self, idx):
        '''Get datapoint with index'''

        if isinstance(idx, int):
            return self.graphs[idx], self.labels[idx]
        elif torch.is_tensor(idx) and idx.dtype == torch.long:
            if idx.dim() == 0:
                return self.graphs[idx], self.labels[idx]
            elif idx.dim() == 1:
                return Subset(self, idx.cpu())

        raise IndexError(
            'Only integers and long are valid '
            'indices (got {}).'.format(type(idx).__name__))

    def __len__(self):
        '''Length of the dataset
        Returns
        -------
        int
            Length of Dataset
        '''
        return len(self.graphs)

    def __repr__(self):  # pragma: no cover
        return '{}({})'.format(self.__class__.__name__, len(self))

# Collate function for ordinary graph classification
def collate_dgl(samples):
    graphs, labels = map(list, zip(*samples))
    batched_graph = dgl.batch(graphs)

    if isinstance(labels[0], torch.Tensor):
        return batched_graph, torch.stack(labels)
    else:
        return batched_graph, labels

if __name__ == '__main__':
    dgl_dataset = DglGraphPropPredDataset(name = 'ogbg-molhiv')
    print(dgl_dataset.num_classes)
    split_index = dgl_dataset.get_idx_split()
    print(dgl_dataset)
    print(dgl_dataset[0])
    print(dgl_dataset[0][1].dtype)
    print(dgl_dataset[split_index['train']])
    print(dgl_dataset[split_index['valid']])
    print(dgl_dataset[split_index['test']])
    # print(collate_dgl([dgl_dataset[0], dgl_dataset[1], dgl_dataset[2]]))


text:
<?php namespace Vinelab\NeoEloquent\Console\Migrations;

use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
use Symfony\Component\Console\Input\InputOption;

class MigrateRefreshCommand extends Command {

    use ConfirmableTrait;

    /**
     * {@inheritDoc}
     */
    protected $name = 'neo4j:migrate:refresh';

    /**
     * {@inheritDoc}
     */
    protected $description = 'Reset and re-run all migrations';

    /**
     * {@inheritDoc}
     */
    public function handle()
    {
        if ( ! $this->confirmToProceed()) return;

        $database = $this->input->getOption('database');

        $force = $this->input->getOption('force');

        $this->call('migrate:reset', array(
            '--database' => $database, '--force' => $force
        ));

        // The refresh command is essentially just a brief aggregate of a few other of
        // the migration commands and just provides a convenient wrapper to execute
        // them in succession. We'll also see if we need to re-seed the database.
        $this->call('migrate', array(
            '--database' => $database, '--force' => $force
        ));

        if ($this->needsSeeding())
        {
            $this->runSeeder($database);
        }
    }

    /**
     * Determine if the developer has requested database seeding.
     *
     * @return bool
     */
    protected function needsSeeding()
    {
        return $this->option('seed') || $this->option('seeder');
    }

    /**
     * Run the database seeder command.
     *
     * @param  string  $database
     * @return void
     */
    protected function runSeeder($database)
    {
        $class = $this->option('seeder') ?: 'DatabaseSeeder';

        $this->call('db:seed', array('--database' => $database, '--class' => $class));
    }

    /**
     * {@inheritDoc}
     */
    protected function getOptions()
    {
        return array(
            array('database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use.'),

            array('force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'),

            array('seed', null, InputOption::VALUE_NONE, 'Indicates if the seed task should be re-run.'),

            array('seeder', null, InputOption::VALUE_OPTIONAL, 'The class name of the root seeder.'),
        );
    }

}


text:
namespace WPF.GettingStarted
{
    using System.Windows;
    using Catel.IoC;
    using Catel.Services;
    using Catel.Windows;
    using WPF.GettingStarted.Services;
    using WPF.GettingStarted.ViewModels;
    using WPF.GettingStarted.Views;

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Application.Startup"/> event.
        /// </summary>
        /// <param name="e">A <see cref="T:System.Windows.StartupEventArgs"/> that contains the event data.</param>
        protected override void OnStartup(StartupEventArgs e)
        {
#if DEBUG
            Catel.Logging.LogManager.AddDebugListener();
#endif

            StyleHelper.CreateStyleForwardersForDefaultStyles();

            var serviceLocator = ServiceLocator.Default;
            serviceLocator.RegisterType<IFamilyService, FamilyService>();

            var uiVisualizerService = serviceLocator.ResolveType<IUIVisualizerService>();
            uiVisualizerService.Register(typeof(PersonViewModel), typeof(PersonWindow));

            base.OnStartup(e);
        }
    }
}


text:
<?php
/**
 * Chunk English lexicon topic
 *
 * @language en
 * @package modx
 * @subpackage lexicon
 */
$_lang['chunk'] = 'מיני תבנית';
$_lang['chunk_desc_category'] = 'הקטגוריה אליה מיני תבנית זו משוייכת.';
$_lang['chunk_desc_description'] = 'תאור קצת של למיני תבנית זו.';
$_lang['chunk_desc_name'] = 'שם המיני תבנית. יהיה זמין על ידי שימוש ב [[$nameOfChunk]].';
$_lang['chunk_code'] = 'קוד HTML למיני תבנית';
$_lang['chunk_desc'] = 'תאור';
$_lang['chunk_delete_confirm'] = 'האם אתם בטוחים שברצונכם למחוק מיני תבנית זו?';
$_lang['chunk_duplicate_confirm'] = 'Are you sure you want to duplicate this chunk?';
$_lang['chunk_err_create'] = 'An error occurred while creating new chunk.';
$_lang['chunk_err_duplicate'] = 'Error duplicating chunk.';
$_lang['chunk_err_exists_name'] = 'There is already a chunk with the name "[[+name]]".';
$_lang['chunk_err_invalid_name'] = 'Chunk name is invalid.';
$_lang['chunk_err_locked'] = 'Chunk is locked.';
$_lang['chunk_err_remove'] = 'An error occurred while trying to remove the chunk.';
$_lang['chunk_err_save'] = 'An error occurred while saving the chunk.';
$_lang['chunk_err_nf'] = 'Chunk not found!';
$_lang['chunk_err_nfs'] = 'Chunk not found with id: [[+id]]';
$_lang['chunk_err_ns'] = 'Chunk not specified.';
$_lang['chunk_err_ns_name'] = 'Please specify a name.';
$_lang['chunk_lock'] = 'Lock chunk for editing';
$_lang['chunk_lock_msg'] = 'Users must have the edit_locked attribute in order to edit this chunk.';
$_lang['chunk_msg'] = 'Here you can add/edit chunks. Remember: Chunks are \'raw\' HTML code; so any PHP code won\'t be processed.';
$_lang['chunk_name'] = 'Chunk name';
$_lang['chunk_new'] = 'New Chunk';
$_lang['chunk_properties'] = 'Default Properties';
$_lang['chunk_title'] = 'Create/edit chunk';
$_lang['chunk_untitled'] = 'Untitled Chunk';
$_lang['chunks'] = 'Chunks';