text:
QUnit.config.testTimeout = 6000;

/* eslint-disable no-unused-vars */
function runODataMessagesTests() {
/* eslint-enable no-unused-vars */
"use strict";
	QUnit.config.autostart = false;

	jQuery.sap.require("sap.ui.model.odata.v2.ODataModel");
	jQuery.sap.require("sap.ui.model.odata.ODataMessageParser");
	jQuery.sap.require("sap.ui.core.message.MessageManager");

	var oInput = new sap.m.Input({value:"{json>/Products(1)/ProductName}"});
	oInput.placeAt("content");

	var oInput2 = new sap.m.Input({value:"{xml>/Products(1)/ProductName}"});
	oInput2.placeAt("content");

	var sServiceURI = "fakeservice://testdata/odata/northwind/";
	// var sServiceURI = "/testsuite/proxy/http/services.odata.org/V3/Northwind/Northwind.svc/";
	var mModelOptions = {
		defaultBindingMode: sap.ui.model.BindingMode.TwoWay,
		async: true,
		useBatch: false
	};

	var oModelJson, oModelXml;

	// Create MessageManager instance and set Message Model in TimeOut...
	sap.ui.getCore().getMessageManager();

	// Start delayed so the message model is available
	setTimeout(function() {
		QUnit.start();
	}, 100);

	var oJsonLayout = new sap.ui.layout.VerticalLayout({
		content: {
			path: "json>/Products",
			template: new sap.ui.commons.Button({
				text: { path: "json>ProductName" }
			})
		}
	});

	var oXmlLayout = new sap.ui.layout.VerticalLayout({
		content: {
			path: "xml>/Products",
			template: new sap.ui.commons.Button({
				text: { path: "xml>ProductName" }
			})
		}
	});

	var oMainLayout = new sap.ui.layout.HorizontalLayout({
		content: [ oJsonLayout, oXmlLayout ]
	});
	oMainLayout.placeAt("content");

	QUnit.test("JSON format", function(assert) {
		var done = assert.async();
		mModelOptions.json = true;
		oModelJson = new sap.ui.model.odata.v2.ODataModel(sServiceURI, mModelOptions);
		sap.ui.getCore().setModel(oModelJson, "json");

		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No message has been added");

		assert.ok(oInput.getValueState() === "None", "ValueState has not been set");

		var iRequests = 0;
		oModelJson.attachRequestCompleted(function(oRequest) {
			iRequests++;
			if (oRequest.getParameter("url").indexOf("$count") == -1) {
				assert.ok(iRequests === 2, "Two Requests (with messages) has been processed");
				setTimeout(function() {
					assert.ok(oInput.getValueState() === "Error", "ValueState has been set to 'Error'");

					var iMessages = oMessageModel.getProperty("/").length;
					assert.equal(iMessages, 21, "One message has been added for every Item and one for the Collection");

					oModelJson.destroy();
					done();
				}, 0);
			}
		});
	});

	QUnit.test("XML format", function(assert) {
		var done = assert.async();
		mModelOptions.json = false;
		oModelXml = new sap.ui.model.odata.v2.ODataModel(sServiceURI, mModelOptions);
		sap.ui.getCore().setModel(oModelXml, "xml");
		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();

		assert.ok(oInput2.getValueState() === "None", "ValueState has not been set");

		var iRequests = 0;
		oModelXml.attachRequestCompleted(function(oRequest) {
			iRequests++;
			var iMessages = oMessageModel.getProperty("/").length;
			if (oRequest.getParameter("url").indexOf("$count") == -1) {
				assert.ok(iRequests === 2, "Two Requests (with messages) has been processed");
				setTimeout(function() {
					assert.ok(oInput2.getValueState() === "Error", "ValueState has been set to 'Error'");

					var iMessages = oMessageModel.getProperty("/").length;
					assert.equal(iMessages, 21, "One message has been added for every Item and one for the Collection");

					oModelXml.destroy();
					done();
				}, 0);
			}
		});
	});

	QUnit.test("Function Imports", function(assert) {
		var done = assert.async();
		var oModel = new sap.ui.model.odata.v2.ODataModel("fakeservice://testdata/odata/function-imports/", {
			useBatch: false,
			json: false
		});
		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test")

		oModel.attachMetadataLoaded(function() {
			var mMessages = oMessageModel.getProperty("/");
			var oMetadata = oModel.getServiceMetadata();

			testFunctionTarget({
				url: "/EditProduct",
				parameters: {
					"ProductUUID": "00000000-0000-0000-0000-000000000001",
				},

				numMessages: 1,
				lastTarget: "/Products(guid'10000000-0000-0000-0000-000000000000')",
				final: false
			});

			testFunctionTarget({
				url: "/EditProduct",
				parameters: {
					"ProductUUID": "00000000-0000-0000-0000-000000000002",
				},

				numMessages: 2,
				lastTarget: "/Products(guid'20000000-0000-0000-0000-000000000000')",
				final: false
			});

			testFunctionTarget({
				url: "/EditProduct",
				parameters: {
					"ProductUUID": "30000000-0000-0000-0000-000000000003",
				},

				numMessages: 3,
				lastTarget: "/Products(guid'30000000-0000-0000-0000-000000000003')",
				final: true
			});

			function testFunctionTarget(mTestOptions) {
				// Set default values
				mTestOptions.method      = mTestOptions.method      ? mTestOptions.method      : "POST";
				mTestOptions.parameters  = mTestOptions.parameters  ? mTestOptions.parameters  : {};
				mTestOptions.numMessages = mTestOptions.numMessages ? mTestOptions.numMessages : {};
				mTestOptions.final       = mTestOptions.final       ? mTestOptions.final       : false;
				mTestOptions.lastTarget  = mTestOptions.lastTarget  ? mTestOptions.lastTarget  : "INVALIDTARGET";

				testFunctionTarget.aTests = testFunctionTarget.aTests ? testFunctionTarget.aTests : [];
				testFunctionTarget.aTests.push(mTestOptions);

				var fnNextTest = function() {
					var mTestOptions;
					if (testFunctionTarget.aTests.length > 0) {
						mTestOptions = testFunctionTarget.aTests.shift();
					} else {
						testFunctionTarget._running = false;
					}

					oModel.callFunction(mTestOptions.url, {
						method: mTestOptions.method,
						urlParameters: mTestOptions.parameters,
						success: function() {
							var aMessages = oMessageModel.getProperty("/");
							assert.equal(aMessages.length, mTestOptions.numMessages, mTestOptions.numMessages + " messages set after the function import");
							assert.equal(aMessages[aMessages.length - 1].target, mTestOptions.lastTarget, "Message has correct target");

							if (mTestOptions.final) {
								testFunctionTarget._running = false;
								oModel.destroy();
								done();
							} else {
								fnNextTest();
							}
						}
					});

				};

				if (!testFunctionTarget._running) {
					testFunctionTarget._running = true;
					fnNextTest();
				}

			}
		});
	});

	var fnTestTechnicalErrors = function(bJson, assert) {
		var done = assert.async();

		assert.expect(20);

		var oModel = new sap.ui.model.odata.v2.ODataModel("fakeservice://testdata/odata/technical-errors/", {
			useBatch: false,
			json: bJson
		});

		var iStartCounter = 4;
		var fnStart = function() {
			if (!--iStartCounter) {
				oModel.destroy();
				done();
			}
		};

		var iExpectedMessages = 0;

		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test")

		oModel.attachMetadataLoaded(function() {
			var mMessages = oMessageModel.getProperty("/");
			var oMetadata = oModel.getServiceMetadata();

			var fnCheckAddedMessages = function() {
				iExpectedMessages += 2;

				var aMessages = oMessageModel.getProperty("/");
				assert.equal(aMessages.length, iExpectedMessages, "There should be more error messages");

				assert.equal(aMessages[iExpectedMessages - 2].getMessage(), "Field \"SALESORDERID\" cannot be changed since it is read only", "Correct message text");
				assert.equal(aMessages[iExpectedMessages - 2].getType(), sap.ui.core.MessageType.Error, "Correct message severity");

				assert.equal(aMessages[iExpectedMessages - 1].getMessage(), "Some other error", "Correct message text");
				assert.equal(aMessages[iExpectedMessages - 1].getType(), sap.ui.core.MessageType.Error, "Correct message severity");

				fnStart();
			};

			var fnCheckAddedMessages2 = function() {
				iExpectedMessages += 6;

				var aMessages = oMessageModel.getProperty("/");
				assert.equal(aMessages.length, iExpectedMessages, "There should be more error messages");

				// Important: In this case the message order has been changed since errors come before warnings
				var mAddesMessages = {
					"Error|SY/530|/Error2(400)/|Warning": false,
					"Error|/IWBEP/CX_MGW_BUSI_EXCEPTION|/Error2(400)/|Business Error with details in TEA application": false,
					"Error||/Error2(400)/Property|Multiple error/warning messages": false,
					"Error||/Error2(400)/Message|Inner error": false,
					"Error||/Error2(400)/Type|Inner error 2": false,
					"Warning||/Error2(400)/Type|Warning": false
				};

				for (var i = aMessages.length - 6; i < aMessages.length; ++i) {
					var oM = aMessages[i]
					var sIdentifier = [oM.getType(), oM.getCode(), oM.getTarget(), oM.getMessage()].join("|");

					assert.equal(mAddesMessages[sIdentifier], false, "Message is as expected");
					mAddesMessages[sIdentifier] = true;
				}

				var bAllMessagesArrived = Object.keys(mAddesMessages).reduce(function(vPrev, sCurrent) {
					return vPrev && mAddesMessages[sCurrent] === true;
				}, true);
				assert.ok(bAllMessagesArrived, "All expected messages are there");

				fnStart();
			};

			oModel.read("/Error(400)", {
				success: function() {
					assert.ok(false, "This should return an error from the server and thus fail");
				},
				error: fnCheckAddedMessages
			});

			oModel.read("/Error(500)", {
				success: function() {
					assert.ok(false, "This should return an error from the server and thus fail");
				},
				error: fnCheckAddedMessages
			});

			oModel.read("/Error2(400)", {
				success: function() {
					assert.ok(false, "This should return an error from the server and thus fail");
				},
				error: fnCheckAddedMessages2
			});

			oModel.read("/Error(900)", {
				success: function() {
					assert.ok(false, "This should return an error from the server and thus fail");
				},
				error: function() {
					var aMessages = oMessageModel.getProperty("/");
					assert.equal(aMessages.length, iExpectedMessages, "There should be no extra error messages for status 900");

					fnStart();
				}
			});

		});
	};

	QUnit.test("Technical Errors (JSON)", fnTestTechnicalErrors.bind(this, true));
	QUnit.test("Technical Errors (XML)", fnTestTechnicalErrors.bind(this, false));

	var fnTestLongtextUrl = function(bJson, assert) {
		var done = assert.async();

		assert.expect(15);

		var oModel = new sap.ui.model.odata.v2.ODataModel("fakeservice://testdata/odata/technical-errors/", {
			useBatch: false,
			json: bJson
		});

		var iStartCounter = 4;
		var fnStart = function() {
			if (!--iStartCounter) {
				oModel.destroy();
				done();
			}
		};

		var iExpectedMessages = 0;

		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();
		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test")

		oModel.attachMetadataLoaded(function() {
			var mMessages = oMessageModel.getProperty("/");
			var oMetadata = oModel.getServiceMetadata();

			var fnCheckAddedMessages = function() {
				iExpectedMessages += 2;

				var aMessages = oMessageModel.getProperty("/");
				assert.equal(aMessages.length, iExpectedMessages, "There should be more error messages");

				// All messages should have longtext URLs
				for (var i = aMessages.length - 2; i < aMessages.length; ++i) {
					assert.ok(aMessages[i].getDescriptionUrl(), "Message has longtext URL");
				}

				fnStart();
			};

			var fnCheckAddedMessages2 = function() {
				iExpectedMessages += 6;

				var aMessages = oMessageModel.getProperty("/");
				assert.equal(aMessages.length, iExpectedMessages, "There should be more error messages");

				// No messages should have longtext URLs
				for (var i = aMessages.length - 6; i < aMessages.length; ++i) {
					assert.ok(!aMessages[i].getDescriptionUrl(), "Message has no longtext URL");
				}

				fnStart();
			};

			oModel.read("/Error(400)", {
				success: function() {
					assert.ok(false, "This should return an error from the server and thus fail");
				},
				error: fnCheckAddedMessages
			});

			oModel.read("/Error(500)", {
				success: function() {
					assert.ok(false, "This should return an error from the server and thus fail");
				},
				error: fnCheckAddedMessages
			});

			oModel.read("/Error2(400)", {
				success: function() {
					assert.ok(false, "This should return an error from the server and thus fail");
				},
				error: fnCheckAddedMessages2
			});

			oModel.read("/Error(900)", {
				success: function() {
					assert.ok(false, "This should return an error from the server and thus fail");
				},
				error: function() {
					var aMessages = oMessageModel.getProperty("/");
					assert.equal(aMessages.length, iExpectedMessages, "There should be no extra error messages for status 900");

					fnStart();
				}
			});

		});
	};

	QUnit.test("LongText URL (JSON)", fnTestLongtextUrl.bind(this, true));
	QUnit.test("LongText URL (XML)", fnTestLongtextUrl.bind(this, false));

	QUnit.test("ODataMessageParser reads headers case-insensitive", function(assert) {
		var done = assert.async();
		var sServiceURI = "fakeservice://testdata/odata/northwind";

		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();
		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test")

		var oMetadata = new sap.ui.model.odata.ODataMetadata(sServiceURI + "/$metadata", {});
		oMetadata.loaded().then(function() {

			// Get Messages sent to console
			var fnError = jQuery.sap.log.error;
			var fnWarn = jQuery.sap.log.warning;
			var fnDebug = jQuery.sap.log.debug;
			var fnInfo = jQuery.sap.log.info;

			var iCounter = 0;
			var fnCount = function(sMessage) {
				if (sMessage.indexOf("[OData Message] ") > -1) {
					iCounter++;
				}
			}

			jQuery.sap.log.error = jQuery.sap.log.warning = jQuery.sap.log.debug = jQuery.sap.log.info = fnCount;

			var oParser = new sap.ui.model.odata.ODataMessageParser(sServiceURI, oMetadata);

			var oRequest = {
				requestUri: "fakeservice://testdata/odata/northwind/Test"
			};

			var oResponse = {
				statusCode: "200", // Parse Header...
				body: "Ignored",
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
					"DataServiceVersion": "2.0;",
					"Sap-Message": JSON.stringify({
						"code":		"999",
						"message":	"This is test message",
						"severity":	"error",
						"details": []
					})
				}
			};
			oParser.parse(oResponse, oRequest);
			assert.equal(iCounter, 1, "Message from 'Sap-Message' header was added");

			var oResponse = {
				statusCode: "200", // Parse Header...
				body: "Ignored",
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
					"DataServiceVersion": "2.0;",
					"sap-message": JSON.stringify({
						"code":		"999",
						"message":	"This is test message",
						"severity":	"error",
						"details": []
					})
				}
			};
			oParser.parse(oResponse, oRequest);
			assert.equal(iCounter, 2, "Message from 'sap-message' header was added");

			var oResponse = {
				statusCode: "200", // Parse Header...
				body: "Ignored",
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
					"DataServiceVersion": "2.0;",
					"SAP-Message": JSON.stringify({
						"code":		"999",
						"message":	"This is test message",
						"severity":	"error",
						"details": []
					})
				}
			};
			oParser.parse(oResponse, oRequest);
			assert.equal(iCounter, 3, "Message from 'SAP-Message' header was added");
			done();
		});
	});

	QUnit.test("ODataMessageParser: target key for created entities", function(assert) {
		var done = assert.async();
		var sServiceURI = "fakeservice://testdata/odata/northwind";

		var oMetadata = new sap.ui.model.odata.ODataMetadata(sServiceURI + "/$metadata", {});
		oMetadata.loaded().then(function() {

			var oParser = new sap.ui.model.odata.ODataMessageParser(sServiceURI, oMetadata);
			// Use processor to get new messages
			var aNewMessages = [];
			oParser.setProcessor({
				fireMessageChange: function(oObj) {
					aNewMessages = oObj.newMessages;
				}
			});

			//SETUP
			var oRequest = {
				method: "POST",
				key: "Products(1)",
				created: true
			};

			var oResponse = {
				statusCode: "400", //CREATED
				body: "Ignored",
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
					"DataServiceVersion": "2.0;"
				}
			};

			var oResponseHeaderSapMessageObject = {
				"odata.error": {
					"details": []
				},
				"code":		"999",
				"message":	"resource created but error occurred",
				"severity":	"error",
				"details": []
			};

			// location header set in response (Products)

			//request uri:          fakeservice://testdata/odata/northwind/Products
			oRequest.requestUri = sServiceURI + "/Products";
			oResponse.body = JSON.stringify(oResponseHeaderSapMessageObject);

			oParser.parse(oResponse, oRequest);

			assert.equal(aNewMessages.length, 1);
			assert.equal(aNewMessages[0].target, "/Products(1)/", "target is read from the provided key");

			//request uri:          fakeservice://testdata/odata/northwind/Products
			oRequest.created = false;

			oParser.parse(oResponse, oRequest);

			assert.equal(aNewMessages.length, 1);
			assert.equal(aNewMessages[0].target, "/Products", "target is parsed from the requestUri");

			done();
		});
	});

	QUnit.test("ODataMessageParser: error for newly created resource with relative target", function(assert) {
		var done = assert.async();
		var sServiceURI = "fakeservice://testdata/odata/northwind";

		var oMetadata = new sap.ui.model.odata.ODataMetadata(sServiceURI + "/$metadata", {});
		oMetadata.loaded().then(function() {

			var oParser = new sap.ui.model.odata.ODataMessageParser(sServiceURI, oMetadata);
			// Use processor to get new messages
			var aNewMessages = [];
			oParser.setProcessor({
				fireMessageChange: function(oObj) {
					aNewMessages = oObj.newMessages;
				}
			});

			//SETUP
			var oRequest = {
				method: "POST"
			};

			var oResponse = {
				statusCode: "201", //CREATED
				body: "Ignored",
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
					"DataServiceVersion": "2.0;"
				}
			};

			var oResponseHeaderSapMessageObject = {
				"code":		"999",
				"message":	"resource created but error occurred",
				"severity":	"error",
				"details": []
			};

			// location header set in response (Products)

			//request uri:          fakeservice://testdata/odata/northwind/Products
			//response location:    fakeservice://testdata/odata/northwind/Products(1)
			//target:               name
			oRequest.requestUri = sServiceURI + "/Products";
			oResponseHeaderSapMessageObject.target = "name";
			oResponse.headers["location"] = sServiceURI + "/Products(1)";
			oResponse.headers["Sap-Message"] = JSON.stringify(oResponseHeaderSapMessageObject);

			oParser.parse(oResponse, oRequest);

			assert.equal(aNewMessages.length, 1);
			assert.equal(aNewMessages[0].target, "/Products(1)/name", "target is relative to newly created product");

			//request uri:          fakeservice://testdata/odata/northwind/Categories(1)/Products
			//response location:    fakeservice://testdata/odata/northwind/Products(1)
			//target:               name
			oRequest.requestUri = sServiceURI + "/Categories(1)/Products";
			oResponseHeaderSapMessageObject.target = "name";
			oResponse.headers["location"] = sServiceURI + "/Products(1)";
			oResponse.headers["Sap-Message"] = JSON.stringify(oResponseHeaderSapMessageObject);

			oParser.parse(oResponse, oRequest);

			assert.equal(aNewMessages.length, 1);
			assert.equal(aNewMessages[0].target, "/Products(1)/name", "target is relative to newly created product");

			done();
		});
	});

	QUnit.test("ODataMessageParser without ODataModel", function(assert) {
		var done = assert.async();
		var sServiceURI = "fakeservice://testdata/odata/northwind";

		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();
		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test")

		var oMetadata = new sap.ui.model.odata.ODataMetadata(sServiceURI + "/$metadata", {});
		oMetadata.loaded().then(function() {

			// Get Messages sent to console
			var fnError = jQuery.sap.log.error;
			var fnWarn = jQuery.sap.log.warning;
			var fnDebug = jQuery.sap.log.debug;
			var fnInfo = jQuery.sap.log.info;

			var iCounter = 0;
			var fnCount = function(sMessage) {
				if (sMessage.indexOf("[OData Message] ") > -1) {
					iCounter++;
				}
			}

			jQuery.sap.log.error = jQuery.sap.log.warning = jQuery.sap.log.debug = jQuery.sap.log.info = fnCount;

			var oParser = new sap.ui.model.odata.ODataMessageParser(sServiceURI, oMetadata);

			var oRequest = {
				requestUri: "fakeservice://testdata/odata/northwind/Test"
			};

			var oResponse = {
				statusCode: "200", // Parse Header...
				body: "Ignored",
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
					"DataServiceVersion": "2.0;",
					"sap-message": JSON.stringify({
						"code":		"999",
						"message":	"This is test message",
						"severity":	"error",
						"details": []
					})
				}
			};
			oParser.parse(oResponse, oRequest);
			assert.equal(iCounter, 1, "Message from 'sap-message' header was added")

			oResponse = {
				statusCode: "200", // Parse Header...
				body: "Ignored",
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
					"DataServiceVersion": "2.0;",
					"message": JSON.stringify({
						"code":		"999",
						"message":	"This is an error test message",
						"severity":	"error",
						"details": [{
							"code":		"999",
							"message":	"This is a warning test message",
							"severity":	"warning",
						}, {
							"code":		"999",
							"message":	"This is a success test message",
							"severity":	"success"
						}, {
							"code":		"999",
							"message":	"This is an information test message",
							"severity":	"info"
						}]
					})
				}
			};
			oParser.setHeaderField("message");
			oParser.parse(oResponse, oRequest);
			assert.equal(iCounter, 5, "Message from 'message' header was added")

			oResponse = {
				statusCode: "200", // Parse Header...
				body: "Ignored",
				headers: {
					"Content-Type": "text/plain;charset=utf-8",
					"DataServiceVersion": "2.0;",
					"invalid": "{ invalid: Json }"
				}
			};
			oParser.setHeaderField("invalid");
			oParser.parse(oResponse, oRequest);
			assert.equal(iCounter, 5, "No message from 'invalid' header was added")

			oParser.setHeaderField("none");
			oParser.parse(oResponse, oRequest);
			assert.equal(iCounter, 5, "No message from non-existent 'none' header was added")

			// Clean up
			jQuery.sap.log.error = fnError;
			jQuery.sap.log.warning = fnWarn;
			jQuery.sap.log.debug = fnDebug;
			jQuery.sap.log.info = fnInfo;

			oMetadata.destroy();
			oParser.destroy();
			done();
		});

	});

	// TODO: Function imports with action-for annotation

	QUnit.test("Function Imports with action-for annotation", function(assert) {
		var done = assert.async();
		var oModel = new sap.ui.model.odata.v2.ODataModel("fakeservice://testdata/odata/function-imports/", {
			useBatch: false,
			json: false
		});
		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test")

		oModel.attachMetadataLoaded(function() {
			var mMessages = oMessageModel.getProperty("/");
			var oMetadata = oModel.getServiceMetadata();

			testFunctionTarget({
				url: "/ActionForFunction",
				parameters: {
					"SupplierUUID": "00000000-0000-0000-0000-000000000001",
				},

				numMessages: 1,
				lastTarget: "/Suppliers(guid'00000000-0000-0000-0000-000000000001')",
				final: false
			});

			testFunctionTarget({
				url: "/ActionForFunction",
				parameters: {
					"SupplierUUID": "00000000-0000-0000-0000-000000000002",
				},

				numMessages: 2,
				lastTarget: "/Products(999)/ProductName",
				final: false
			});

			testFunctionTarget({
				url: "/ActionForFunction",
				parameters: {
					"SupplierUUID": "00000000-0000-0000-0000-000000000002",
				},

				numMessages: 2,
				lastTarget: "/Products(999)/ProductName",
				final: true
			});

			function testFunctionTarget(mTestOptions) {
				// Set default values
				mTestOptions.method      = mTestOptions.method      ? mTestOptions.method      : "POST";
				mTestOptions.parameters  = mTestOptions.parameters  ? mTestOptions.parameters  : {};
				mTestOptions.numMessages = mTestOptions.numMessages ? mTestOptions.numMessages : {};
				mTestOptions.final       = mTestOptions.final       ? mTestOptions.final       : false;
				mTestOptions.lastTarget  = mTestOptions.lastTarget  ? mTestOptions.lastTarget  : "INVALIDTARGET";

				testFunctionTarget.aTests = testFunctionTarget.aTests ? testFunctionTarget.aTests : [];
				testFunctionTarget.aTests.push(mTestOptions);

				var fnNextTest = function() {
					var mTestOptions;
					if (testFunctionTarget.aTests.length > 0) {
						mTestOptions = testFunctionTarget.aTests.shift();
					} else {
						testFunctionTarget._running = false;
					}

					oModel.callFunction(mTestOptions.url, {
						method: mTestOptions.method,
						urlParameters: mTestOptions.parameters,
						success: function() {
							var aMessages = oMessageModel.getProperty("/");
							assert.equal(aMessages.length, mTestOptions.numMessages, mTestOptions.numMessages + " messages set after the function import");
							assert.equal(aMessages[aMessages.length - 1].target, mTestOptions.lastTarget, "Message has correct target");

							if (mTestOptions.final) {
								testFunctionTarget._running = false;
								oModel.destroy();
								done();
							} else {
								fnNextTest();
							}
						}
					});

				};

				if (!testFunctionTarget._running) {
					testFunctionTarget._running = true;
					fnNextTest();
				}

			}
		});
	});

	// TODO: Function imports with multiple key fields

	var fnTestBatchGroups = function(bUseBatch, bJSON, assert) {
		var done = assert.async();

		assert.expect(bUseBatch ? 9 : 5);
		var oModel = new sap.ui.model.odata.v2.ODataModel("fakeservice://testdata/odata/northwind/", {
			useBatch: bUseBatch,
			json: bJSON
		});
		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test")

		oModel.attachMetadataLoaded(function() {
			var aMessages = oMessageModel.getProperty("/");

			assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set after metadata loaded")

			oModel.setDeferredBatchGroups(["deferredId"]);
			oModel.read("/Products(1)", { batchGroupId : "deferredId" });
			oModel.read("/Products(2)", { batchGroupId : "deferredId" });
			oModel.read("/Products(3)", { batchGroupId : "deferredId" });

			oModel.attachBatchRequestSent(function() {
				assert.ok(bUseBatch, "Only receive batchRequestSent event in batch mode");
				var aMessages = oMessageModel.getProperty("/");
				assert.equal(aMessages.length, 0, "No messages when requests have been sent");
			});
			oModel.attachBatchRequestCompleted(function(oEvent) {
				assert.ok(bUseBatch, "Only receive batchRequestCompleted event in batch mode");
				var aMessages = oMessageModel.getProperty("/");
				assert.equal(aMessages.length, 1 + iRequestsCompleted, "One Message for the EntitySet plus one for every item");

				onCompleted();
			});

			var iRequestsCompleted = 0;
			oModel.attachRequestCompleted(function(oEvent) {
				++iRequestsCompleted;
				var aMessages = oMessageModel.getProperty("/");
				assert.equal(aMessages.length, 1 + iRequestsCompleted, "One Message for the EntitySet plus one for every item");

				if (!bUseBatch && iRequestsCompleted === 3) {
					onCompleted();
				}
			});

			oModel.submitChanges();
		});

		function onCompleted() {
			oModel.destroy();
			done();
		}
	}

	QUnit.test("Message with groups - Batch: off, JSON: true",  fnTestBatchGroups.bind(this, false, true));
	QUnit.test("Message with groups - Batch: off, JSON: false", fnTestBatchGroups.bind(this, false, false));
	QUnit.test("Message with groups - Batch: on,  JSON: true",  fnTestBatchGroups.bind(this, true,  true));
	QUnit.test("Message with groups - Batch: on,  JSON: false", fnTestBatchGroups.bind(this, true,  false));

	var fnTestWriteBatchGroups = function(bUseBatch, bJSON, assert) {
		var done = assert.async();

		assert.expect(bUseBatch ? 9 : 5);
		var oModel = new sap.ui.model.odata.v2.ODataModel("fakeservice://testdata/odata/northwind/", {
			useBatch: bUseBatch,
			json: bJSON
		});
		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test")

		oModel.attachMetadataLoaded(function() {
			var aMessages = oMessageModel.getProperty("/");

			assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set after metadata loaded")

			oModel.setDeferredBatchGroups(["deferredId"]);
			oModel.update("/Products(1)", { ProductName: "Updated 1" }, { batchGroupId : "deferredId" });
			oModel.update("/Products(2)", { ProductName: "Updated 2" }, { batchGroupId : "deferredId" });
			oModel.update("/Products(3)", { ProductName: "Updated 3" }, { batchGroupId : "deferredId" });

			oModel.attachBatchRequestSent(function() {
				assert.ok(bUseBatch, "Only receive batchRequestSent event in batch mode");
				var aMessages = oMessageModel.getProperty("/");
				assert.equal(aMessages.length, 0, "No messages when requests have been sent");
			});
			oModel.attachBatchRequestCompleted(function(oEvent) {
				assert.ok(bUseBatch, "Only receive batchRequestCompleted event in batch mode");
				var aMessages = oMessageModel.getProperty("/");
				assert.equal(aMessages.length, 1 + iRequestsCompleted, "One Message for the EntitySet plus one for every item");

				onCompleted();
			});

			var iRequestsCompleted = 0;
			oModel.attachRequestCompleted(function(oEvent) {
				++iRequestsCompleted;
				var aMessages = oMessageModel.getProperty("/");
				assert.equal(aMessages.length, 1 + iRequestsCompleted, "One Message for the EntitySet plus one for every item");

				if (!bUseBatch && iRequestsCompleted === 3) {
					onCompleted();
				}
			});

			oModel.submitChanges();
		});

		function onCompleted() {
			oModel.destroy();
			done();
		}
	}

	QUnit.test("Message with groups (write) - Batch: off, JSON: true",  fnTestWriteBatchGroups.bind(this, false, true));
	QUnit.test("Message with groups (write) - Batch: off, JSON: false", fnTestWriteBatchGroups.bind(this, false, false));
	QUnit.test("Message with groups (write) - Batch: on,  JSON: true",  fnTestWriteBatchGroups.bind(this, true,  true));
	QUnit.test("Message with groups (write) - Batch: on,  JSON: false", fnTestWriteBatchGroups.bind(this, true,  false));

	var fnTestFunctionImport = function(assert) {
		var done = assert.async();

		assert.expect(10);
		var oModel = new sap.ui.model.odata.v2.ODataModel("fakeservice://testdata/odata/northwind/", { tokenHandling: false, useBatch: false });
		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test")

		oModel.attachMetadataLoaded(function() {
			var aMessages = oMessageModel.getProperty("/");

			assert.equal(aMessages.length, 0, "No messages are set at the after metadata was loaded")

			oModel.read("/Products(1)", {
				success: function() {
					var aMessages = oMessageModel.getProperty("/");
					var aMessageTagets = aMessages.map(function(oMessage) { return oMessage.getTarget(); });

					assert.equal(aMessages.length, 2, "Two messages are set at the beginning of the test")
					assert.ok(aMessageTagets.indexOf("/Products") > -1, "Message targetting '/Products' has been received.");
					assert.ok(aMessageTagets.indexOf("/Products(1)/ProductName") > -1, "Message targetting '/Products(1)/ProductName' has been received.");

					oModel.read("/Products(1)/Supplier", {
						success: function() {
							var aMessages = oMessageModel.getProperty("/");
							var aMessageTagets = aMessages.map(function(oMessage) { return oMessage.getTarget(); });

							assert.equal(aMessages.length, 4, "Four messages are set at the beginning of the test")

							assert.ok(aMessageTagets.indexOf("/Products") > -1, "Message targetting '/Products' has been received.");
							assert.ok(aMessageTagets.indexOf("/Products(1)/ProductName") > -1, "Message targetting '/Products(1)/ProductName' has been received.");
							assert.ok(aMessageTagets.indexOf("/Suppliers") > -1, "Message targetting '/Products' has been received.");
							var sSupplierNameTarget = aMessageTagets.reduce(function(sPrevious, sValue) {
								return sValue.indexOf(")/SupplierName") > -1 ? sValue : sPrevious;
							});
							assert.ok(/\/Suppliers\(.{1,2}\)\/SupplierName/.test(sSupplierNameTarget), "Message targetting '/Suppliers(XXX)/SupplierName' has been received.");

							oModel.destroy();
							done();
						}
					});
				}
			});

		});
	};

	QUnit.test("Messages for NavigationProperties",  fnTestFunctionImport);

	var fnTestFunctionImportWithInvalidTarget = function(assert) {
		var done = assert.async();

		assert.expect(20);
		var oModel = new sap.ui.model.odata.v2.ODataModel("fakeservice://testdata/odata/northwind/", { tokenHandling: false, useBatch: false });
		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test")

		oModel.attachMetadataLoaded(function() {
			var aMessages = oMessageModel.getProperty("/");

			assert.equal(aMessages.length, 0, "No messages are set at the after metadata was loaded")

			oModel.read("/Products(1)", {
				success: function() {
					var aMessages = oMessageModel.getProperty("/");
					var aMessageTagets = aMessages.map(function(oMessage) { return oMessage.getTarget(); });

					assert.equal(aMessages.length, 2, "Two messages are set after the entity was read");
					assert.ok(aMessageTagets.indexOf("/Products") > -1, "Message targetting '/Products' has been received.");
					assert.ok(aMessageTagets.indexOf("/Products(1)/ProductName") > -1, "Message targetting '/Products(1)/ProductName' has been received.");

					oModel.callFunction("/functionWithInvalidTarget", {
						method: "POST",
						success: function() {
							var aMessages = oMessageModel.getProperty("/");
							var aMessageTagets = aMessages.map(function(oMessage) { return oMessage.getTarget(); });

							assert.equal(aMessages.length, 3, "Three messages are set after the FunctionImport returned");

							assert.ok(aMessageTagets.indexOf("/Products") > -1, "Message targetting '/Products' is still there.");
							assert.ok(aMessageTagets.indexOf("/Products(1)/SupplierID") > -1, "Message targetting '/Products(1)/SupplierID' has been received.");
							assert.ok(aMessageTagets.indexOf("/PersistedMessages/functionWithInvalidTarget") > -1, "Message targetting '/PersistedMessages/functionWithInvalidTarget' has been received.");

							assert.ok(aMessageTagets.indexOf("/Products(1)/ProductName") === -1, "Message targetting '/Products(1)/ProductName' has been removed.");

							oModel.read("/Products(1)", {
								success: function() {
									var aMessages = oMessageModel.getProperty("/");
									var aMessageTagets = aMessages.map(function(oMessage) { return oMessage.getTarget(); });

									assert.equal(aMessages.length, 3, "Three messages are set after /Products(1) is requested again");

									assert.ok(aMessageTagets.indexOf("/Products") > -1, "Message targetting '/Products' has been received.");
									assert.ok(aMessageTagets.indexOf("/Products(1)/ProductName") > -1, "Message targetting '/Products(1)/ProductName' has been received.");
									assert.ok(aMessageTagets.indexOf("/PersistedMessages/functionWithInvalidTarget") > -1, "Message targetting '/PersistedMessages/functionWithInvalidTarget' has been kept.");

									assert.ok(aMessageTagets.indexOf("/Products(1)/SupplierID") === -1, "Message targetting '/Products(1)/SupplierID' has been removed.");

									oModel.callFunction("/functionWithInvalidTarget", {
										method: "POST",
										success: function() {
											var aMessages = oMessageModel.getProperty("/");
											var aMessageTagets = aMessages.map(function(oMessage) { return oMessage.getTarget(); });

											assert.equal(aMessages.length, 3, "Three messages are set after FunctionImport is called again");

											assert.ok(aMessageTagets.indexOf("/Products") > -1, "Message targetting '/Products' is still there.");
											assert.ok(aMessageTagets.indexOf("/Products(1)/SupplierID") > -1, "Message targetting '/Products(1)/SupplierID' has been received.");
											assert.ok(aMessageTagets.indexOf("/PersistedMessages/functionWithInvalidTarget") > -1, "Message targetting '/PersistedMessages/functionWithInvalidTarget' has been received.");

											assert.ok(aMessageTagets.indexOf("/Products(1)/ProductName") === -1, "Message targetting '/Products(1)/ProductName' has been removed.");

											oModel.destroy();
											done();
										}
									});
								}
							});
						}
					});
				}
			});

		});
	};

	QUnit.test("Messages with 'invalid' targets",  fnTestFunctionImportWithInvalidTarget);

	var fnTestRemoveMessagesWithBinding = function(assert) {
		var done = assert.async();

		assert.expect(11);

		var oInput3 = new sap.m.Input({
			value: {
				path: "/Products(1)/ProductName",
				type: new sap.ui.model.type.String(null, {
					maxLength: 3
				})
			}
		});

		var wait = function() {
			return new Promise(function(resolve) {
				oInput3.getBinding("value").attachAggregatedDataStateChange(resolve);
			});
		};

		var read = function(sPath) {
			return new Promise(function(resolve) {
				oModel.read(sPath, { success: resolve });
			});
		}

		var oModel = new sap.ui.model.odata.v2.ODataModel(sServiceURI, mModelOptions);
		sap.ui.getCore().setModel(oModel);

		oInput3.placeAt("content");
		sap.ui.getCore().getMessageManager().registerObject(oInput3, true);

		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test");

		read("/Products(1)").then(function() {
			oInput3.setValue("123");

			return wait();
		}).then(function() {
			assert.equal(oMessageModel.getProperty("/").length, 2, "Two messages from the OData service with a correct value set");
			assert.equal(oInput3.getBinding("value").getDataState().getControlMessages().length, 0, "No validation errors");

			oInput3.setValue("1234");

			return wait();
		}).then(function() {
			assert.equal(oMessageModel.getProperty("/").length, 3, "Two messages from the OData service and one from validation");
			assert.equal(oInput3.getBinding("value").getDataState().getControlMessages().length, 1, "One validation error");

			oInput3.bindProperty("value",  {
				path: "ProductName",
				type: new sap.ui.model.type.String(null, {
					maxLength: 3
				})
			});

		}).then(function() {
			assert.equal(oMessageModel.getProperty("/").length, 2, "Two messages from the OData service after rebinding");
			assert.equal(oInput3.getBinding("value").getDataState().getControlMessages().length, 0, "No validation errors");

			oInput3.setValue("1234");

			return wait();
		}).then(function() {
			assert.equal(oMessageModel.getProperty("/").length, 3, "Two messages from the OData service and one from validation");
			assert.equal(oInput3.getBinding("value").getDataState().getControlMessages().length, 1, "One validation error");

			oInput3.setBindingContext(oModel.createBindingContext("/Products(1)"))

			return wait();
		}).then(function() {
			assert.equal(oMessageModel.getProperty("/").length, 2, "Two messages from the OData service after changing the binding context");
			assert.equal(oInput3.getBinding("value").getDataState().getControlMessages().length, 0, "No validation errors");

			oInput3.destroy();
			oModel.destroy();
			done();
		});
	};

	QUnit.test("Delete control messages when the binding is destroyed and on rebinding",  fnTestRemoveMessagesWithBinding);

	var fnTestTransientMessages = function(assert) {
		var done = assert.async();

		assert.expect(19);

		var oModel = new sap.ui.model.odata.v2.ODataModel(sServiceURI, jQuery.extend({}, mModelOptions, { json: true }));
		sap.ui.getCore().setModel(oModel);

		var read = function(sPath) {
			return new Promise(function(resolve) {
				oModel.read(sPath, { success: resolve });
			});
		}

		var oMessageModel = sap.ui.getCore().getMessageManager().getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test");

		read("/TransientTest1").then(function() {
			var aMessages = oMessageModel.getProperty("/");
			assert.equal(aMessages.length, 3, "Three messages from the back-end");
			assert.equal(aMessages[0].persistent, false, "First message should not be persistent");
			assert.equal(aMessages[0].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[1].persistent, true, "Second message should be persistent");
			assert.equal(aMessages[1].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[2].persistent, true, "Third message should be persistent");
			assert.equal(aMessages[2].target, "/TransientTest1/SupplierID", "Message has correct target");

			return read("/TransientTest1");
		}).then(function() {
			var aMessages = oMessageModel.getProperty("/");
			assert.equal(aMessages.length, 5, "Five messages - 3 new ones from the back-end");

			assert.equal(aMessages[0].persistent, true, "First message should be persistent");
			assert.equal(aMessages[0].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[1].persistent, true, "Second message should be persistent");
			assert.equal(aMessages[1].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[2].persistent, false, "Third message should not be persistent");
			assert.equal(aMessages[2].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[3].persistent, true, "Fourth message should be persistent");
			assert.equal(aMessages[3].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[4].persistent, true, "Fifth message should be persistent");
			assert.equal(aMessages[4].target, "/TransientTest1/SupplierID", "Message has correct target");

			oModel.destroy();
			done();
		});
	};

	QUnit.test("Transient messages with /#TRANSIENT#-target or transient-flag", fnTestTransientMessages);

	var fnTestTransientMessageRemoval = function(assert) {
		var done = assert.async();

		assert.expect(35);

		var oModel = new sap.ui.model.odata.v2.ODataModel(sServiceURI, jQuery.extend({}, mModelOptions, { json: true }));
		sap.ui.getCore().setModel(oModel);

		var read = function(sPath) {
			return new Promise(function(resolve) {
				oModel.read(sPath, { success: resolve });
			});
		}

		var oMessageManager = sap.ui.getCore().getMessageManager();
		var oMessageModel = oMessageManager.getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test");

		read("/TransientTest1").then(function() {
			var aMessages = oMessageModel.getProperty("/");
			assert.equal(aMessages.length, 3, "Three messages from the back-end");
			assert.equal(aMessages[0].persistent, false, "First message should not be persistent");
			assert.equal(aMessages[0].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[1].persistent, true, "Second message should be persistent");
			assert.equal(aMessages[1].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[2].persistent, true, "Third message should be persistent");
			assert.equal(aMessages[2].target, "/TransientTest1/SupplierID", "Message has correct target");

			oMessageManager.removeAllMessages();

			assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set after removal of all messages");

			return read("/TransientTest1");
		}).then(function() {

			var aMessages = oMessageModel.getProperty("/");
			assert.equal(aMessages.length, 3, "Three messages from the back-end");
			assert.equal(aMessages[0].persistent, false, "First message should not be persistent");
			assert.equal(aMessages[0].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[1].persistent, true, "Second message should be persistent");
			assert.equal(aMessages[1].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[2].persistent, true, "Third message should be persistent");
			assert.equal(aMessages[2].target, "/TransientTest1/SupplierID", "Message has correct target");

			oMessageManager.removeMessages(aMessages[0]);
			oMessageManager.removeMessages(aMessages[2]);

			aMessages = oMessageModel.getProperty("/");

			assert.equal(aMessages.length, 1, "One message left after removal of two messages");
			assert.equal(aMessages[0].persistent, true, "First message should not be persistent");
			assert.equal(aMessages[0].target, "/TransientTest1/SupplierID", "Message has correct target");

			return read("/TransientTest1");
		}).then(function() {

			var aMessages = oMessageModel.getProperty("/");
			assert.equal(aMessages.length, 4, "Five messages - 3 new ones from the back-end");

			assert.equal(aMessages[0].persistent, true, "First message should be persistent");
			assert.equal(aMessages[0].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[1].persistent, false, "Second message should not be persistent");
			assert.equal(aMessages[1].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[2].persistent, true, "Third message should be persistent");
			assert.equal(aMessages[2].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[3].persistent, true, "Fourth message should be persistent");
			assert.equal(aMessages[3].target, "/TransientTest1/SupplierID", "Message has correct target");

			aMessages[0].setPersistent(false);
			aMessages[2].setPersistent(false);
			aMessages[3].setPersistent(false);

			return read("/TransientTest1");
		}).then(function() {
			var aMessages = oMessageModel.getProperty("/");
			assert.equal(aMessages.length, 3, "Three messages from the back-end, all previous messages removed after being set to non-persistent");
			assert.equal(aMessages[0].persistent, false, "First message should not be persistent");
			assert.equal(aMessages[0].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[1].persistent, true, "Second message should be persistent");
			assert.equal(aMessages[1].target, "/TransientTest1/SupplierID", "Message has correct target");
			assert.equal(aMessages[2].persistent, true, "Third message should be persistent");
			assert.equal(aMessages[2].target, "/TransientTest1/SupplierID", "Message has correct target");

			oModel.destroy();
			done();
		});
	};

	QUnit.test("Transient message removal from MessageManager", fnTestTransientMessageRemoval);

	var fnTestNormalization = function(assert) {
		var done = assert.async();

		assert.expect(7);

		var oModel = new sap.ui.model.odata.v2.ODataModel(sServiceURI, jQuery.extend({}, mModelOptions, { json: true }));
		sap.ui.getCore().setModel(oModel);

		var oBinding = oModel.bindProperty("/Products(ContextId='CLF(12)SEMANTIC_OBJ(7)Product(10)OBJECT_KEY(11)ZTEST_GD_02(9)DRAFT_KEY(36)005056ba-1dcb-1ee7-8ec6-ae98ab359923')/ProductName");
		oModel.addBinding(oBinding);
		var read = function(sPath) {
			return new Promise(function(resolve) {
				oModel.read(sPath, { success: resolve });
			});
		}

		var oMessageManager = sap.ui.getCore().getMessageManager();
		var oMessageModel = oMessageManager.getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test");

		read("/Products(ContextId='CLF%2812%29SEMANTIC_OBJ%287%29Product%2810%29OBJECT_KEY%2811%29ZTEST_GD_02%289%29DRAFT_KEY%2836%29005056ba-1dcb-1ee7-8ec6-ae98ab359923')").then(function() {
			var aMessages = oMessageModel.getProperty("/");
			assert.equal(aMessages.length, 2, "Two messages from the back-end");
			assert.equal(aMessages[0].target, "/Products(ContextId='CLF(12)SEMANTIC_OBJ(7)Product(10)OBJECT_KEY(11)ZTEST_GD_02(9)DRAFT_KEY(36)005056ba-1dcb-1ee7-8ec6-ae98ab359923')/ProductName", "Message has correct target");
			assert.ok(oBinding.getDataState().getChanges(), "Messages propageted to binding");
			assert.equal(oBinding.getDataState().getMessages().length, 1, " 1 Message propageted to binding");
			assert.equal(oBinding.getDataState().getMessages()[0], aMessages[0], "Message propageted to binding");
			oMessageManager.removeAllMessages();
			assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set after removal of all messages");
			return read("/Products(ContextId='CLF%2812%29SEMANTIC_OBJ%287%29Product%2810%29OBJECT_KEY%2811%29ZTEST_GD_02%289%29DRAFT_KEY%2836%29005056ba-1dcb-1ee7-8ec6-ae98ab359923')");
		}).then(function() {
			oModel.destroy();
			done();
		});
	};

	QUnit.test("Message target normalization", fnTestNormalization);

	var fnTestNavProp = function() {
		var done = assert.async();

		assert.expect(8);

		var oModel = new sap.ui.model.odata.v2.ODataModel(sServiceURI, jQuery.extend({}, mModelOptions, { json: true }));
		sap.ui.getCore().setModel(oModel);
		var oBinding = oModel.bindProperty("Supplier/Name");
		oModel.addBinding(oBinding);
		var oContext = oModel.getContext("/Products(1)");
		oBinding.setContext(oContext);

		var read = function(sPath, mParameters) {
			return new Promise(function(resolve) {
				mParameters = mParameters ? mParameters : {};
				mParameters.success = resolve;
				oModel.read(sPath, mParameters);
			});
		}

		var oMessageManager = sap.ui.getCore().getMessageManager();
		var oMessageModel = oMessageManager.getMessageModel();

		assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set at the beginning of the test");

		read("/Products(1)", {urlParameters:{"$expand":"Supplier"}}).then(function() {
			var aMessages = oMessageModel.getProperty("/");
			assert.equal(aMessages.length,1, "One message from the back-end");
			assert.equal(aMessages[0].target, "/Suppliers(1)/Name", "Message has correct target");
			assert.ok(oBinding.getDataState().getChanges(), "Messages propageted to binding");
			assert.equal(oBinding.getDataState().getMessages().length, 1, " 1 Message propageted to binding");
			assert.equal(oBinding.getDataState().getMessages()[0], aMessages[0], "Message propageted to binding");
			assert.equal(oBinding.getDataState().getMessages()[0].message, "This is a server test message", "Message has correct message text");
			oMessageManager.removeAllMessages();
			assert.equal(oMessageModel.getProperty("/").length, 0, "No messages are set after removal of all messages");
			oModel.destroy();
			done();
		});
	};

	QUnit.test("Propagate Message: Binding to NavProp",fnTestNavProp);
}


text:
namespace ParentLoadSoftDelete.DataAccess.ERLevel
{
    public partial interface IE10_CityDal
    {
    }
}

redpajama_set_name: RedPajamaGithub


text:
static double
form_volume(double radius, double thick_rim, double thick_face, double length)
{
    return M_PI*square(radius+thick_rim)*(length+2.0*thick_face);
}

static double
bicelle_kernel(double qab,
    double qc,
    double radius,
    double thick_radius,
    double thick_face,
    double halflength,
    double sld_core,
    double sld_face,
    double sld_rim,
    double sld_solvent)
{
    const double dr1 = sld_core-sld_face;
    const double dr2 = sld_rim-sld_solvent;
    const double dr3 = sld_face-sld_rim;
    const double vol1 = M_PI*square(radius)*2.0*(halflength);
    const double vol2 = M_PI*square(radius+thick_radius)*2.0*(halflength+thick_face);
    const double vol3 = M_PI*square(radius)*2.0*(halflength+thick_face);

    const double be1 = sas_2J1x_x((radius)*qab);
    const double be2 = sas_2J1x_x((radius+thick_radius)*qab);
    const double si1 = sas_sinx_x((halflength)*qc);
    const double si2 = sas_sinx_x((halflength+thick_face)*qc);

    const double t = vol1*dr1*si1*be1 +
                     vol2*dr2*si2*be2 +
                     vol3*dr3*si2*be1;

    return t;
}

static double
radius_from_excluded_volume(double radius, double thick_rim, double thick_face, double length)
{
    const double radius_tot = radius + thick_rim;
    const double length_tot = length + 2.0*thick_face;
    return 0.5*cbrt(0.75*radius_tot*(2.0*radius_tot*length_tot + (radius_tot + length_tot)*(M_PI*radius_tot + length_tot)));
}

static double
radius_from_volume(double radius, double thick_rim, double thick_face, double length)
{
    const double volume_bicelle = form_volume(radius,thick_rim,thick_face,length);
    return cbrt(volume_bicelle/M_4PI_3);
}

static double
radius_from_diagonal(double radius, double thick_rim, double thick_face, double length)
{
    const double radius_tot = radius + thick_rim;
    const double length_tot = length + 2.0*thick_face;
    return sqrt(radius_tot*radius_tot + 0.25*length_tot*length_tot);
}

static double
radius_effective(int mode, double radius, double thick_rim, double thick_face, double length)
{
    switch (mode) {
    default:
    case 1: // equivalent cylinder excluded volume
        return radius_from_excluded_volume(radius, thick_rim, thick_face, length);
    case 2: // equivalent sphere
        return radius_from_volume(radius, thick_rim, thick_face, length);
    case 3: // outer rim radius
        return radius + thick_rim;
    case 4: // half outer thickness
        return 0.5*length + thick_face;
    case 5: // half diagonal
        return radius_from_diagonal(radius,thick_rim,thick_face,length);
    }
}

static void
Fq(double q,
    double *F1,
    double *F2,
    double radius,
    double thick_radius,
    double thick_face,
    double length,
    double sld_core,
    double sld_face,
    double sld_rim,
    double sld_solvent)
{
    // set up the integration end points
    const double uplim = M_PI_4;
    const double halflength = 0.5*length;

    double total_F1 = 0.0;
    double total_F2 = 0.0;
    for(int i=0;i<GAUSS_N;i++) {
        double theta = (GAUSS_Z[i] + 1.0)*uplim;
        double sin_theta, cos_theta; // slots to hold sincos function output
        SINCOS(theta, sin_theta, cos_theta);
        double form = bicelle_kernel(q*sin_theta, q*cos_theta, radius, thick_radius, thick_face,
                                   halflength, sld_core, sld_face, sld_rim, sld_solvent);
        total_F1 += GAUSS_W[i]*form*sin_theta;
        total_F2 += GAUSS_W[i]*form*form*sin_theta;
    }
    // Correct for integration range
    total_F1 *= uplim;
    total_F2 *= uplim;

    *F1 = 1.0e-2*total_F1;
    *F2 = 1.0e-4*total_F2;
}

static double
Iqac(double qab, double qc,
    double radius,
    double thick_rim,
    double thick_face,
    double length,
    double core_sld,
    double face_sld,
    double rim_sld,
    double solvent_sld)
{
    double fq = bicelle_kernel(qab, qc, radius, thick_rim, thick_face,
                           0.5*length, core_sld, face_sld, rim_sld,
                           solvent_sld);
    return 1.0e-4*fq*fq;
}


text:
package com.twelvemonkeys.io.enc;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Random;

import static org.junit.Assert.assertArrayEquals;

public class EncoderStreamTest {

    private final Random rng = new Random(5467809876546L);

    private byte[] createData(final int length) {
        byte[] data = new byte[length];
        rng.nextBytes(data);
        return data;
    }

    @Test
    public void testEncodeSingleBytes() throws IOException {
        byte[] data = createData(1327);

        ByteArrayOutputStream result = new ByteArrayOutputStream();
        try (OutputStream stream = new EncoderStream(result, new NullEncoder())) {
            for (byte datum : data) {
                stream.write(datum);
            }
        }

        assertArrayEquals(data, result.toByteArray());
    }

    @Test
    public void testEncodeArray() throws IOException {
        byte[] data = createData(1793);

        ByteArrayOutputStream result = new ByteArrayOutputStream();
        try (OutputStream stream = new EncoderStream(result, new NullEncoder())) {
            for (int i = 0; i < 10; i++) {
                stream.write(data);
            }
        }

        byte[] encoded = result.toByteArray();

        for (int i = 0; i < 10; i++) {
            assertArrayEquals(data, Arrays.copyOfRange(encoded, i * data.length, (i + 1) * data.length));
        }
    }

    @Test
    public void testEncodeArrayOffset() throws IOException {
        byte[] data = createData(87);

        ByteArrayOutputStream result = new ByteArrayOutputStream();
        try (OutputStream stream = new EncoderStream(result, new NullEncoder())) {
            for (int i = 0; i < 10; i++) {
                stream.write(data, 13, 59);
            }
        }

        byte[] original = Arrays.copyOfRange(data, 13, 13 + 59);
        byte[] encoded = result.toByteArray();

        for (int i = 0; i < 10; i++) {
            assertArrayEquals(original, Arrays.copyOfRange(encoded, i * original.length, (i + 1) * original.length));
        }
    }

    private static final class NullEncoder implements Encoder {
        @Override
        public void encode(OutputStream stream, ByteBuffer buffer) throws IOException {
            stream.write(buffer.array(), buffer.arrayOffset(), buffer.remaining());
        }
    }
}


text:
int main(int argc, char** argv){

  //let's say we are taking in an input, but we want a number only
  //first we take it as a string
  std::string input;
  std::cout << "Please enter a number\n";
  std::cin >> input;

  //then we use a magic (not really) function conver it into a number called stoi
  //this was just introduced in C++11 so you HAVE to compile it with the -std=c++11 flag
  //its easy to use
  int number = std::stoi(input);

  //now we have a number!

  //lets go over loops: there's two main types

  //first, let's go over while loops
  //basically while loops mean that "while something is happening do this"
  //let's use our input
  //first lets create a variable to test against the input
  int test = 1;

  //then we do the loop!
  while (test < number + 1){

    std::cout << "I am " << test << " years old\n";

    //if we don't add this next like, this loop will go on forever and your computer will literally explode
    //ok not really, but it could be annoying
    //so let's add this
    test++; //a.k.a test += 1 a.k.a test = test + 1;

  }

  //now let's do for loops
  //there's three parts to this
  //the test variable is before the first semicolon, the condition before the second semicolon, and the variable change is the third paramater
  //note you can use any type of variable that makes sense, you can add by 2, 5, 10, you decrement, you add more conditional stuff or different conditional stuff
  for(int i = 0; i < number;i++){

    //easy!
    std::cout << "I am " << i + 1 << " years old\n";

  }

  //time for arrays
  //so as Bernie mentioned in lecture there's two types ways to declare arrays: the C-style and the modern style
  //the C-style is simple: we just do <type>* variableName = new <type>[N], where N is the size of the array
  //examples:

  //array of 10 booleans
  bool* booleans = new bool[10];
  //here's the catch, this is taking memory from the OS so we have to return it otherwise we get memory leaks
  //its easy
  delete[] booleans;

  //here's the modern way:
  //using vectors! std::vector<type> variabeName;
  std::vector<int> numbers;
  //can initalize too
  std::vector<int> numbersTwo(15); //vector with 15 0's
  std::vector<int> numbersThree(15,10); //vector with 15 10's
  std::vector<int> numbersFour = {3,6,7,8}; //vector containing 3,6,7,8

  //clear vectors
  numbersFour.clear();
  //add numbers to vectors
  numbersFour.push_back(13);
  numbersFour.push_back(7);
  numbersFour.push_back(17);

  //get size
  int sizeOfVector = numbersFour.size();

  //using loops....
  //arrays in C++ (and pretty much any important language) are 0-based, meaning the first number is at index 0
  for(int i = 0;i < sizeOfVector;i++){

    std::cout << numbersFour[i] << std::endl;

  }

  return 0;

}


text:
namespace content {
class RenderFrameHost;
}  // namespace content

// SerialChooserController provides data for the Serial API permission prompt.
class SerialChooserController final
    : public permissions::ChooserController,
      public SerialChooserContext::PortObserver {
 public:
  SerialChooserController(
      content::RenderFrameHost* render_frame_host,
      std::vector<blink::mojom::SerialPortFilterPtr> filters,
      content::SerialChooser::Callback callback);

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

  ~SerialChooserController() override;

  // permissions::ChooserController:
  bool ShouldShowHelpButton() const override;
  std::u16string GetNoOptionsText() const override;
  std::u16string GetOkButtonLabel() const override;
  std::pair<std::u16string, std::u16string> GetThrobberLabelAndTooltip()
      const override;
  size_t NumOptions() const override;
  std::u16string GetOption(size_t index) const override;
  bool IsPaired(size_t index) const override;
  void Select(const std::vector<size_t>& indices) override;
  void Cancel() override;
  void Close() override;
  void OpenHelpCenterUrl() const override;

  // SerialChooserContext::PortObserver:
  void OnPortAdded(const device::mojom::SerialPortInfo& port) override;
  void OnPortRemoved(const device::mojom::SerialPortInfo& port) override;
  void OnPortManagerConnectionError() override;
  void OnPermissionRevoked(const url::Origin& origin) override {}

 private:
  void OnGetDevices(std::vector<device::mojom::SerialPortInfoPtr> ports);
  bool DisplayDevice(const device::mojom::SerialPortInfo& port) const;
  void AddMessageToConsole(blink::mojom::ConsoleMessageLevel level,
                           const std::string& message) const;
  void RunCallback(device::mojom::SerialPortInfoPtr port);

  std::vector<blink::mojom::SerialPortFilterPtr> filters_;
  content::SerialChooser::Callback callback_;
  content::WeakDocumentPtr initiator_document_;
  url::Origin origin_;

  base::WeakPtr<SerialChooserContext> chooser_context_;
  base::ScopedObservation<SerialChooserContext,
                          SerialChooserContext::PortObserver>
      observation_{this};

  std::vector<device::mojom::SerialPortInfoPtr> ports_;

  base::WeakPtrFactory<SerialChooserController> weak_factory_{this};
};

#endif  // CHROME_BROWSER_UI_SERIAL_SERIAL_CHOOSER_CONTROLLER_H_


text:
from .helpers import insights_upload_conf
from mock.mock import call, patch
from pytest import raises

collection_rules_file = "/tmp/collection_rules"
collection_fallback_file = "/tmp/collection_fallback"

def patch_collection_rules_file():
    """
    Makes collection_rules_file contain a fixed path.
    """
    def decorator(old_function):
        patcher = patch("insights.client.collection_rules.constants.collection_rules_file", collection_rules_file)
        return patcher(old_function)
    return decorator

def patch_collection_fallback_file():
    """
    Makes collection_fallback_file contain a fixed path.
    """
    def decorator(old_function):
        patcher = patch("insights.client.collection_rules.constants.collection_fallback_file", collection_fallback_file)
        return patcher(old_function)
    return decorator

def patch_try_disk(return_values):
    """
    Makes try_disk sequentially return the passed contents.
    """
    def decorator(old_function):
        patcher = patch("insights.client.collection_rules.InsightsUploadConf.try_disk", side_effect=return_values)
        return patcher(old_function)
    return decorator

@patch_try_disk([{"version": "1.2.3"}])
@patch_collection_rules_file()
def test_collection_rules_file_try_disk(try_disk):
    """
    Collection rules are loaded from the default file while performing signature validation.
    """
    gpg = "perhaps"
    upload_conf = insights_upload_conf(gpg=gpg)
    upload_conf.get_conf_file()

    try_disk.assert_called_once_with(collection_rules_file, gpg)

@patch_try_disk([{"version": None}])
def test_collection_rules_file_no_version_error(try_disk):
    """
    Collection rules from the default file are rejected if they don't specify version.
    """
    upload_conf = insights_upload_conf()

    with raises(ValueError):
        upload_conf.get_conf_file()

@patch_try_disk([{"version": "1.2.3"}])
@patch_collection_rules_file()
def test_return_collection_rules(try_disk):
    """
    Collection rules from the default file are returned with the filename appended to the data.
    """
    upload_conf = insights_upload_conf()

    assert upload_conf.get_conf_file() == {"version": "1.2.3", "file": collection_rules_file}

@patch_try_disk([None, {"version": "1.2.3"}])
@patch_collection_fallback_file()
@patch_collection_rules_file()
def test_fallback_file_try_disk(try_disk):
    """
    If there are no collection rules in the default file, they are loaded from the fallback file while performing
    signature validation.
    """
    gpg = "perhaps"
    upload_conf = insights_upload_conf(gpg=gpg)

    upload_conf.get_conf_file()

    calls = [call(collection_rules_file, gpg), call(collection_fallback_file, gpg)]
    try_disk.assert_has_calls(calls)

@patch_try_disk([None, {"version": None}])
def test_fallback_file_no_version_error(try_disk):
    """
    Collection rules from the fallback file are rejected if they don't specify version.
    """
    upload_conf = insights_upload_conf()

    with raises(ValueError):
        upload_conf.get_conf_file()

@patch_try_disk([None, {"version": "1.2.3"}])
@patch_collection_fallback_file()
def test_return_collection_fallback(try_disk):
    """
    Collection rules from the fallback file are returned with the filename appended to the data.
    """
    upload_conf = insights_upload_conf()

    assert upload_conf.get_conf_file() == {"version": "1.2.3", "file": collection_fallback_file}

@patch_try_disk([None, None])
def test_no_file_error(try_disk):
    """
    An error is raised if there are no collection rules neither in the default nor the fallback file.
    """
    upload_conf = insights_upload_conf()

    with raises(RuntimeError):
        upload_conf.get_conf_file()


text:
title: Long Polynomial Division
localeTitle: Длинный полиномиальный дивизион
---
## Длинный полиномиальный дивизион

Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/long-polynomial-division/index.md) .

[Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Дополнительная информация:


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Ember.js • TodoMVC</title>
    <link rel="stylesheet" href="style.css">


text:
require 'rails_helper'

RSpec.describe Issue, type: :model do
  it "has an authenticated user"
  it "is invalid without an issue name"
  it "is invalid without a start date"
end


text:
package com.appnexus.opensdk;

public enum ANClickThroughAction {
    RETURN_URL,
    OPEN_SDK_BROWSER,
    OPEN_DEVICE_BROWSER
}


text:
package org.elasticsearch.search.aggregations.matrix.stats;

import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.aggregations.InternalAggregation;
import org.elasticsearch.search.aggregations.metrics.InternalMetricsAggregation;
import org.elasticsearch.search.aggregations.pipeline.PipelineAggregator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.util.Collections.emptyMap;

/**
 * Computes distribution statistics over multiple fields
 */
public class InternalMatrixStats extends InternalMetricsAggregation implements MatrixStats {
    /** per shard stats needed to compute stats */
    private final RunningStats stats;
    /** final result */
    private final MatrixStatsResults results;

    /** per shard ctor */
    protected InternalMatrixStats(String name, long count, RunningStats multiFieldStatsResults, MatrixStatsResults results,
                                  List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) {
        super(name, pipelineAggregators, metaData);
        assert count >= 0;
        this.stats = multiFieldStatsResults;
        this.results = results;
    }

    /**
     * Read from a stream.
     */
    public InternalMatrixStats(StreamInput in) throws IOException {
        stats = in.readOptionalWriteable(RunningStats::new);
        results = in.readOptionalWriteable(MatrixStatsResults::new);
    }

    @Override
    protected void doWriteTo(StreamOutput out) throws IOException {
        out.writeOptionalWriteable(stats);
        out.writeOptionalWriteable(results);
    }

    @Override
    public String getWriteableName() {
        return MatrixStatsAggregationBuilder.NAME;
    }

    /** get the number of documents */
    @Override
    public long getDocCount() {
        return stats.docCount;
    }

    /** get the number of samples for the given field. == docCount - numMissing */
    @Override
    public long getFieldCount(String field) {
        if (results == null) {
            return 0;
        }
        return results.getFieldCount(field);
    }

    /** get the mean for the given field */
    @Override
    public double getMean(String field) {
        if (results == null) {
            return Double.NaN;
        }
        return results.getMean(field);
    }

    /** get the variance for the given field */
    @Override
    public double getVariance(String field) {
        if (results == null) {
            return Double.NaN;
        }
        return results.getVariance(field);
    }

    /** get the distribution skewness for the given field */
    @Override
    public double getSkewness(String field) {
        if (results == null) {
            return Double.NaN;
        }
        return results.getSkewness(field);
    }

    /** get the distribution shape for the given field */
    @Override
    public double getKurtosis(String field) {
        if (results == null) {
            return Double.NaN;
        }
        return results.getKurtosis(field);
    }

    /** get the covariance between the two fields */
    @Override
    public double getCovariance(String fieldX, String fieldY) {
        if (results == null) {
            return Double.NaN;
        }
        return results.getCovariance(fieldX, fieldY);
    }

    /** get the correlation between the two fields */
    @Override
    public double getCorrelation(String fieldX, String fieldY) {
        if (results == null) {
            return Double.NaN;
        }
        return results.getCorrelation(fieldX, fieldY);
    }

    static class Fields {
        public static final String FIELDS = "fields";
        public static final String NAME = "name";
        public static final String COUNT = "count";
        public static final String MEAN = "mean";
        public static final String VARIANCE = "variance";
        public static final String SKEWNESS = "skewness";
        public static final String KURTOSIS = "kurtosis";
        public static final String COVARIANCE = "covariance";
        public static final String CORRELATION = "correlation";
    }

    @Override
    public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
        if (results != null && results.getFieldCounts().keySet().isEmpty() == false) {
            builder.startArray(Fields.FIELDS);
            for (String fieldName : results.getFieldCounts().keySet()) {
                builder.startObject();
                // name
                builder.field(Fields.NAME, fieldName);
                // count
                builder.field(Fields.COUNT, results.getFieldCount(fieldName));
                // mean
                builder.field(Fields.MEAN, results.getMean(fieldName));
                // variance
                builder.field(Fields.VARIANCE, results.getVariance(fieldName));
                // skewness
                builder.field(Fields.SKEWNESS, results.getSkewness(fieldName));
                // kurtosis
                builder.field(Fields.KURTOSIS, results.getKurtosis(fieldName));
                // covariance
                builder.startObject(Fields.COVARIANCE);
                for (String fieldB : results.getFieldCounts().keySet()) {
                    builder.field(fieldB, results.getCovariance(fieldName, fieldB));
                }
                builder.endObject();
                // correlation
                builder.startObject(Fields.CORRELATION);
                for (String fieldB : results.getFieldCounts().keySet()) {
                    builder.field(fieldB, results.getCorrelation(fieldName, fieldB));
                }
                builder.endObject();
                builder.endObject();
            }
            builder.endArray();
        }
        return builder;
    }

    @Override
    public Object getProperty(List<String> path) {
        if (path.isEmpty()) {
            return this;
        } else if (path.size() == 1) {
            String element = path.get(0);
            if (results == null) {
                return emptyMap();
            }
            switch (element) {
                case "counts":
                    return results.getFieldCounts();
                case "means":
                    return results.getMeans();
                case "variances":
                    return results.getVariances();
                case "skewness":
                    return results.getSkewness();
                case "kurtosis":
                    return results.getKurtosis();
                case "covariance":
                    return results.getCovariances();
                case "correlation":
                    return results.getCorrelations();
                default:
                    throw new IllegalArgumentException("Found unknown path element [" + element + "] in [" + getName() + "]");
            }
        } else {
            throw new IllegalArgumentException("path not supported for [" + getName() + "]: " + path);
        }
    }

    @Override
    public InternalAggregation doReduce(List<InternalAggregation> aggregations, ReduceContext reduceContext) {
        // merge stats across all shards
        List<InternalAggregation> aggs = new ArrayList<>(aggregations);
        aggs.removeIf(p -> ((InternalMatrixStats)p).stats == null);

        // return empty result iff all stats are null
        if (aggs.isEmpty()) {
            return new InternalMatrixStats(name, 0, null, new MatrixStatsResults(), pipelineAggregators(), getMetaData());
        }

        RunningStats runningStats = new RunningStats();
        for (int i=0; i < aggs.size(); ++i) {
            runningStats.merge(((InternalMatrixStats) aggs.get(i)).stats);
        }
        MatrixStatsResults results = new MatrixStatsResults(runningStats);

        return new InternalMatrixStats(name, results.getDocCount(), runningStats, results, pipelineAggregators(), getMetaData());
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Interface engine.rendering.IRenderContext</title>
<meta name="date" content="2015-07-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
engine.rendering.IRenderContext

Packages that use IRenderContext

Package
Description

engine.components

Provides various components that are useful in virtually any application.

engine.core

Classes defining the core functionality of the game engine.

engine.core.entity

Classes for defining the objects in the game and their functionality.

engine.rendering

Classes for rendering graphics.

engine.rendering.opengl

Classes for rendering graphics with OpenGL.

engine.util.menu

Classes for creating and rendering a menu.

Uses of IRenderContext in engine.components

Methods in engine.components with parameters of type IRenderContext

Modifier and Type
Method and Description

void
SpriteComponent.render(IRenderContext target,
      double viewportX,
      double viewportY)

void
LightComponent.render(IRenderContext target,
      double viewportX,
      double viewportY)

Uses of IRenderContext in engine.core

Methods in engine.core with parameters of type IRenderContext

Modifier and Type
Method and Description

abstract void
Scene.render(IRenderContext target)

Renders the scene

Uses of IRenderContext in engine.core.entity

Methods in engine.core.entity with parameters of type IRenderContext

Modifier and Type
Method and Description

void
Entity.render(IRenderContext target,
      double viewportX,
      double viewportY)

Renders all the components attached to this entity.

void
EntityComponent.render(IRenderContext target,
      double viewportX,
      double viewportY)

Renders this component.

Uses of IRenderContext in engine.rendering

Classes in engine.rendering that implement IRenderContext

Modifier and Type
Class and Description

class
RenderContext

An implementation of higher-level rendering functions.

Methods in engine.rendering that return IRenderContext

Modifier and Type
Method and Description

IRenderContext
IDisplay.getRenderContext()

Gets the render context that can be used with this display.

Uses of IRenderContext in engine.rendering.opengl

Methods in engine.rendering.opengl that return IRenderContext

Modifier and Type
Method and Description

IRenderContext
OpenGLDisplay.getRenderContext()

Uses of IRenderContext in engine.util.menu

Methods in engine.util.menu with parameters of type IRenderContext

Modifier and Type
Method and Description

void
MenuStack.render(IRenderContext target)

Render the current menu.

void
Menu.render(IRenderContext target,
      SpriteSheet font,
      double offsetX,
      double offsetY,
      double scale,
      Color selectionColor,
      Color fontColor)

Renders the menu.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
#define BOOST_RANDOM_SOURCE

#include <boost/random/random_device.hpp>
#include <boost/config.hpp>
#include <boost/assert.hpp>
#include <boost/detail/workaround.hpp>
#include <string>

#if !defined(BOOST_NO_INCLASS_MEMBER_INITIALIZATION) && !BOOST_WORKAROUND(BOOST_MSVC, BOOST_TESTED_AT(1600))
//  A definition is required even for integral static constants
const bool boost::random::random_device::has_fixed_range;
#endif

#if defined(BOOST_WINDOWS)

#include <windows.h>
#include <wincrypt.h>
#include <stdexcept>  // std::invalid_argument

#define BOOST_AUTO_LINK_NOMANGLE
#define BOOST_LIB_NAME "Advapi32"
#include <boost/config/auto_link.hpp>

#ifdef __MINGW32__

extern "C" {

// mingw's wincrypt.h appears to be missing some things
WINADVAPI
BOOL
WINAPI
CryptEnumProvidersA(
    DWORD dwIndex,
    DWORD *pdwReserved,
    DWORD dwFlags,
    DWORD *pdwProvType,
    LPSTR szProvName,
    DWORD *pcbProvName
    );

}

#endif

namespace {

const char * const default_token = MS_DEF_PROV_A;

}

class boost::random::random_device::impl
{
public:
  impl(const std::string & token) : provider(token) {
    char buffer[80];
    DWORD type;
    DWORD len;

    // Find the type of the provider
    for(DWORD i = 0; ; ++i) {
      len = sizeof(buffer);
      if(!CryptEnumProvidersA(i, NULL, 0, &type, buffer, &len)) {
        error("Could not find provider name");
      }
      if(buffer == provider) {
        break;
      }
    }

    if(!CryptAcquireContextA(&hProv, NULL, provider.c_str(), type,
        CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
      error("Could not acquire CSP context");
    }
  }

  ~impl() {
    if(!CryptReleaseContext(hProv, 0)) error("Could not release CSP context");
  }

  unsigned int next() {
    unsigned int result;

    if(!CryptGenRandom(hProv, sizeof(result),
        static_cast<BYTE*>(static_cast<void*>(&result)))) {
      error("error while reading");
    }

    return result;
  }

private:
  void error(const std::string & msg) {
    char buf[80];
    DWORD num = FormatMessageA(
      FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
      NULL,
      GetLastError(),
      0,
      buf,
      sizeof(buf),
      NULL);

    throw std::invalid_argument("boost::random_device: " + msg +
                                " Cryptopraphic Service Provider " + provider +
                                ": " + std::string(&buf[0], &buf[0] + num));
  }
  const std::string provider;
  HCRYPTPROV hProv;
};

#else

namespace {
// the default is the unlimited capacity device, using some secure hash
// try "/dev/random" for blocking when the entropy pool has drained
const char * const default_token = "/dev/urandom";
}

/*
 * This uses the POSIX interface for unbuffered reading.
 * Using buffered std::istream would consume entropy which may
 * not actually be used.  Entropy is a precious good we avoid
 * wasting.
 */

#if defined(__GNUC__) && defined(_CXXRT_STD_NAME)
// I have severe difficulty to get the POSIX includes to work with
// -fhonor-std and Dietmar Kuhl's standard C++ library.  Hack around that
// problem for now.
extern "C" {
static const int O_RDONLY = 0;
extern int open(const char *__file, int __oflag, ...);
extern int read(int __fd, __ptr_t __buf, size_t __nbytes);
extern int close(int __fd);
}
#else
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>    // open
#include <unistd.h>   // read, close
#endif

#include <errno.h>    // errno
#include <string.h>   // strerror
#include <stdexcept>  // std::invalid_argument

class boost::random::random_device::impl
{
public:
  impl(const std::string & token) : path(token) {
    fd = open(token.c_str(), O_RDONLY);
    if(fd < 0)
      error("cannot open");
  }

  ~impl() { if(close(fd) < 0) error("could not close"); }

  unsigned int next() {
    unsigned int result;
    long sz = read(fd, reinterpret_cast<char *>(&result), sizeof(result));
    if(sz == -1)
      error("error while reading");
    else if(sz != sizeof(result)) {
      errno = 0;
      error("EOF while reading");
    }
    return result;
  }

private:
  void error(const std::string & msg) {
    throw std::invalid_argument("boost::random_device: " + msg +
                                " random-number pseudo-device " + path +
                                ": " + strerror(errno));
  }
  const std::string path;
  int fd;
};

#endif // BOOST_WINDOWS

BOOST_RANDOM_DECL boost::random::random_device::random_device()
  : pimpl(new impl(default_token))
{}

BOOST_RANDOM_DECL boost::random::random_device::random_device(const std::string& token)
  : pimpl(new impl(token))
{}

BOOST_RANDOM_DECL boost::random_device::~random_device()
{
  delete pimpl;
}

BOOST_RANDOM_DECL double boost::random_device::entropy() const
{
  return 10;
}

BOOST_RANDOM_DECL unsigned int boost::random_device::operator()()
{
  return pimpl->next();
}


text:
package service

import scalikejdbc._
import scalikejdbc.scalatest.AutoRollback

import org.scalatest._

class ServiceSpec extends fixture.FunSpec with Matchers with Connection with CreateTables with AutoRollback {

  override def db(): DB = NamedDB('service).toDB()

  override def fixture(implicit session: DBSession): Unit = {
    val serviceNo = Service.createWithAttributes('name -> "Cool Web Service")
    Application.createWithAttributes('name -> "Smartphone site", 'serviceNo   -> serviceNo)
    Application.createWithAttributes('name -> "PC site", 'serviceNo           -> serviceNo)
    Application.createWithAttributes('name -> "Featurephone site", 'serviceNo -> serviceNo)
  }

  describe("hasMany without byDefault") {
    it("should work as expected") { implicit session =>
      val service = Service.joins(Service.applications).findAll().head
      service.applications.size should equal(3)
    }
  }

  describe("belongsTo without byDefault") {
    it("should work as expected") { implicit session =>
      val app = Application.joins(Application.service).findAll().head
      app.service.isDefined should equal(true)

      val beforeService = Service.joins(Service.applications).findById(app.serviceNo).get

      Application.deleteById(beforeService.applications.head.id)

      val afterService = Service.joins(Service.applications).findById(app.serviceNo).get
      afterService.applications.size should equal(
        beforeService.applications.size - 1
      )
    }
  }
}


text:
#pragma once
#include <stdint.h>

namespace OPC {

    enum Command {
        SetPixelColors = 0x00,
        SystemExclusive = 0xFF,
    };

    // SysEx system and command IDs
    enum SysEx {
        FCSetGlobalColorCorrection = 0x00010001,
        FCSetFirmwareConfiguration = 0x00010002
    };

    struct Message
    {
        uint8_t channel;
        uint8_t command;
        uint8_t lenHigh;
        uint8_t lenLow;
        uint8_t data[0xFFFF];

        unsigned length() const {
            return lenLow | (unsigned(lenHigh) << 8);
        }

        void setLength(unsigned l) {
            lenLow = (uint8_t) l;
            lenHigh = (uint8_t) (l >> 8);
        }
    };

    static const unsigned HEADER_BYTES = 4;

    typedef void (*callback_t)(Message &msg, void *context);
}


text:
/**
 * conbo.Context
 *
 * This is your application's event bus and dependency injector, and is
 * usually where all your models and web service classes are registered,
 * using mapSingleton(...), and Command classes are mapped to events
 *
 * @class		Context
 * @memberof	conbo
 * @augments	conbo.EventDispatcher
 * @author		Neil Rackett
 * @param 		{Object} options - Object containing initialisation options, including 'app' (Application) and 'namespace' (Namespace)
 */
conbo.Context = conbo.EventDispatcher.extend(
/** @lends conbo.Context.prototype */
{
	/**
	 * Constructor: DO NOT override! (Use initialize instead)
	 * @param options
	 */
	__construct: function(options)
	{
		__definePrivateProperties(this,
		{
			__commands: options.commands || {},
			__singletons: options.singletons || {},
			__app: options.app,
			__namespace: options.namespace || options.app.namespace,
			__parentContext: options.context
		});

		this.addEventListener(conbo.Event.ALL, this.__allHandler);
	},

	/**
	 * The Application instance associated with this context
	 * @returns {conbo.Application}
	 */
	get app()
	{
		return this.__app;
	},

	/**
	 * The Namespace this context exists in
	 * @returns {conbo.Namespace}
	 */
	get namespace()
	{
		return this.__namespace;
	},

	/**
	 * If this is a subcontext, this is a reference to the Context that created it
	 * @returns {conbo.Context}
	 */
	get parentContext()
	{
		return this.__parentContext;
	},

	/**
	 * Create a new subcontext that shares the same application
	 * and namespace as this one
	 *
	 * @param	{class} [contextClass] - The context class to use (default: conbo.Context)
	 * @param	{boolean} [cloneSingletons] - Should this Context's singletons be duplicated on the new subcontext? (default: false)
	 * @param	{boolean} [cloneCommands] - Should this Context's commands be duplicated on the new subcontext? (default: false)
	 * @returns {conbo.Context}
	 */
	createSubcontext: function(contextClass, cloneSingletons, cloneCommands)
	{
		contextClass || (contextClass = conbo.Context);
		return new contextClass
		({
			context: this,
			app: this.app,
			namespace: this.namespace,
			commands: cloneCommands ? conbo.clone(this.__commands) : undefined,
			singletons: cloneSingletons ? conbo.clone(this.__singletons) : undefined
		});
	},

	/**
	 * Map specified Command class the given event
	 * @param	{string}	eventType - The name of the event
	 * @param	{class}		commandClass - The command class to instantiate when the event is dispatched
	 */
	mapCommand: function(eventType, commandClass)
	{
		if (!eventType) throw new Error('eventType cannot be undefined');
		if (!commandClass) throw new Error('commandClass for '+eventType+' cannot be undefined');

		if (this.__commands[eventType] && this.__commands[eventType].indexOf(commandClass) != -1)
		{
			return this;
		}

		this.__commands[eventType] = this.__commands[eventType] || [];
		this.__commands[eventType].push(commandClass);

		return this;
	},

	/**
	 * Unmap specified Command class from given event
	 */
	unmapCommand: function(eventType, commandClass)
	{
		if (!eventType) throw new Error('eventType cannot be undefined');

		if (commandClass === undefined)
		{
			delete this.__commands[eventType];
			return this;
		}

		if (!this.__commands[eventType]) return;
		var index = this.__commands[eventType].indexOf(commandClass);
		if (index == -1) return;
		this.__commands[eventType].splice(index, 1);

		return this;
	},

	/**
	 * Map class instance to a property name
	 *
	 * To inject a property into a class, register the property name
	 * with the Context and declare the value as undefined in your class
	 * to enable it to be injected at run time
	 *
	 * @example		context.mapSingleton('myProperty', MyModel);
	 * @example		myProperty: undefined
	 */
	mapSingleton: function(propertyName, singletonClass)
	{
		if (!propertyName) throw new Error('propertyName cannot be undefined');

		if (singletonClass === undefined)
		{
			conbo.warn('singletonClass for '+propertyName+' is undefined');
		}

		if (conbo.isClass(singletonClass))
		{
			var args = conbo.rest(arguments);

			if (args.length == 1 && singletonClass.prototype instanceof conbo.ConboClass)
			{
				args.push(this);
			}

			this.__singletons[propertyName] = new (Function.prototype.bind.apply(singletonClass, args))
		}
		else
		{
			this.__singletons[propertyName] = singletonClass;
		}

		return this;
	},

	/**
	 * Unmap class instance from a property name
	 */
	unmapSingleton: function(propertyName)
	{
		if (!propertyName) throw new Error('propertyName cannot be undefined');

		if (!this.__singletons[propertyName]) return;
		delete this.__singletons[propertyName];

		return this;
	},

	/**
	 * Map constant value to a property name
	 *
	 * To inject a constant into a class, register the property name
	 * with the Context and declare the property as undefined in your
	 * class to enable it to be injected at run time
	 *
	 * @example		context.mapConstant('MY_VALUE', 123);
	 * @example		MY_VALUE: undefined
	 */
	mapConstant: function(propertyName, value)
	{
		return this.mapSingleton(propertyName, value);
	},

	/**
	 * Unmap constant value from a property name
	 */
	unmapConstant: function(propertyName)
	{
		return this.unmapSingleton(propertyName);
	},

	/**
	 * Add this Context to the specified Object, or create an object with a
	 * reference to this Context
	 */
	addTo: function(obj)
	{
		return conbo.defineValues(obj || {}, {context:this});
	},

	/**
	 * Inject singleton instances into specified object
	 *
	 * @param	obj		{Object} 	The object to inject singletons into
	 */
	injectSingletons: function(obj)
	{
		var scope = this;

		for (var a in scope.__singletons)
		{
			if (a in obj)
			{
				(function(value)
				{
					Object.defineProperty(obj, a,
					{
						configurable: true,
						get: function() { return value; }
					});
				})(scope.__singletons[a]);
			}
		}

		return this;
	},

	/**
	 * Set all singleton instances on the specified object to undefined
	 *
	 * @param	obj		{Object} 	The object to remove singletons from
	 */
	uninjectSingletons: function(obj)
	{
		for (var a in this.__singletons)
		{
			if (a in obj)
			{
				Object.defineProperty(obj, a,
				{
					configurable: true,
					value: undefined
				});
			}
		}

		return this;
	},

	/**
	 * Clears all commands and singletons, and removes all listeners
	 */
	destroy: function()
	{
		conbo.assign(this,
		{
			__commands: undefined,
			__singletons: undefined,
			__app: undefined,
			__namespace: undefined,
			__parentContext: undefined
		});

		this.removeEventListener();

		return this;
	},

	toString: function()
	{
		return 'conbo.Context';
	},

	/**
	 * @private
	 */
	__allHandler: function(event)
	{
		var commands = conbo.union(this.__commands.all || [], this.__commands[event.type] || []);
		if (!commands.length) return;

		conbo.forEach(commands, function(commandClass, index, list)
		{
			this.__executeCommand(commandClass, event);
		},
		this);
	},

	/**
	 * @private
	 */
	__executeCommand: function(commandClass, event)
	{
		var command, options;

		options = {event:event};

		command = new commandClass(this.addTo(options));
		command.execute();
		command = null;

		return this;
	},

});

__denumerate(conbo.Context.prototype);


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fr.avianey.androidsvgdrawable.sample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="23" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/icon"
        android:label="@string/app_name"
        android:theme="@style/GdxTheme" >
        <activity
            android:name="fr.avianey.androidsvgdrawable.sample.AndroidLauncher"
            android:label="@string/app_name"
            android:screenOrientation="landscape"
            android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
#ifndef CAFFE2_OPERATORS_LAYER_NORM_OP_H
#define CAFFE2_OPERATORS_LAYER_NORM_OP_H

#include "caffe2/core/context.h"
#include "caffe2/core/operator.h"
#include "caffe2/utils/math.h"

namespace caffe2 {

template <class Context>
class LayerNormOp : public Operator<Context> {
 public:
  USE_OPERATOR_CONTEXT_FUNCTIONS;
  LayerNormOp(const OperatorDef& operator_def, Workspace* ws)
      : Operator<Context>(operator_def, ws),
        axis_(OperatorBase::GetSingleArgument<int>("axis", 1)),
        epsilon_(OperatorBase::GetSingleArgument<float>("epsilon", 1e-5f)) {}
  ~LayerNormOp() {}

  template <typename T>
  bool DoRunWithType();

  bool RunOnDevice() override {
    return DoRunWithType<float>();
  }

 protected:
  int axis_;
  float epsilon_;

  Tensor<Context> scratch_;
  Tensor<Context> seg_indices_;
};

template <class Context>
class LayerNormGradientOp : public Operator<Context> {
 public:
  USE_OPERATOR_CONTEXT_FUNCTIONS;
  LayerNormGradientOp(const OperatorDef& operator_def, Workspace* ws)
      : Operator<Context>(operator_def, ws),
        axis_(OperatorBase::GetSingleArgument<int>("axis", 1)),
        epsilon_(OperatorBase::GetSingleArgument<float>("epsilon", 0.001)) {}
  ~LayerNormGradientOp() {}

  template <typename T>
  bool DoRunWithType();

  bool RunOnDevice() override {
    return DoRunWithType<float>();
  }

 protected:
  int axis_;
  float epsilon_;

  Tensor<Context> scratch_;
  Tensor<Context> gscratch_;
  Tensor<Context> seg_indices_;
  Tensor<Context> dstdev_;
  Tensor<Context> dmean_;
};

} // namespace caffe2

#endif /* CAFFE2_OPERATORS_LAYER_NORM_OP_H */


text:
/*global hatchet: false, document: false, NodeFilter: false, window: false, alert: false, confirm: false, console: false, Debug: false, opera: false, prompt: false, WSH: false */
hatchet.htmlTextNodeWalker = function () {
    var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false),
        node;
    while (node = walker.nextNode()) {
        node.nodeValue = hatchet.wickedizer(node.nodeValue);
    }
};