text:
/*global QUnit, sinon */
sap.ui.define([
	"sap/ui/thirdparty/jquery",
	"sap/m/GenericTile",
	"sap/m/NumericContent",
	"sap/m/TileContent",
	"sap/ui/core/TooltipBase",
	"sap/ui/core/ResizeHandler",
	"sap/m/library",
	"sap/ui/util/Mobile",
	"sap/ui/core/Core"
], function (jQuery, GenericTile, NumericContent, TileContent, TooltipBase, ResizeHandler, library, Mobile, oCore) {
	"use strict";

	var oResourceBundle = oCore.getLibraryResourceBundle("sap.m");

	// shortcut for sap.m.ValueColor
	var ValueColor = library.ValueColor;

	// shortcut for sap.m.DeviationIndicator
	var DeviationIndicator = library.DeviationIndicator;

	// shortcut for sap.m.LoadState
	var LoadState = library.LoadState;

	// shortcut for sap.m.Size
	var Size = library.Size;

	Mobile.init();

	QUnit.module("Rendering test - sap.m.NumericContent", {
		beforeEach: function () {
			this.oNumericContent = fnCreateExampleNumericContent();
			this.oNumericContent.placeAt("qunit-fixture");
			oCore.applyChanges();
		},
		afterEach: function () {
			this.oNumericContent.destroy();
			this.oNumericContent = null;
		}
	});
	QUnit.test("Numeric Content rendered.", function (assert) {
		this.oNumericContent.setValue("12");
		oCore.applyChanges();
		fnAssertNumericContentHasRendered(assert);
	});

	QUnit.test("Numeric Content rendered with correct value and scale when formatterValue is set to true.", function (assert) {
		var value = '12.2';
		var scale = '%';

		this.oNumericContent.setFormatterValue(true);

		this.oNumericContent.setValue(value + scale);
		oCore.applyChanges();
		assert.strictEqual(document.getElementById("numeric-cnt-value-inner").innerText, value, "Value is rendered correctly");
		assert.strictEqual(document.getElementById("numeric-cnt-scale").innerText, scale, "Scale is rendered correctly");

		// for few countries metric representation is different
		// for eg; in turkish % is written as %12.2 instead of 12.2%
		this.oNumericContent.setValue(scale + value);
		oCore.applyChanges();
		assert.strictEqual(document.getElementById("numeric-cnt-value-inner").innerText, value, "Value is rendered correctly");
		assert.strictEqual(document.getElementById("numeric-cnt-scale").innerText, scale, "Scale is rendered correctly");
	});

	QUnit.test("Numeric Content - Render Placeholder loading animation", function (assert) {
		//Switch to Loading State
		this.oNumericContent.setState(LoadState.Loading);
		oCore.applyChanges();
		assert.ok(document.querySelector(".sapMNCLoadingShimmer"), "Loading Shimmer present on 'Loading' state");

		//Switch to Loaded State
		this.oNumericContent.setState(LoadState.Loaded);
		oCore.applyChanges();
		assert.equal(document.querySelector(".sapMNCLoadingShimmer"), null, "Loading Shimmer absent on 'Loaded' state");
	});

	QUnit.test("Numeric Content - State test", function (assert) {
		this.oNumericContent.setValue(200);

		//Switch to Loading State
		this.oNumericContent.setState(LoadState.Loading);
		oCore.applyChanges();
		assert.ok(document.querySelector(".sapMNCLoadingShimmer"), "Loading Shimmer present on 'Loading' state");
		assert.equal(getComputedStyle(document.querySelector(".sapMNCLoadingShimmer")).opacity, "1" ,"Loading Shimmer Opacity is set correctly");
		assert.equal(getComputedStyle(document.querySelector(".sapMNCValue.Good.Loading")).opacity, "1" ,"NumericContent Opacity is set correctly");

		//Switch to Loaded State
		this.oNumericContent.setState(LoadState.Loaded);
		oCore.applyChanges();
		assert.equal(document.querySelector(".sapMNCLoadingShimmer"), null, "Loading Shimmer absent on 'Loaded' state");
		assert.equal(getComputedStyle(document.querySelector(".sapMNCValue.Good.Loaded")).opacity, "1" ,"NumericContent Opacity is set correctly");

		//Switch to Failed State
		this.oNumericContent.setState(LoadState.Failed);
		oCore.applyChanges();
		assert.equal(getComputedStyle(document.querySelector(".sapMNCValue.Good.Failed")).opacity, "0.25" ,"sapMNCValue Opacity is set correctly");
		assert.equal(getComputedStyle(document.querySelector(".sapMNCIconImage.Failed")).opacity, "1" ,"sapMNCValue Opacity is set correctly");
		assert.equal(getComputedStyle(document.querySelector(".sapMNCScale.Failed")).opacity, "1" ,"sapMNCScale Opacity is set correctly");

	});

	QUnit.test("Numeric Content has ARIA properties", function (assert) {
		assert.strictEqual(this.oNumericContent.$().attr("role"), "img", "The role is set to 'img'");
		assert.strictEqual(this.oNumericContent.$().attr("aria-label"), this.oNumericContent.getTooltip_AsString(), "The aria-label is set to numeric content's tooltip");
		assert.strictEqual(this.oNumericContent.$().attr("aria-roledescription"),  oResourceBundle.getText("NUMERIC_CONTENT_ROLE_DESCRIPTION"), "The roledescription is set to 'Numeric Content'");
	});

	QUnit.test("The Icon's cursor is pointer if press event is attached", function (assert) {
		// Arrange
		var oSpy = sinon.spy(this.oNumericContent, "_setPointerOnIcon");
		// Act
		this.oNumericContent.attachPress(function () {});
		// Assert
		assert.strictEqual(oSpy.callCount, 1, "setPointerOnIcon was called.");
		assert.ok(this.oNumericContent._oIcon.hasStyleClass("sapMPointer"), "sapMPointer class was added");
	});

	QUnit.test("The Icon's cursor is default if press event is detached", function (assert) {
		// Arrange
		var oSpy = sinon.spy(this.oNumericContent, "_setPointerOnIcon");
		function onPress () {}
		// Act
		this.oNumericContent.attachPress(onPress);
		this.oNumericContent.detachPress(onPress);
		// Assert
		assert.strictEqual(oSpy.callCount, 2, "setPointerOnIcon was called.");
		assert.ok(!this.oNumericContent._oIcon.hasStyleClass("sapMPointer"), "sapMPointer class not present");
	});

	QUnit.test("setIcon calls _setPointerOnIcon", function (assert) {
		// Arrange
		var oSpy = sinon.spy(this.oNumericContent, "_setPointerOnIcon");
		// Act
		this.oNumericContent.setIcon();
		// Assert
		assert.strictEqual(oSpy.callCount, 1, "setPointerOnIcon was called.");
	});

	/**
	 * @deprecated Since version 1.38.0.
	 */
	QUnit.test("setIndicator function", function (assert) {
		var fnAssert = function (sExpectedIcon, sExpectedIndicator) {
			assert.strictEqual(this.oNumericContent._oIndicatorIcon.getSrc(), sExpectedIcon, "Indicator icon src should be correct.");
			assert.strictEqual(this.oNumericContent._oIndicatorIcon.getSize(), "0.875rem", "Indicator icon size should be correct.");
			assert.ok(this.oNumericContent._oIndicatorIcon.hasStyleClass("sapMNCIndIcon"), "Indicator icon size should have correct style class.");
			assert.strictEqual(this.oNumericContent.getIndicator(), sExpectedIndicator, "Indicator property should be set correctly.");
		}.bind(this);

		// Act
		this.oNumericContent.setIndicator(DeviationIndicator.Down);
		// Assert
		fnAssert("sap-icon://down", DeviationIndicator.Down);
		// Act
		this.oNumericContent.setIndicator(DeviationIndicator.None);
		// Assert
		fnAssert("sap-icon://none", DeviationIndicator.None);
		// Act
		this.oNumericContent.setIndicator(DeviationIndicator.Up);
		// Assert
		fnAssert("sap-icon://up", DeviationIndicator.Up);
		// Act
		this.oNumericContent.setIndicator();
		// Assert
		fnAssert("sap-icon://none", DeviationIndicator.None);
	});

	QUnit.module("Rendering test - sap.m.NumericContent inside sap.m.GenericTile");

	QUnit.test("Numeric Content inside sap.m.GenericTile rendered.", function (assert) {
		// Arrange
		this.oNumericContent = fnCreateExampleNumericContent();
		this.oGenericTile = new GenericTile("generic-tile", {
			tileContent: [new TileContent({
				content: this.oNumericContent
			})]
		});
		this.oGenericTile.placeAt("qunit-fixture");
		oCore.applyChanges();

		// Act
		this.oNumericContent.setValue("12");
		oCore.applyChanges();

		// Assert
		assert.ok(document.getElementById("generic-tile"), "GenericTile (wrapper of NumericContent) was rendered successfully");
		fnAssertNumericContentHasRendered(assert);

		// Cleanup
		this.oGenericTile.destroy();
		this.oGenericTile = null;
		this.oNumericContent = null;
	});

	QUnit.test("Resize handler is registered in init phase.", function (assert) {
		// Arrange
		var oSpyRegister = sinon.spy(ResizeHandler, "register");
		var oSpyDeregister = sinon.spy(ResizeHandler, "deregister");
		this.oNumericContent = fnCreateExampleNumericContent();
		this.oGenericTile = new GenericTile("generic-tile", {
			tileContent: [new TileContent({
				content: this.oNumericContent
			})]
		});

		// Act
		this.oGenericTile.placeAt("qunit-fixture");
		oCore.applyChanges();

		// Assert
		assert.strictEqual(oSpyRegister.callCount, 2, "ResizeHandler.register was called.");
		this.oGenericTile.destroy();
		assert.strictEqual(oSpyDeregister.callCount, 3, "ResizeHandler.deregister was called.");

		// Cleanup
		this.oGenericTile = null;
		this.oNumericContent = null;
	});

	QUnit.module("Functional tests - sap.m.NumericContent", {
		beforeEach: function () {
			this.oNumericContent = fnCreateExampleNumericContent();
			this.oNumericContent.placeAt("qunit-fixture");
			oCore.applyChanges();
		},
		afterEach: function () {
			this.oNumericContent.destroy();
			this.oNumericContent = null;
		}
	});

	QUnit.test("Test formatter value processing", function (assert) {
		this.oNumericContent.setFormatterValue(false);
		this.oNumericContent.setValue("68Mio.");
		oCore.applyChanges();

		assert.strictEqual(this.oNumericContent.getDomRef("value-inner").textContent, "68Mi", "Value was rendered successfully with formatter switched off");
		assert.strictEqual(this.oNumericContent.getDomRef("scale").textContent, "M", "Scale was rendered successfully with formatter switched off");
		this.oNumericContent.setFormatterValue(true);
		this.oNumericContent.setValue("68 Mio");
		oCore.applyChanges();

		assert.strictEqual(this.oNumericContent.getDomRef("value-inner").textContent, "68", "Value was rendered successfully with formatter switched on");
		assert.strictEqual(this.oNumericContent.getDomRef("scale").textContent, "Mio", "Scale was rendered successfully with formatter switched on");
		this.oNumericContent.setValue(undefined);
		oCore.applyChanges();
		assert.strictEqual(this.oNumericContent.getDomRef("value-inner").textContent, "0", "Value cleaned successfully with formatter switched on");
		assert.strictEqual(this.oNumericContent.getDomRef("scale"), null, "Scale cleaned successfully with formatter switched on");
	});

	QUnit.test("Test processing of formatter value with RTL and LTR mark", function (assert) {
		this.oNumericContent.setFormatterValue(true);
		var sFormattedValue = String.fromCharCode(8206) + String.fromCharCode(8207) + "58,7 Mio";
		this.oNumericContent.setValue(sFormattedValue);
		oCore.applyChanges();

		assert.strictEqual(this.oNumericContent.getDomRef("value-inner").textContent, "58,7", "Value was rendered successfully with formatter switched on");
		assert.strictEqual(this.oNumericContent.getDomRef("scale").textContent, "Mio", "Scale was rendered successfully with formatter switched on");
	});

	QUnit.test("Test nullify parameter", function (assert) {
		assert.strictEqual(this.oNumericContent.getDomRef("value-inner").textContent, "0", "Value was nullified successfully");
		this.oNumericContent.setNullifyValue(false);
		oCore.applyChanges();
		assert.strictEqual(this.oNumericContent.getDomRef("value-inner").textContent, "", "Value was not nullified");
	});

	QUnit.test("Test tooltip text", function (assert) {
		//Arrange
		this.oNumericContent.setTooltip("Test, test");
		//Act
		var sTooltip = this.oNumericContent.getTooltip();
		//Assert
		assert.deepEqual(sTooltip, "Test, test", "Tooltip is a string and it's correct");

		//Act
		sTooltip = this.oNumericContent.getTooltip_AsString();
		//Assert
		assert.deepEqual(sTooltip, "Test, test", "Tooltip is correct");

		//Arrange
		var oTooltip = new TooltipBase({text: "Test, test"});
		this.oNumericContent.setTooltip(oTooltip);
		//Act
		sTooltip = this.oNumericContent.getTooltip();
		//Assert
		assert.notDeepEqual(sTooltip, "Test, test", "Tooltip is not a string");
	});

	QUnit.test("Tests tooltip to check if it includes value color text", function (assert) {
		//Arrange
		var sTooltip = this.oNumericContent.getTooltip_AsString();
		//Act
		var isValueColorPresent = sTooltip.indexOf(oResourceBundle.getText("SEMANTIC_COLOR_" + this.oNumericContent.getValueColor().toUpperCase())) > -1;
		//Assert
		assert.equal(isValueColorPresent, true, "The tooltip contains the value color text");

		//Arrange
		this.oNumericContent.setValueColor(ValueColor.None);
		//Act
		oCore.applyChanges();
		sTooltip = this.oNumericContent.getTooltip_AsString();
		isValueColorPresent = sTooltip.indexOf(ValueColor.None) > -1;

		//Assert
		assert.equal(this.oNumericContent.$("value").hasClass("Neutral"), true, "It contains the Neutral class for value color None");
		assert.equal(isValueColorPresent, false, "The tooltip does not contain the value color text");
	});

	QUnit.test("Test alternative text", function (assert) {
		//Act
		var sAltText = this.oNumericContent.getAltText();
		//Assert
		assert.strictEqual(sAltText, "0\nAscending\nGood", "Alternative text is correct");

		//Arrange
		this.oNumericContent.setIconDescription("Icon description");
		//Act
		sAltText = this.oNumericContent.getAltText();
		//Assert
		assert.strictEqual(sAltText, "Icon description\n0\nAscending\nGood", "Alternative text is correct with icon description");

		//Arrange
		this.oNumericContent.setNullifyValue(false);
		//Act
		sAltText = this.oNumericContent.getAltText();
		//Assert
		assert.strictEqual(sAltText, "Icon description\n\nAscending\nGood", "Alternative text is correct with nullify value set to false");

		//Arrange
		this.oNumericContent.setNullifyValue(true);
		//Act
		this.oNumericContent.setValue("10");
		this.oNumericContent.setScale("$");
		sAltText = this.oNumericContent.getAltText();
		//Assert
		assert.strictEqual(this.oNumericContent.getAltText(), "Icon description\n10$\nAscending\nGood", "Alternative text is correct with a value and scale set up");
	});

	QUnit.test("Test _getMaxDigitsData language", function (assert) {
		// Arrange 1
		var sOrigLang = oCore.getConfiguration().getLanguage();
		var oExpected = {fontClass: "sapMNCLargeFontSize", maxLength: 4};
		oCore.getConfiguration().setLanguage("en_US");

		// Act 1
		var oMaxDigitsData = this.oNumericContent._getMaxDigitsData();

		// Assert 1
		assert.deepEqual(oMaxDigitsData, oExpected, "Max digits data should be correct with normal language casing.");

		// Arrange 2
		oCore.getConfiguration().setLanguage("EN_US");

		// Act 2
		oMaxDigitsData = this.oNumericContent._getMaxDigitsData();

		// Assert 2
		assert.deepEqual(oMaxDigitsData, oExpected, "Max digits data should be correct with uppercase language casing.");

		// Arrange 3
		oCore.getConfiguration().setLanguage("en_us");

		// Act 3
		oMaxDigitsData = this.oNumericContent._getMaxDigitsData();

		// Assert 3
		assert.deepEqual(oMaxDigitsData, oExpected, "Max digits data should be correct with lowercase language casing.");

		// Arrange 4
		oCore.getConfiguration().setLanguage("en-US-x-sappsd");

		// Act 4
		oMaxDigitsData = this.oNumericContent._getMaxDigitsData();

		// Assert 4
		assert.deepEqual(oMaxDigitsData, oExpected, "Max digits data should be correct for a language which is not defined in the language map.");

		// Arrange 5
		oCore.getConfiguration().setLanguage("de");

		// Act 5
		oMaxDigitsData = this.oNumericContent._getMaxDigitsData();

		// Assert 5
		assert.deepEqual(oMaxDigitsData, {fontClass: "sapMNCSmallFontSize", maxLength: 8}, "Max digits data should be correct for de language.");

		// Restore
		oCore.getConfiguration().setLanguage(sOrigLang);
	});

	QUnit.module("Property withoutMargin", {
		beforeEach: function () {
			this.oNumericContent = new NumericContent({
				scale: "Mrd",
				indicator: DeviationIndicator.Up,
				value: "699"
			}).placeAt("qunit-fixture");
			oCore.applyChanges();
		},
		afterEach: function () {
			this.oNumericContent.destroy();
			this.oNumericContent = null;
		}
	});

	QUnit.test("Check default value", function (assert) {
		assert.ok(this.oNumericContent.getWithMargin(), "Default value shall be 'false'.");
	});

	QUnit.test("CSS Class needs to be added if withoutMargin is set to true", function (assert) {
		assert.ok(!this.oNumericContent.$().hasClass("WithoutMargin"));
		this.oNumericContent.setWithMargin(false);
		oCore.applyChanges();
		assert.ok(this.oNumericContent.$().hasClass("WithoutMargin"), "'withoutMargin' CSS class expected.");
		assert.ok(jQuery(this.oNumericContent.$().children()[0]).hasClass("WithoutMargin"), "'withoutMargin' CSS class expected within the inner div container.");
		assert.ok(this.oNumericContent.$("value").hasClass("WithoutMargin"), "'withoutMargin' CSS class expected within the parent value container.");
		assert.strictEqual(this.oNumericContent.$("value").css("justify-content"), "flex-start", "'flex-start' CSS style expected within the parent value container.");
		assert.ok(this.oNumericContent.$().find(".sapMNCIndScale").hasClass("WithoutMargin"), "'withoutMargin' CSS class expected within the indicator and scale container.");
	});

	QUnit.module("Events test", {
		beforeEach: function () {
			this.oNumericContent = fnCreateExampleNumericContent();
			this.oNumericContent.placeAt("qunit-fixture");
			oCore.applyChanges();
		},
		afterEach: function () {
			this.oNumericContent.destroy();
			this.oNumericContent = null;
		}
	});

	QUnit.test("Attach events", function (assert) {
		//Arrange
		//Act
		var oNumericContent = this.oNumericContent.attachEvent("hover", fnHoverHandler, this.oNumericContent);
		//Assert
		assert.deepEqual(oNumericContent, this.oNumericContent, "NumericContent returned is equal to initial one");
		assert.strictEqual(hasAttribute("tabindex", this.oNumericContent), false, "Attribute has not been added successfully since press handler was not available");
		assert.strictEqual(this.oNumericContent.$().hasClass("sapMPointer"), false, "Class has not been added successfully since press handler was not available");

		//Arrange
		//Act
		oNumericContent = this.oNumericContent.attachEvent("press", fnPressHandler, this.oNumericContent);
		//Assert
		assert.ok(hasAttribute("tabindex", this.oNumericContent), "Attribute has been added successfully since press handler was available");
		assert.ok(this.oNumericContent.$().hasClass("sapMPointer"), "Class has been added successfully since press handler was available");
	});

	QUnit.test("Detach events.", function (assert) {
		//Arrange
		//Act
		var oNumericContent = this.oNumericContent.detachEvent("press", fnPressHandler, this.oNumericContent);
		//Assert
		assert.deepEqual(oNumericContent, this.oNumericContent, "NumericContentreturned is equal to initial one");
		assert.strictEqual(hasAttribute("tabindex", this.oNumericContent), false, "Attribute not available since press was not defined");
		assert.strictEqual(this.oNumericContent.$().hasClass("sapMPointer"), false, "Class not available since press was not defined");

		//Arrange
		oNumericContent = this.oNumericContent.attachEvent("press", fnPressHandler, this.oNumericContent);
		oNumericContent = this.oNumericContent.attachEvent("hover", fnHoverHandler, this.oNumericContent);
		//Act
		oNumericContent = this.oNumericContent.detachEvent("hover", fnHoverHandler, this.oNumericContent);
		//Assert
		assert.ok(hasAttribute("tabindex", this.oNumericContent), "Attribute still available since hover was unregistered (not press)");
		assert.ok(this.oNumericContent.$().hasClass("sapMPointer"), "Class still available since hover was unregistered (not press)");

		//Arrange
		//Act
		oNumericContent = this.oNumericContent.detachEvent("press", fnPressHandler, this.oNumericContent);
		//Assert
		assert.strictEqual(hasAttribute("tabindex", this.oNumericContent), false, "Attribute has been removed successfully");
		assert.strictEqual(this.oNumericContent.$().hasClass("sapMPointer"), false, "Class has been removed successfully");
	});

	QUnit.module("Adaptive font size", {
		beforeEach: function () {
			this.oNumericContent = new NumericContent("numeric-cnt", {
				indicator: DeviationIndicator.Up,
				value: "12345678",
				animateTextChange: false,
				icon:  "sap-icon://line-charts"
			}).placeAt("qunit-fixture");
			oCore.applyChanges();
		},
		afterEach: function () {
			this.oNumericContent.destroy();
			this.oNumericContent = null;
		},
		fnAssertFontSizeClassesForLanguage: function (assert, sExpectedFontSizeClass, sCurrentLanguageCode, sWhenCondition, sWhenValue, bNegativeAssert) {
			sWhenCondition = sWhenCondition || "When the language is set to";
			sWhenValue = sWhenValue || sCurrentLanguageCode;
			var sWhenMessagePart = sWhenCondition + " '" + sWhenValue + "' ",
				sOptionalNot = bNegativeAssert ? "NOT" : "",
				fnAssert = bNegativeAssert ? assert.notOk.bind(assert) : assert.ok.bind(assert);

			fnAssert(
				this.oNumericContent.$("icon-image").hasClass(sExpectedFontSizeClass),
				sWhenMessagePart + "the icon image should " + sOptionalNot + " have class " + sExpectedFontSizeClass + "."
			);
			fnAssert(
				this.oNumericContent.$("value-inner").hasClass(sExpectedFontSizeClass),
				sWhenMessagePart + "the inner value should " + sOptionalNot + " have class " + sExpectedFontSizeClass + "."
			);
			fnAssert(
				this.oNumericContent.$("indicator").hasClass(sExpectedFontSizeClass),
				sWhenMessagePart + "the indicator should " + sOptionalNot + " have class " + sExpectedFontSizeClass + "."
			);
		}
	});

	QUnit.test("Test the adaptive font size change based on language - small", function (assert) {
		// Arrange
		var sDefaultLanguage = oCore.getConfiguration().getLanguage(),
			sNewLanguage = "de";
		oCore.getConfiguration().setLanguage(sNewLanguage);
		this.oNumericContent.invalidate();
		oCore.applyChanges();
		// Assert
		this.fnAssertFontSizeClassesForLanguage(assert, "sapMNCSmallFontSize", sNewLanguage);
		// Arrange
		sNewLanguage = "de-de";
		oCore.getConfiguration().setLanguage(sNewLanguage);
		this.oNumericContent.invalidate();
		oCore.applyChanges();
		// Assert
		this.fnAssertFontSizeClassesForLanguage(assert, "sapMNCSmallFontSize", sNewLanguage);
		// Arrange
		this.oNumericContent.setAdaptiveFontSize(false);
		this.oNumericContent.invalidate();
		oCore.applyChanges();
		// Assert
		this.fnAssertFontSizeClassesForLanguage(assert, "sapMNCLargeFontSize", sNewLanguage);
		oCore.getConfiguration().setLanguage(sDefaultLanguage);
	});

	QUnit.test("Test the adaptive font size change based on language - medium", function (assert) {
		// Arrange
		var sDefaultLanguage = oCore.getConfiguration().getLanguage(),
			sNewLanguage = "es";
		oCore.getConfiguration().setLanguage(sNewLanguage);
		this.oNumericContent.invalidate();
		oCore.applyChanges();
		// Assert
		this.fnAssertFontSizeClassesForLanguage(assert, "sapMNCMediumFontSize", sNewLanguage);
		// Arrange
		this.oNumericContent.setAdaptiveFontSize(false);
		this.oNumericContent.invalidate();
		oCore.applyChanges();
		// Assert
		this.fnAssertFontSizeClassesForLanguage(assert, "sapMNCLargeFontSize", sNewLanguage);
		this.oNumericContent.setAdaptiveFontSize(true);
		oCore.getConfiguration().setLanguage(sDefaultLanguage);
	});

	QUnit.test("Test the adaptive font size change based on language - large", function (assert) {
		// Arrange
		var sDefaultLanguage = oCore.getConfiguration().getLanguage(),
			sNewLanguage = "bg";
		oCore.getConfiguration().setLanguage(sNewLanguage);
		this.oNumericContent.invalidate();
		oCore.applyChanges();
		// Assert
		this.fnAssertFontSizeClassesForLanguage(assert, "sapMNCLargeFontSize", sNewLanguage);
		// Arrange
		this.oNumericContent.setAdaptiveFontSize(false);
		this.oNumericContent.invalidate();
		oCore.applyChanges();
		// Assert
		this.fnAssertFontSizeClassesForLanguage(assert, "sapMNCLargeFontSize", sNewLanguage);
		this.oNumericContent.setAdaptiveFontSize(true);
		oCore.getConfiguration().setLanguage(sDefaultLanguage);
	});

	QUnit.test("Test the adaptive font size change based on language - adaptiveFontSize: false", function (assert) {
		// Arrange
		this.oNumericContent.setAdaptiveFontSize(false);

		// Assert
		this.fnAssertFontSizeClassesForLanguage(assert, "sapMNCLargeFontSize", null, "When adaptiveFontSize is set to", "false");
		this.fnAssertFontSizeClassesForLanguage(assert, "sapMNCSmallFontSize", null, "When adaptiveFontSize is set to", "false", true);
		this.fnAssertFontSizeClassesForLanguage(assert, "sapMNCMediumFontSize", null, "When adaptiveFontSize is set to", "false", true);

		this.oNumericContent.setAdaptiveFontSize(true);
	});

	QUnit.module("Truncate value to", {
		beforeEach: function () {
			this.oNumericContent = new NumericContent("numeric-cnt", {
				value: "12345678123456781234567812345678",
				animateTextChange: false
			}).placeAt("qunit-fixture");
			oCore.applyChanges();
		},
		afterEach: function () {
			this.oNumericContent.destroy();
			this.oNumericContent = null;
		}
	});

	QUnit.test("Test custom truncateValueTo property", function(assert) {
		// Arrange
		this.oNumericContent.setTruncateValueTo(1);
		oCore.applyChanges();

		// Assert
		assert.strictEqual(this.oNumericContent.$("value-inner").html().length, 1, "Value is truncated to 1 char");

		// Arrange
		this.oNumericContent.setTruncateValueTo(20);
		oCore.applyChanges();

		// Assert
		assert.strictEqual(this.oNumericContent.$("value-inner").html().length, 20, "Value is truncated to 20 chars");
	});

	QUnit.test("Test default value when adaptiveFontSize=false", function(assert) {
		// Arrange
		this.oNumericContent.setAdaptiveFontSize(false);
		oCore.applyChanges();

		// Assert
		assert.strictEqual(this.oNumericContent.$("value-inner").html().length, 4, "Value is truncated to 4 chars");
	});

	QUnit.test("Test default value for specific language", function(assert) {
		// Arrange
		var sDefaultLanguage = oCore.getConfiguration().getLanguage();
		oCore.getConfiguration().setLanguage("de");
		this.oNumericContent.invalidate();
		oCore.applyChanges();

		// Assert
		assert.strictEqual(this.oNumericContent.$("value-inner").html().length, 8, "Value is truncated to 8 chars for 'de'");

		// Arrange
		oCore.getConfiguration().setLanguage("es");
		this.oNumericContent.invalidate();
		oCore.applyChanges();

		// Assert
		assert.strictEqual(this.oNumericContent.$("value-inner").html().length, 6, "Value is truncated to 6 chars for 'es'");

		// Arrange
		oCore.getConfiguration().setLanguage("en");
		this.oNumericContent.invalidate();
		oCore.applyChanges();

		// Assert
		assert.strictEqual(this.oNumericContent.$("value-inner").html().length, 4, "Value is truncated to 4 chars for 'en'");

		// return the language
		oCore.getConfiguration().setLanguage(sDefaultLanguage);
	});

	/* --- Helpers --- */

	function fnAssertNumericContentHasRendered (assert) {
		assert.ok(document.getElementById("numeric-cnt"), "NumericContent was rendered successfully");
		assert.ok(document.getElementById("numeric-cnt-icon-image"), "Icon was rendered successfully");
		assert.ok(document.getElementById("numeric-cnt-value"), "Value was rendered successfully");
		assert.ok(document.getElementById("numeric-cnt-value-inner"), "Inner value was rendered successfully");
		assert.ok(document.getElementById("numeric-cnt-indicator"), "Indicator was rendered successfully");
		assert.ok(document.getElementById("numeric-cnt-icon-indicator"), "Icon indicator was rendered successfully");
		assert.ok(document.getElementById("numeric-cnt-scale"), "Scale was rendered successfully");
	}

	function fnCreateExampleNumericContent () {
		return new NumericContent("numeric-cnt", {
			size: Size.L, // deprecated since 1.38
			state: LoadState.Loaded,
			scale: "M",
			indicator: DeviationIndicator.Up,
			nullifyValue: true,
			formatterValue: false,
			valueColor: ValueColor.Good,
			icon: "sap-icon://customer-financial-fact-sheet"
		});
	}

	function fnHoverHandler () {
	}

	function fnPressHandler () {
	}

	function hasAttribute (sAttribute, oCurrentObject) {
		var sAttributeValue = oCurrentObject.$().attr(sAttribute);
		return typeof sAttributeValue !== typeof undefined && sAttributeValue !== false;
	}

});


text:
export LOGS_FILE="$RUNTIME_DIR/logs/$SERVICE_NAME.log"
export SCRIPTS_DIR="$SCRIPTS_DIR"

## Write logs of this script to component specific file
exec &> >(tee -a "$LOGS_FILE")

__validate_service_configs() {
  __process_msg "Service $SERVICE_NAME configuration"
  __process_msg "SERVICE: $SERVICE_NAME"
  __process_msg "SERVICE_IMAGE: $SERVICE_IMAGE"
  __process_msg "ACCESS_KEY: ${#ACCESS_KEY}"
  __process_msg "SECRET_KEY: ${#SECRET_KEY}"
  __process_msg "SCRIPTS_DIR: $SCRIPTS_DIR"
  __process_msg "LOGS_FILE:$LOGS_FILE"
}

__cleanup_containers() {
  __process_msg "Stopping stale container for the service"
  sudo docker rm -f $SERVICE_NAME || true
}

__cleanup_service() {
  __process_msg "Removing stale service definitions"
  sudo docker service rm $SERVICE_NAME || true
}

__run_service() {
  __process_msg "Running service: $SERVICE_NAME"
  local run_output=$($RUN_COMMAND)
  __process_msg "Docker run returned: $run_output"
}

main() {
  if [ -z "$SERVICE_NAME" ] || [ "$SERVICE_NAME" == "" ]; then
    __process_error "'SERVICE_NAME' env not present, exiting"
    exit 1
  else
    __process_marker "Booting service: $SERVICE_NAME"
    __validate_service_configs
    __cleanup_containers
    __cleanup_service
    __run_service
  fi
}

main

redpajama_set_name: RedPajamaGithub


text:
'use strict'

const Packet = require('../packet')
const Events = require('../events/node')
const util = require('util')

class CallbackWrapper {
  /**
   *
   * Generic Callback wrapper
   *
   * Will collect the arguments and pass them on to the next node
   *
   * So technically the next node is the callback.
   *
   * Parameters are defined on the output as ports.
   *
   * Each callback argument must be defined as output port
   * in the callee's schema
   *
   * e.g.
   *
   *  node style callback:
   *
   *  ports.output: { err: ..., result: ... }
   *
   *  connect style callback:
   *
   *  ports.output: { req: ..., res: ..., next: ... }
   *
   * The order of appearance of arguments must match those of the ports within
   * the json schema.
   *
   * TODO: Within the schema you must define the correct type otherwise output
   * will be refused
   *
   *
   * @private
   */
  // PUT THIS INTO A DIFFERENT NODE TYPE, SEPERATE THE DIFFERENT FLAVOURS
  _callbackWrapper () {
    const obj = {}
    const ports = this.outPorts

    for (let i = 0; i < arguments.length; i++) {
      if (!ports[i]) {
        this.event(Events.ERROR, {
          msg: Error(
            util.format('Unexpected extra port of type %s',
              typeof arguments[i] === 'object' ? arguments[i].constructor.name : typeof arguments[i]
            )
          )
        })
      } else {
        obj[ports[i]] = Packet.create(arguments[i])
      }
    }
    this._output(obj)
  }
}

module.exports = CallbackWrapper


text:
from xrayvision import global_segment, get_trace_info, parse_trace_info

class XRayMiddleware(object):
    '''Wrap a WSGI app to provide Xray stats'''

    def __init__(self, app, name=None, prefer_lambda_trace=False):
        self.app = app
        self.name = name
        self.prefer_lambda_trace = prefer_lambda_trace

    def __call__(self, environ, start_response):
        '''Call the app handler'''

        trace_id = environ.get('HTTP_X_AMZN_TRACE_ID')
        trace_root = None
        trace_parent = None
        sampled = None

        # in lambda, this will be sourced from the environment
        if self.prefer_lambda_trace:
            trace_root, trace_parent, sampled = get_trace_info()

        if not trace_root:
            trace_root, trace_parent, sampled = parse_trace_info(trace_id)

        name = (self.name or environ.get('SCRIPT_NAME')
                or environ.get('SERVER_SOFTWARE') or 'wsgi')

        trace = global_segment.begin(name, trace_root, trace_parent)

        if sampled == '1':
            trace.sampled = True
        elif sampled == '0':
            trace.sampled = False

        url = '{0}://{1}{2}'.format(environ['wsgi.url_scheme'],
                                    environ['HTTP_HOST'],
                                    environ['PATH_INFO'])

        if environ.get('QUERY_STRING'):
            url += '?' + environ['QUERY_STRING']

        http = {
            'request': {
                'method': environ['REQUEST_METHOD'],
                'url': url,
                'user_agent': environ['HTTP_USER_AGENT'],
                'client_ip': environ['REMOTE_ADDR']
            }
        }

        trace.http = http

        # record header stuff in metadata
        for name, value in environ.items():
            if name.startswith('HTTP_'):
                trace.add_metadata(name, value)

        trace.add_annotation('server_protocol', environ['SERVER_PROTOCOL'])

        # helper to capture response information
        def _start_response(status, headers):
            http.setdefault('response', {})
            response = http['response']

            response['status'] = int(status.split()[0])
            hdict = {x[0]: x[1] for x in headers}
            if 'Content-Length' in hdict:
                response['content_length'] = int(hdict['Content-Length'])

            return start_response(status, headers)

        if environ.get('HTTP_X_FORWARDED_FOR'):
            http['request']['x_forwarded_for'] = environ['HTTP_X_FORWARDED_FOR']

        try:
            app_iter = self.app(environ, _start_response)
            for item in app_iter:
                yield item

            status = http.get('response', {}).get('status', 0)
            trace.add_http_status(status)

        except:
            trace.add_exception()
            raise

        finally:
            trace.close()

        if hasattr(app_iter, 'close'):
            app_iter.close()


text:
package org.spdx.rdfparser.model;

import java.util.List;
import java.util.regex.Matcher;

import org.spdx.rdfparser.IModelContainer;
import org.spdx.rdfparser.InvalidSPDXAnalysisException;
import org.spdx.rdfparser.SpdxRdfConstants;

import com.google.common.base.Objects;
import com.google.common.collect.Lists;

/**
 * This is an SPDX element which is in an external document.
 *
 * The only fields required to be valid are the id and externalDocumentId.
 *
 * @author Gary O'Neall
 *
 */
public class ExternalSpdxElement extends SpdxElement {

	/**
	 * @param id SPDX ID used for referencing this external element.  Format ExternalSPDXRef:SPDXID
	 * @throws InvalidSPDXAnalysisException
	 *
	 */
	public ExternalSpdxElement(String id) throws InvalidSPDXAnalysisException {
		super(null, null, null, null);
		if (!SpdxRdfConstants.EXTERNAL_ELEMENT_REF_PATTERN.matcher(id).matches()) {
			throw(new InvalidSPDXAnalysisException("Invalid id format for an external document reference.  Must be of the form ExternalSPDXRef:SPDXID"));
		}
		this.setId(id);
	}

	@Override
	public void setId(String id) throws InvalidSPDXAnalysisException {
		if (id != null && !SpdxRdfConstants.EXTERNAL_ELEMENT_REF_PATTERN.matcher(id).matches()) {
			throw(new InvalidSPDXAnalysisException("Invalid id format for an external document reference.  Must be of the form ExternalSPDXRef:SPDXID"));
		}
		super.setId(id);
	}

	/**
	 * @return external document ID for the external reference
	 * @throws InvalidSPDXAnalysisException
	 */
	public String getExternalDocumentId() throws InvalidSPDXAnalysisException {
		Matcher matcher = SpdxRdfConstants.EXTERNAL_ELEMENT_REF_PATTERN.matcher(this.getId());
		if (!matcher.matches()) {
			throw(new InvalidSPDXAnalysisException("Invalid id format for an external document reference.  Must be of the form ExternalSPDXRef:SPDXID"));
		}
		return matcher.group(1);
	}

	/**
	 * @return element ID used in the external document
	 * @throws InvalidSPDXAnalysisException
	 */
	public String getExternalElementId() throws InvalidSPDXAnalysisException {
		Matcher matcher = SpdxRdfConstants.EXTERNAL_ELEMENT_REF_PATTERN.matcher(this.getId());
		if (!matcher.matches()) {
			throw(new InvalidSPDXAnalysisException("Invalid id format for an external document reference.  Must be of the form ExternalSPDXRef:SPDXID"));
		}
		return matcher.group(2);
	}

	@Override
    public String getUri(IModelContainer modelContainer) throws InvalidSPDXAnalysisException {
		Matcher matcher = SpdxRdfConstants.EXTERNAL_ELEMENT_REF_PATTERN.matcher(this.getId());
		if (!matcher.matches()) {
			throw(new InvalidSPDXAnalysisException("Invalid id format for an external document reference.  Must be of the form ExternalSPDXRef:SPDXID"));
		}
		String externalDocumentUri = modelContainer.externalDocumentIdToNamespace(matcher.group(1));
		if (externalDocumentUri == null) {
			throw(new InvalidSPDXAnalysisException("No external document reference exists for document ID "+matcher.group(1)));
		}
		return externalDocumentUri + "#" + matcher.group(2);
	}

	@Override
	public boolean equivalent(IRdfModel o) {
		return this.equivalent(o, true);
	}

	@Override
	public boolean equivalent(IRdfModel o, boolean testRelationships) {
		if (o == this) {
			return true;
		}
		if (!(o instanceof ExternalSpdxElement)) {
			return false;
		}
		ExternalSpdxElement comp = (ExternalSpdxElement)o;
		if (!super.equivalent(comp, testRelationships)) {
			return false;
		}
        return (Objects.equal(this.getId(), comp.getId()));
	}

	@Override
	public ExternalSpdxElement clone() {
		try {
			return new ExternalSpdxElement(this.getId());
		} catch (InvalidSPDXAnalysisException e) {
			throw new AssertionError("Clone should never cause an Invalid SPDX Exception",e);
		}
	}

	@Override
	public List<String> verify() {
		// we don't want to call super.verify since we really don't require those fields
		List<String> retval = Lists.newArrayList();
		String id = this.getId();
		if (!SpdxRdfConstants.EXTERNAL_ELEMENT_REF_PATTERN.matcher(id).matches()) {
			retval.add("Invalid id format for an external document reference.  Must be of the form ExternalSPDXRef:SPDXID");
		}
		return retval;
	}

	/* (non-Javadoc)
	 * @see org.spdx.rdfparser.model.RdfModelObject#getPropertiesFromModel()
	 */
	@Override
	public void getPropertiesFromModel() throws InvalidSPDXAnalysisException {
		// Do nothing
	}

	/* (non-Javadoc)
	 * @see org.spdx.rdfparser.model.RdfModelObject#populateModel()
	 */
	@Override
	public void populateModel() throws InvalidSPDXAnalysisException {
		// Do nothing
	}
}


text:
'use strict';

angular.
  module('phonecatApp').
  config(['$locationProvider' ,'$routeProvider',
    function config($locationProvider, $routeProvider) {
      $locationProvider.hashPrefix('!');

      $routeProvider.
        when('/phones', {
          template: '<phone-list></phone-list>'
        }).
        when('/phones/:phoneId', {
          template: '<phone-detail></phone-detail>'
        }).when('/login', {
        template: '<login></login>'
        }).otherwise('/phones');

    }
  ]);


text:
\hypertarget{enumvalues__3_8js}{}\section{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/search/enumvalues\+\_\+3.js File Reference}
\label{enumvalues__3_8js}\index{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/search/enumvalues\+\_\+3.\+js@{/home/bhargavi/\+Documents/\+S\+D\+R/\+Copy\+\_\+\+Exam\+\_\+808\+X/docs/html/search/enumvalues\+\_\+3.\+js}}
\subsection*{Variables}
\begin{DoxyCompactItemize}
\item
var \hyperlink{enumvalues__3_8js_ad01a7523f103d6242ef9b0451861231e}{search\+Data}
\end{DoxyCompactItemize}

\subsection{Variable Documentation}
\index{enumvalues\+\_\+3.\+js@{enumvalues\+\_\+3.\+js}!search\+Data@{search\+Data}}
\index{search\+Data@{search\+Data}!enumvalues\+\_\+3.\+js@{enumvalues\+\_\+3.\+js}}
\subsubsection[{\texorpdfstring{search\+Data}{searchData}}]{\setlength{\rightskip}{0pt plus 5cm}var search\+Data}\hypertarget{enumvalues__3_8js_ad01a7523f103d6242ef9b0451861231e}{}\label{enumvalues__3_8js_ad01a7523f103d6242ef9b0451861231e}
{\bfseries Initial value\+:}
\begin{DoxyCode}
=
[
  [\textcolor{stringliteral}{'honor\_5fsharding\_5fprotocol'},[\textcolor{stringliteral}{'HONOR\_SHARDING\_PROTOCOL'},[\textcolor{stringliteral}{'
      ../classtesting\_1\_1internal\_1\_1\_unit\_test\_impl.html#acc5ffd3f9bc2e87bb3dba4218f58af43abec11f1c4bb8a3e2b99fa8328bccd58c'},1,\textcolor{stringliteral}{'
      testing::internal::UnitTestImpl'}]]]
]
\end{DoxyCode}

Definition at line 1 of file enumvalues\+\_\+3.\+js.


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Flora, Jena 45: 322 (1863)

#### Original name
Sphaeria dacrymycella Nyl., 1863

### Remarks
null


text:
package io.github.ineedcode.Producer;

import org.apache.kafka.clients.producer.*;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class KafkaProNewApi {

    public static void send() throws InterruptedException {
        Properties props = new Properties();
        props.put("bootstrap.servers", "kafka-1:9092");
        props.put("acks", "all");
        props.put("retries", 0);
        props.put("batch.size", 16384);
        props.put("linger.ms", 1);
        props.put("buffer.memory", 33554432);
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer<>(props);
        String data="{taskId: 164,tokenArray: [" +
                "\"308187f0904411e6830419bbff96e759\",\"dsarewfafas\",\"3erdasd\"]" +
                "}";
        ProducerRecord<String,String> record = new ProducerRecord<>("akhlaq","1", data);
            producer.send(record,
                    (metadata, e) -> {
                        if(e != null){
                            e.printStackTrace();
                        }
                        System.out.println("The offset of the record we just sent is: " + metadata.offset());
                    });
            TimeUnit.SECONDS.sleep(1);
//            producer.send(new ProducerRecord<>("bar", Integer.toString(i), Integer.toString(i)));
        producer.close();

    }

    public static void main(String[] args) throws InterruptedException {
        send();
    }
}


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

namespace EnormousInput {
    class Program {
        const int size = 1 << 20;
        static void Main (string[] args) {
            int n, k;
            int counter = 0;
            using (var stream = Console.OpenStandardInput()) {
                byte[] buffer = new byte[size];
                int bytesRead = stream.Read(buffer, 0, size);
                string convertedBytes = Encoding.ASCII.GetString(buffer);
                string[] splitStringArray = convertedBytes.Split(new char[] { '\n' });
                string[] firstLine = splitStringArray[0].Split(new char[] { ' ' });
                n = Convert.ToInt32(firstLine[0]);
                k = Convert.ToInt32(firstLine[1]);
                int length = splitStringArray.Length;
                for (int i = 1; i < length; i++) {
                    if (Convert.ToInt32((splitStringArray[i])) % k == 0)
                        counter++;
                }
                Console.WriteLine(counter);
            }
            //    string input = Console.ReadLine();
            //string[] inputArray = input.Split(new char[] { ' ' });
            //n = Convert.ToInt32(inputArray[0]);
            //k = Convert.ToInt32(inputArray[1]);
            //int temp;
            //int counter = 0;
            //for (int i = 0; i < n; i++) {
            //    temp = Convert.ToInt32(Console.ReadLine());
            //    if (temp % k == 0)
            //        counter++;
            //}
            //Console.WriteLine(counter);

        }

        //static Stream ReadStream;
        //static int Idx, Size, BytesRead;
        //static byte[] Buffer = new byte[Size];

        //[MethodImpl(MethodImplOptions.AggressiveInlining)]
        //public static void Initialze () {
        //    ReadStream = Console.OpenStandardInput();
        //    Idx = BytesRead = 0;
        //    Size = 1 << 17;
        //    Buffer = new byte[Size];
        //}
        //[MethodImpl(MethodImplOptions.AggressiveInlining)]
        //public static int ReadInt () {
        //    byte _ReadByte;
        //    //For trimming
        //    do {
        //        _ReadByte = ReadByte();
        //    }
        //    while (_ReadByte < '-');
        //    bool neg = false;
        //    //Checking sign of number
        //    if (_ReadByte == '-') {
        //        neg = true;
        //        _ReadByte = ReadByte();
        //    }
        //    int m = _ReadByte - '0';
        //    while (true) {
        //        _ReadByte = ReadByte();
        //        if (_ReadByte < '0') break;
        //        m = m * 10 + (_ReadByte - '0');
        //    }
        //    if (neg) return -m;
        //    return m;
        //}
        //[MethodImpl(MethodImplOptions.AggressiveInlining)]
        //private static void ReadConsoleInput () {
        //    Idx = 0;
        //    BytesRead = ReadStream.Read(Buffer, 0, Size);
        //    if (BytesRead <= 0) Buffer[0] = 32;
        //}

        //[MethodImpl(MethodImplOptions.AggressiveInlining)]
        //private static byte ReadByte () {
        //    if (Idx == BytesRead) ReadConsoleInput();
        //    return Buffer[Idx++];
        //}

        //[MethodImpl(MethodImplOptions.AggressiveInlining)]
        //public static void Dispose () {
        //    ReadStream.Close();
        //}
        //static void Main (string[] args) {
        //    Initialze();
        //    int n, d, m, count = 0;
        //    m = ReadInt();
        //    d = ReadInt();
        //    while (m-- > 0) {
        //        n = ReadInt();
        //        if (n % d == 0)
        //            count++;
        //    }
        //    Dispose();
        //    Console.WriteLine(count);
        //}
    }
}


text: hack/concat-kubernetes-manifests.sh example/rbac/prometheus-operator/*.yaml > bundle.yaml


text:
module ActiveModel
  class Parameters < HashWithIndifferentAccess
    class Default < self

    end
  end
end


text:
The Redux Resource ecosystem provides bits of code that make working with the library even better.

* [Redux Resource Action Creators](redux-resource-action-creators.md)
* [Redux Resource XHR](redux-resource-xhr.md)
* [Redux Resource Plugins](redux-resource-plugins.md)
* [Redux Resource Prop Types](redux-resource-prop-types.md)


text:
function capture(arr) {
  return (_, v) => {
    arr.push(v)
    return { value: null }
  }
}

function defer() {
  let resolve
  let reject

  const promise = new Promise((resolveFn, rejectFn) => {
    resolve = resolveFn
    reject = rejectFn
  })

  return {
    resolve,
    reject,
    promise
  }
}

export { capture, defer }


text:
<?php

namespace WebNavigator;

use Facebook\WebDriver\Exception;
use Facebook\WebDriver\Exception\NoSuchElementException;
use Facebook\WebDriver\JavaScriptExecutor;
use Facebook\WebDriver\WebDriver;
use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\WebDriverDimension;
use Facebook\WebDriver\WebDriverElement;
use Facebook\WebDriver\WebDriverExpectedCondition;
use Facebook\WebDriver\WebDriverKeys;
use Facebook\WebDriver\WebDriverPoint;
use Facebook\WebDriver\WebDriverSelect;

class Navigator {

    /** @var WebDriver|JavaScriptExecutor */
    private $_webDriver;

    /** @var string */
    private $_baseUrl;

    /** @var string|null */
    private $_locatorPrefix;

    /** @var Options */
    private $_options;

    /**
     * @param WebDriver  $driver
     * @param string     $baseUrl
     * @param array|null $options
     */
    public function __construct(WebDriver $driver, $baseUrl, array $options = null) {
        $this->_webDriver = $driver;
        $this->_baseUrl = (string) $baseUrl;
        $this->_options = new Options($options);

        $this->setWindowSize($this->_options->getWindowSize());
    }

    /**
     * @return WebDriver
     */
    public function getWebDriver() {
        return $this->_webDriver;
    }

    public function quit() {
        $this->_webDriver->quit();
    }

    /**
     * @param string        $locatorPrefix
     * @param callable|null $block fn(Navigator)
     */
    public function scope($locatorPrefix, callable $block = null) {
        $locatorPrefix = (string) $locatorPrefix;
        if (null === $block) {
            $this->_locatorPrefix = $locatorPrefix;
        } else {
            $navigator = clone $this;
            $navigator->scope($locatorPrefix);
            $block($navigator);
        }
    }

    /**
     * @return string|null
     */
    public function getLocatorPrefix() {
        return $this->_locatorPrefix;
    }

    /**
     * @param WebDriverDimension  $windowSize
     * @param WebDriverPoint|null $position
     */
    public function setWindowSize(WebDriverDimension $windowSize, WebDriverPoint $position=null) {
        if(null == $position) {
            $position = new WebDriverPoint(0, 0);
        }
        $this->_webDriver->manage()->window()->setSize($windowSize);
        $this->_webDriver->manage()->window()->setPosition($position);
    }

    /**
     * @param string $path
     */
    public function get($path) {
        $url = $this->_baseUrl . $path;
        $this->_webDriver->get($url);
    }

    /**
     * @param string $locator
     */
    public function click($locator) {
        $this->_findElement($locator)->click();
    }

    /**
     * @param string $locator
     */
    public function sendReturn($locator) {
        $this->_findElement($locator)->sendKeys(WebDriverKeys::RETURN_KEY);
    }

    /**
     * @param string   $locator
     * @param int|null $timeout
     */
    public function waitForElement($locator, $timeout = null) {
        $this->_waitUntil(WebDriverExpectedCondition::presenceOfElementLocated($this->_getLocator($locator)), $timeout);
    }

    /**
     * @param string   $javascript
     * @param int|null $timeout
     */
    public function waitForJs($javascript, $timeout = null) {
        $this->_waitUntil(function (JavaScriptExecutor $driver) use ($javascript) {
            return $driver->executeScript($javascript);
        }, $timeout);
    }

    /**
     * @param int|null $timeout
     */
    public function waitForAjax($timeout = null) {
        $this->waitForJs('return (0 === $.active);', $timeout);
    }

    /**
     * @param string $javascript
     * @return mixed
     */
    public function executeJs($javascript) {
        return $this->_webDriver->executeScript($javascript);
    }

    /**
     * @param string $locator
     * @return string
     */
    public function getText($locator) {
        return $this->_findElement($locator)->getText();
    }

    /**
     * @param string $locator
     * @return string
     */
    public function getHtml($locator) {
        return $this->getAttribute($locator, 'innerHTML');
    }

    /**
     * @param string $locator
     * @param string $attribute
     * @return string
     */
    public function getAttribute($locator, $attribute) {
        return $this->_findElement($locator)->getAttribute($attribute);
    }

    /**
     * @return string
     */
    public function getUrl() {
        return $this->_webDriver->getCurrentURL();
    }

    /**
     * @param string $locator
     * @return bool
     */
    public function isDisplayed($locator) {
        return $this->_findElement($locator)->isDisplayed();
    }

    /**
     * @param string $path
     */
    public function takeScreenshot($path) {
        $this->_webDriver->takeScreenshot($path);
    }

    /**
     * @param string               $locator
     * @param string|string[]|bool $value
     * @throws \Exception
     */
    public function setField($locator, $value) {
        $element = $this->_findElement($locator);
        $tagName = $element->getTagName();
        switch ($tagName) {
            case 'select':
                $this->_setFieldSelect(new WebDriverSelect($element), $value);
                break;
            case 'textarea':
                $this->_setFieldText($element, $value);
                break;
            case 'input':
                if ('radio' === $element->getAttribute('type') || 'checkbox' === $element->getAttribute('type')) {
                    if ($element->isSelected() != $value) {
                        $element->click();
                    }
                } else {
                    $this->_setFieldText($element, $value);
                }
                break;
            default:
                throw new \Exception("Cannot set field with tagName `{$tagName}`");
                break;
        }
    }

    /**
     * @param WebDriverElement $element
     * @param string           $value
     */
    protected function _setFieldText(WebDriverElement $element, $value) {
        $element->clear();
        $element->sendKeys($value);
    }

    /**
     * @param WebDriverSelect $select
     * @param string|string[] $value
     * @throws \Exception
     */
    protected function _setFieldSelect(WebDriverSelect $select, $value) {
        $valueList = (array) $value;

        if ($select->isMultiple()) {
            $select->deselectAll();
        }

        $matched = false;
        foreach ($valueList as $value) {
            try {
                $select->selectByVisibleText($value);
                $matched = true;
            } catch (NoSuchElementException $e) {
            }
        }
        if ($matched) {
            return;
        }
        foreach ($valueList as $value) {
            try {
                $select->selectByValue($value);
                $matched = true;
            } catch (NoSuchElementException $e) {
            }
        }
        if (false === $matched) {
            throw new \Exception("Cannot select option `{$value}`");
        }
    }

    /**
     * @param \Closure|WebDriverExpectedCondition $functionOrCondition
     * @param int|null                            $timeout
     */
    protected function _waitUntil($functionOrCondition, $timeout = null) {
        if (null === $timeout) {
            $timeout = $this->_options->getWaitTimeout();
        }
        $this->_webDriver->wait($timeout)->until($functionOrCondition);
    }

    /**
     * @param string $locator
     * @return WebDriverElement
     */
    protected function _findElement($locator) {
        return $this->_webDriver->findElement($this->_getLocator($locator));
    }

    /**
     * @param string $locator
     * @return WebDriverBy
     */
    protected function _getLocator($locator) {
        if (null !== $this->_locatorPrefix) {
            $locator = $this->_locatorPrefix . ' ' . $locator;
        }
        return WebDriverBy::cssSelector($locator);
    }
}


text:
set -o pipefail
#
# See docker_toy/README.md before running this script!
#

# Assume that `docker_toy` is not a symlink, so we can `dirname` twice.
docker_toy_dir=$(dirname "$0")
web_ui_dir=$(dirname "$docker_toy_dir")

tar -C "$web_ui_dir" -czf "$docker_toy_dir/web_ui.tgz" .
cd "$docker_toy_dir"
docker build .


text:
<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * Staff.php.
 *
 * Part of Supe\Wechat.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015 overtrue <i@overtrue.me>
 *
 * @link      https://github.com/overtrue
 * @link      http://overtrue.me
 */

namespace Supe\Wechat;

use Supe\Wechat\Messages\BaseMessage;

/**
 * 客服.
 */
class Staff
{
    /**
     * 消息.
     *
     * @var \Supe\Wechat\Messages\BaseMessage;
     */
    protected $message;

    /**
     * 指定消息发送客服账号.
     *
     * @var string
     */
    protected $by;

    /**
     * 请求的headers.
     *
     * @var array
     */
    protected $headers = array('content-type:application/json');

    const API_GET = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist';
    const API_ONLINE = 'https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist';
    const API_DELETE = 'https://api.weixin.qq.com/customservice/kfaccount/del';
    const API_UPDATE = 'https://api.weixin.qq.com/customservice/kfaccount/update';
    const API_CREATE = 'https://api.weixin.qq.com/customservice/kfaccount/add';
    const API_MESSAGE_SEND = 'https://api.weixin.qq.com/cgi-bin/message/custom/send';
    const API_AVATAR_UPLOAD = 'http://api.weixin.qq.com/customservice/kfaccount/uploadheadimg';

    /**
     * Http对象
     *
     * @var Http
     */
    protected $http;

    /**
     * constructor.
     *
     * @param string $appId
     * @param string $appSecret
     */
    public function __construct($appId, $appSecret)
    {
        $this->http = new Http(new AccessToken($appId, $appSecret));
    }

    /**
     * 获取所有的客服.
     *
     * @return array
     */
    public function lists()
    {
        $response = $this->http->get(self::API_GET);

        return $response['kf_list'];
    }

    /**
     * 获取所有在线的.
     *
     * @return array
     */
    public function onlines()
    {
        $response = $this->http->get(self::API_ONLINE);

        return $response['kf_online_list'];
    }

    /**
     * 添加客服账号.
     *
     * @param string $email
     * @param string $nickname
     * @param string $password
     *
     * @return bool
     */
    public function create($email, $nickname, $password)
    {
        $params = array(
                   'kf_account' => $email,
                   'nickname' => $nickname,
                   'password' => $password,
                  );

        return $this->http->jsonPost(self::API_CREATE, $params);
    }

    /**
     * 修改客服账号.
     *
     * @param string $email
     * @param string $nickname
     * @param string $password
     *
     * @return bool
     */
    public function update($email, $nickname, $password)
    {
        $params = array(
                   'kf_account' => $email,
                   'nickname' => $nickname,
                   'password' => $password,
                  );

        return $this->http->jsonPost(self::API_UPDATE, $params);
    }

    /**
     * 删除客服账号.
     *
     * @param string $email
     *
     * @return bool
     */
    public function delete($email, $nickname, $password)
    {
        $params = array(
                   'kf_account' => $email,
                   'nickname' => $nickname,
                   'password' => $password,
                  );

        return $this->http->jsonPost(self::API_DELETE, $params);
    }

    /**
     * 上传头像.
     *
     * @param string $email
     * @param string $path
     *
     * @return bool
     */
    public function avatar($email, $path)
    {
        $options = array(
                    'files' => array('media' => $path),
                   );

        $url = self::API_AVATAR_UPLOAD."?kf_account={$email}";

        return $this->http->post($url, array(), $options);
    }

    /**
     * 准备消息.
     *
     * @param \Supe\Wechat\Messages\BaseMessage $message
     *
     * @return Staff
     */
    public function send($message)
    {
        is_string($message) && $message = Message::make('text')->with('content', $message);

        if (!$message instanceof BaseMessage) {
            throw new \Exception("消息必须继承自 'Supe\\Wechat\\BaseMessage'");
        }

        $this->message = $message;

        return $this;
    }

    /**
     * 指定客服.
     *
     * @param string $account
     *
     * @return Staff
     */
    public function by($account)
    {
        if (empty($this->message)) {
            throw new Exception('未设置要发送的消息');
        }

        $this->message->staff = $account;

        return $this;
    }

    /**
     * 发送消息.
     *
     * @param string $openId
     *
     * @return bool
     */
    public function to($openId)
    {
        if (empty($this->message)) {
            throw new Exception('未设置要发送的消息');
        }

        $this->message->to = $openId;

        return $this->http->jsonPost(self::API_MESSAGE_SEND, $this->message->buildForStaff());
    }
}


text:
package uk.gov.hmrc.ct

import uk.gov.hmrc.ct.box.{Calculated, CtBoxIdentifier, CtInteger, NotInPdf}
import uk.gov.hmrc.ct.computations.calculations.ExpensesCalculator
import uk.gov.hmrc.ct.computations.retriever.ComputationsBoxRetriever

case class CATO14(value: Int) extends CtBoxIdentifier(name = "Directors Expenses") with CtInteger with NotInPdf

object CATO14 extends Calculated[CATO14, ComputationsBoxRetriever] with ExpensesCalculator {

  override def calculate(fieldValueRetriever: ComputationsBoxRetriever): CATO14 = {
    calculateDirectorsExpenses(cp15 = fieldValueRetriever.retrieveCP15(),
                               cp16 = fieldValueRetriever.retrieveCP16(),
                               cp17 = fieldValueRetriever.retrieveCP17(),
                               cp18 = fieldValueRetriever.retrieveCP18(),
                               cp19 = fieldValueRetriever.retrieveCP19(),
                               cp20 = fieldValueRetriever.retrieveCP20(),
                               cp21 = fieldValueRetriever.retrieveCP21())
  }
}


text:
var ANY: any;
var ANY1;
var ANY2: any[] = ["", ""];
var obj: () => {};
var obj1 = { x: "", y: () => { }};
function foo(): any {
    var a;
    return a;
}
class A {
    public a: any;
    static foo() {
        var a;
        return a;
    }
}
module M {
    export var n: any;
}
var objA = new A();

// any type var
var ResultIsBoolean1 = delete ANY1;
var ResultIsBoolean2 = delete ANY2;
var ResultIsBoolean3 = delete A;
var ResultIsBoolean4 = delete M;
var ResultIsBoolean5 = delete obj;
var ResultIsBoolean6 = delete obj1;

// any type literal
var ResultIsBoolean7 = delete undefined;
var ResultIsBoolean8 = delete null;

// any type expressions
var ResultIsBoolean9 = delete ANY2[0];
var ResultIsBoolean10 = delete obj1.x;
var ResultIsBoolean11 = delete obj1.y;
var ResultIsBoolean12 = delete objA.a;
var ResultIsBoolean13 = delete M.n;
var ResultIsBoolean14 = delete foo();
var ResultIsBoolean15 = delete A.foo();
var ResultIsBoolean16 = delete (ANY + ANY1);
var ResultIsBoolean17 = delete (null + undefined);
var ResultIsBoolean18 = delete (null + null);
var ResultIsBoolean19 = delete (undefined + undefined);

// multiple delete  operators
var ResultIsBoolean20 = delete delete ANY;
var ResultIsBoolean21 = delete delete delete (ANY + ANY1);

// miss assignment operators
delete ANY;
delete ANY1;
delete ANY2[0];
delete ANY, ANY1;
delete obj1.x;
delete obj1.y;
delete objA.a;
delete M.n;

//// [deleteOperatorWithAnyOtherType.js]
// delete  operator on any type
var ANY;
var ANY1;
var ANY2 = ["", ""];
var obj;
var obj1 = { x: "", y: function () {
} };
function foo() {
    var a;
    return a;
}
var A = (function () {
    function A() {
    }
    A.foo = function () {
        var a;
        return a;
    };
    return A;
})();
var M;
(function (M) {
    M.n;
})(M || (M = {}));
var objA = new A();
// any type var
var ResultIsBoolean1 = delete ANY1;
var ResultIsBoolean2 = delete ANY2;
var ResultIsBoolean3 = delete A;
var ResultIsBoolean4 = delete M;
var ResultIsBoolean5 = delete obj;
var ResultIsBoolean6 = delete obj1;
// any type literal
var ResultIsBoolean7 = delete undefined;
var ResultIsBoolean8 = delete null;
// any type expressions
var ResultIsBoolean9 = delete ANY2[0];
var ResultIsBoolean10 = delete obj1.x;
var ResultIsBoolean11 = delete obj1.y;
var ResultIsBoolean12 = delete objA.a;
var ResultIsBoolean13 = delete M.n;
var ResultIsBoolean14 = delete foo();
var ResultIsBoolean15 = delete A.foo();
var ResultIsBoolean16 = delete (ANY + ANY1);
var ResultIsBoolean17 = delete (null + undefined);
var ResultIsBoolean18 = delete (null + null);
var ResultIsBoolean19 = delete (undefined + undefined);
// multiple delete  operators
var ResultIsBoolean20 = delete delete ANY;
var ResultIsBoolean21 = delete delete delete (ANY + ANY1);
// miss assignment operators
delete ANY;
delete ANY1;
delete ANY2[0];
delete ANY, ANY1;
delete obj1.x;
delete obj1.y;
delete objA.a;
delete M.n;


text:
"""
Support for Yr.no weather service.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.yr/
"""
import asyncio
from datetime import timedelta
import logging
from random import randrange
from xml.parsers.expat import ExpatError

import async_timeout
import aiohttp
import voluptuous as vol

import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
    CONF_LATITUDE, CONF_LONGITUDE, CONF_ELEVATION, CONF_MONITORED_CONDITIONS,
    ATTR_ATTRIBUTION)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import (
    async_track_point_in_utc_time, async_track_utc_time_change)
from homeassistant.util import dt as dt_util

REQUIREMENTS = ['xmltodict==0.11.0']

_LOGGER = logging.getLogger(__name__)

CONF_ATTRIBUTION = "Weather forecast from yr.no, delivered by the Norwegian " \
                   "Meteorological Institute and the NRK."

# Sensor types are defined like so:
SENSOR_TYPES = {
    'symbol': ['Symbol', None],
    'precipitation': ['Precipitation', 'mm'],
    'temperature': ['Temperature', '°C'],
    'windSpeed': ['Wind speed', 'm/s'],
    'windGust': ['Wind gust', 'm/s'],
    'pressure': ['Pressure', 'hPa'],
    'windDirection': ['Wind direction', '°'],
    'humidity': ['Humidity', '%'],
    'fog': ['Fog', '%'],
    'cloudiness': ['Cloudiness', '%'],
    'lowClouds': ['Low clouds', '%'],
    'mediumClouds': ['Medium clouds', '%'],
    'highClouds': ['High clouds', '%'],
    'dewpointTemperature': ['Dewpoint temperature', '°C'],
}

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Optional(CONF_MONITORED_CONDITIONS, default=['symbol']): vol.All(
        cv.ensure_list, vol.Length(min=1), [vol.In(SENSOR_TYPES.keys())]),
    vol.Optional(CONF_LATITUDE): cv.latitude,
    vol.Optional(CONF_LONGITUDE): cv.longitude,
    vol.Optional(CONF_ELEVATION): vol.Coerce(int),
})

@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Yr.no sensor."""
    latitude = config.get(CONF_LATITUDE, hass.config.latitude)
    longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
    elevation = config.get(CONF_ELEVATION, hass.config.elevation or 0)

    if None in (latitude, longitude):
        _LOGGER.error("Latitude or longitude not set in Home Assistant config")
        return False

    coordinates = {'lat': str(latitude),
                   'lon': str(longitude),
                   'msl': str(elevation)}

    dev = []
    for sensor_type in config[CONF_MONITORED_CONDITIONS]:
        dev.append(YrSensor(sensor_type))
    async_add_devices(dev)

    weather = YrData(hass, coordinates, dev)
    # Update weather on the hour, spread seconds
    async_track_utc_time_change(
        hass, weather.async_update, minute=randrange(1, 10),
        second=randrange(0, 59))
    yield from weather.async_update()

class YrSensor(Entity):
    """Representation of an Yr.no sensor."""

    def __init__(self, sensor_type):
        """Initialize the sensor."""
        self.client_name = 'yr'
        self._name = SENSOR_TYPES[sensor_type][0]
        self.type = sensor_type
        self._state = None
        self._unit_of_measurement = SENSOR_TYPES[self.type][1]

    @property
    def name(self):
        """Return the name of the sensor."""
        return '{} {}'.format(self.client_name, self._name)

    @property
    def state(self):
        """Return the state of the device."""
        return self._state

    @property
    def should_poll(self):  # pylint: disable=no-self-use
        """No polling needed."""
        return False

    @property
    def entity_picture(self):
        """Weather symbol if type is symbol."""
        if self.type != 'symbol':
            return None
        return "//api.met.no/weatherapi/weathericon/1.1/" \
               "?symbol={0};content_type=image/png".format(self._state)

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return {
            ATTR_ATTRIBUTION: CONF_ATTRIBUTION,
        }

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement of this entity, if any."""
        return self._unit_of_measurement

class YrData(object):
    """Get the latest data and updates the states."""

    def __init__(self, hass, coordinates, devices):
        """Initialize the data object."""
        self._url = 'https://aa015h6buqvih86i1.api.met.no/'\
                    'weatherapi/locationforecast/1.9/'
        self._urlparams = coordinates
        self._nextrun = None
        self.devices = devices
        self.data = {}
        self.hass = hass

    @asyncio.coroutine
    def async_update(self, *_):
        """Get the latest data from yr.no."""
        import xmltodict

        def try_again(err: str):
            """Retry in 15 minutes."""
            _LOGGER.warning('Retrying in 15 minutes: %s', err)
            self._nextrun = None
            nxt = dt_util.utcnow() + timedelta(minutes=15)
            if nxt.minute >= 15:
                async_track_point_in_utc_time(self.hass, self.async_update,
                                              nxt)

        if self._nextrun is None or dt_util.utcnow() >= self._nextrun:
            try:
                websession = async_get_clientsession(self.hass)
                with async_timeout.timeout(10, loop=self.hass.loop):
                    resp = yield from websession.get(
                        self._url, params=self._urlparams)
                if resp.status != 200:
                    try_again('{} returned {}'.format(resp.url, resp.status))
                    return
                text = yield from resp.text()

            except (asyncio.TimeoutError, aiohttp.ClientError) as err:
                try_again(err)
                return

            try:
                self.data = xmltodict.parse(text)['weatherdata']
                model = self.data['meta']['model']
                if '@nextrun' not in model:
                    model = model[0]
                self._nextrun = dt_util.parse_datetime(model['@nextrun'])
            except (ExpatError, IndexError) as err:
                try_again(err)
                return

        now = dt_util.utcnow()

        tasks = []
        # Update all devices
        for dev in self.devices:
            # Find sensor
            for time_entry in self.data['product']['time']:
                valid_from = dt_util.parse_datetime(time_entry['@from'])
                valid_to = dt_util.parse_datetime(time_entry['@to'])
                new_state = None

                loc_data = time_entry['location']

                if dev.type not in loc_data or now >= valid_to:
                    continue

                if dev.type == 'precipitation' and valid_from < now:
                    new_state = loc_data[dev.type]['@value']
                    break
                elif dev.type == 'symbol' and valid_from < now:
                    new_state = loc_data[dev.type]['@number']
                    break
                elif dev.type in ('temperature', 'pressure', 'humidity',
                                  'dewpointTemperature'):
                    new_state = loc_data[dev.type]['@value']
                    break
                elif dev.type in ('windSpeed', 'windGust'):
                    new_state = loc_data[dev.type]['@mps']
                    break
                elif dev.type == 'windDirection':
                    new_state = float(loc_data[dev.type]['@deg'])
                    break
                elif dev.type in ('fog', 'cloudiness', 'lowClouds',
                                  'mediumClouds', 'highClouds'):
                    new_state = loc_data[dev.type]['@percent']
                    break

            # pylint: disable=protected-access
            if new_state != dev._state:
                dev._state = new_state
                tasks.append(dev.async_update_ha_state())

        if tasks:
            yield from asyncio.wait(tasks, loop=self.hass.loop)


text:
"""Tests for reading with file without samples"""

from io import StringIO
import textwrap

import vcfpy

def test_reading_parse_nosample(tmpdir, nosample_vcf_file):
    """Test reading of VCF file without any samples."""
    # Perform record-wise copying, saving results in records
    records = []
    with vcfpy.Reader.from_path(nosample_vcf_file) as reader:
        for record in reader:
            records.append(record)
    # Check resulting records, checking the first and last records is enough
    assert len(records) == 5

def test_reading_parse_nosample(tmpdir, nosample_vcf_file):
    """Read VCF file without samples, write file with samples."""
    # Perform record-wise copying, saving results in records
    path_out = tmpdir.mkdir("output").join("output.vcf")
    with vcfpy.Reader.from_path(nosample_vcf_file) as reader:
        header = reader.header.copy()
        header.samples = vcfpy.SamplesInfos(["NA00001", "NA00002", "NA00003"])
        with vcfpy.Writer.from_path(str(path_out), header) as writer:
            for record in reader:
                record.update_calls(
                    [vcfpy.Call(sample, {}) for sample in ("NA00001", "NA00002", "NA00003")]
                )
                record.add_format("GT", "./.")
                writer.write_record(record)

    expected = textwrap.dedent(
        """
    ##fileformat=VCFv4.3
    ##contig=<ID=20,length=62435964,assembly=B36,md5=f126cdf8a6e0c7f379d618ff66beb2da,species="Homo sapiens",taxonomy=x>
    ##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">
    #CHROM	POS	ID	REF	ALT	QUAL	FILTER	INFO	FORMAT	NA00001	NA00002	NA00003
    20	14370	.	G	A	29	.	.	GT	.	.	.
    20	17330	.	T	A	3	.	.	GT	.	.	.
    20	1110696	.	A	G,T	67	.	.	GT	.	.	.
    20	1230237	.	T	.	47	.	.	GT	.	.	.
    20	1234567	.	GTC	G,GTCT	50	.	.	GT	.	.	.
    """
    ).lstrip()

    assert path_out.open("rt").read() == expected


text:
using Synology.Attributes;
using System.ComponentModel;

namespace Synology.FileStation.Search.Parameters
{
	public enum FileType
	{
		[Description("file")]
		File,
		[Description("dir")]
		Directory,
		[Description("all")]
		All
	}
}


text:
package org.guvnor.common.services.project.backend.server;

import java.net.URI;
import java.util.Collection;
import java.util.Map;
import javax.enterprise.event.Event;

import org.guvnor.common.services.project.events.DeleteProjectEvent;
import org.guvnor.common.services.project.model.Project;
import org.uberfire.commons.validation.PortablePreconditions;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.file.Path;
import org.uberfire.workbench.events.ResourceBatchChangesEvent;
import org.uberfire.workbench.events.ResourceChange;
import org.uberfire.workbench.events.ResourceDeleted;
import org.uberfire.workbench.events.ResourceDeletedEvent;

/**
 * A bridge between changes made to an underlying VFS and Project abstractions. Projects can be deleted
 * either through the Workbench's UI or via REST or on a cloned repository that's pushed back to the Workbench.
 * Interested observers are signaled of a Project deletion event when a pom.xml file is detected as deleted.
 */
public abstract class AbstractDeleteProjectObserverBridge<T extends Project> {

    private IOService ioService;
    private Event<DeleteProjectEvent> deleteProjectEvent;

    public AbstractDeleteProjectObserverBridge() {
        //Zero-arg constructor for CDI proxying
    }

    public AbstractDeleteProjectObserverBridge(final IOService ioService,
                                               final Event<DeleteProjectEvent> deleteProjectEvent) {
        this.ioService = PortablePreconditions.checkNotNull("ioService",
                                                            ioService);
        this.deleteProjectEvent = PortablePreconditions.checkNotNull("deleteProjectEvent",
                                                                     deleteProjectEvent);
    }

    public void onBatchResourceChanges(final ResourceDeletedEvent event) {
        if (event.getPath().getFileName().equals("pom.xml")) {
            fireDeleteEvent(event.getPath());
        }
    }

    public void onBatchResourceChanges(final ResourceBatchChangesEvent resourceBatchChangesEvent) {
        for (final Map.Entry<org.uberfire.backend.vfs.Path, Collection<ResourceChange>> entry : resourceBatchChangesEvent.getBatch().entrySet()) {
            if (entry.getKey().getFileName().equals("pom.xml") && isDelete(entry.getValue())) {
                fireDeleteEvent(entry.getKey());
            }
        }
    }

    private boolean isDelete(final Collection<ResourceChange> value) {
        for (final ResourceChange resourceChange : value) {
            if (resourceChange instanceof ResourceDeleted) {
                return true;
            }
        }
        return false;
    }

    private void fireDeleteEvent(final org.uberfire.backend.vfs.Path _path) {
        final Path path = ioService.get(URI.create(_path.toURI()));
        final T project = getProject(path.getParent());
        deleteProjectEvent.fire(new DeleteProjectEvent(project));
    }

    protected abstract T getProject(final Path path);
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/nacl/loader/nacl_sandbox_linux.h"

#include <errno.h>
#include <signal.h>
#include <sys/ptrace.h>

#include "base/basictypes.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "build/build_config.h"
#include "content/public/common/sandbox_init.h"
#include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
#include "sandbox/linux/seccomp-bpf/sandbox_bpf_policy.h"
#include "sandbox/linux/services/linux_syscalls.h"

using sandbox::ErrorCode;
using sandbox::SandboxBPF;
using sandbox::SandboxBPFPolicy;

namespace {

// On ARM and x86_64, System V shared memory calls have each their own system
// call, while on i386 they are multiplexed.
#if defined(__x86_64__) || defined(__arm__)
bool IsSystemVSharedMemory(int sysno) {
  switch (sysno) {
    case __NR_shmat:
    case __NR_shmctl:
    case __NR_shmdt:
    case __NR_shmget:
      return true;
    default:
      return false;
  }
}
#endif

#if defined(__i386__)
// Big system V multiplexing system call.
bool IsSystemVIpc(int sysno) {
  switch (sysno) {
    case __NR_ipc:
      return true;
    default:
      return false;
  }
}
#endif

class NaClBPFSandboxPolicy : public SandboxBPFPolicy {
 public:
  NaClBPFSandboxPolicy()
      : baseline_policy_(content::GetBPFSandboxBaselinePolicy()) {}
  virtual ~NaClBPFSandboxPolicy() {}

  virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox_compiler,
                                    int system_call_number) const OVERRIDE;

 private:
  scoped_ptr<SandboxBPFPolicy> baseline_policy_;
  DISALLOW_COPY_AND_ASSIGN(NaClBPFSandboxPolicy);
};

ErrorCode NaClBPFSandboxPolicy::EvaluateSyscall(
    sandbox::SandboxBPF* sb, int sysno) const {
  DCHECK(baseline_policy_);
  switch (sysno) {
    // TODO(jln): NaCl's GDB debug stub uses the following socket system calls,
    // see if it can be restricted a bit.
#if defined(__x86_64__) || defined(__arm__)
    // transport_common.cc needs this.
    case __NR_accept:
    case __NR_setsockopt:
#elif defined(__i386__)
    case __NR_socketcall:
#endif
    // trusted/service_runtime/linux/thread_suspension.c needs sigwait() and is
    // used by NaCl's GDB debug stub.
    case __NR_rt_sigtimedwait:
#if defined(__i386__)
    // Needed on i386 to set-up the custom segments.
    case __NR_modify_ldt:
#endif
    // NaClAddrSpaceBeforeAlloc needs prlimit64.
    case __NR_prlimit64:
    // NaCl uses custom signal stacks.
    case __NR_sigaltstack:
    // Below is fairly similar to the policy for a Chromium renderer.
    // TODO(jln): restrict clone(), ioctl() and prctl().
    case __NR_ioctl:
#if defined(__i386__) || defined(__x86_64__)
    case __NR_getrlimit:
#endif
#if defined(__i386__) || defined(__arm__)
    case __NR_ugetrlimit:
#endif
    // NaCl runtime exposes clock_getres to untrusted code.
    case __NR_clock_getres:
    // NaCl runtime uses flock to simulate POSIX behavior for pwrite.
    case __NR_flock:
    case __NR_pread64:
    case __NR_pwrite64:
    case __NR_sched_get_priority_max:
    case __NR_sched_get_priority_min:
    case __NR_sched_getaffinity:
    case __NR_sched_getparam:
    case __NR_sched_getscheduler:
    case __NR_sched_setscheduler:
    case __NR_setpriority:
    case __NR_sysinfo:
    // __NR_times needed as clock() is called by CommandBufferHelper, which is
    // used by NaCl applications that use Pepper's 3D interfaces.
    // See crbug.com/264856 for details.
    case __NR_times:
    case __NR_uname:
      return ErrorCode(ErrorCode::ERR_ALLOWED);
    case __NR_ptrace:
      return ErrorCode(EPERM);
    default:
      // TODO(jln): look into getting rid of System V shared memory:
      // platform_qualify/linux/sysv_shm_and_mmap.c makes it a requirement, but
      // it may not be needed in all cases. Chromium renderers don't need
      // System V shared memory on Aura.
#if defined(__x86_64__) || defined(__arm__)
      if (IsSystemVSharedMemory(sysno))
        return ErrorCode(ErrorCode::ERR_ALLOWED);
#elif defined(__i386__)
      if (IsSystemVIpc(sysno))
        return ErrorCode(ErrorCode::ERR_ALLOWED);
#endif
      return baseline_policy_->EvaluateSyscall(sb, sysno);
  }
  NOTREACHED();
  // GCC wants this.
  return ErrorCode(EPERM);
}

void RunSandboxSanityChecks() {
  errno = 0;
  // Make a ptrace request with an invalid PID.
  long ptrace_ret = ptrace(PTRACE_PEEKUSER, -1 /* pid */, NULL, NULL);
  CHECK_EQ(-1, ptrace_ret);
  // Without the sandbox on, this ptrace call would ESRCH instead.
  CHECK_EQ(EPERM, errno);
}

}  // namespace

bool InitializeBPFSandbox() {
  bool sandbox_is_initialized = content::InitializeSandbox(
      scoped_ptr<SandboxBPFPolicy>(new NaClBPFSandboxPolicy()));
  if (sandbox_is_initialized) {
    RunSandboxSanityChecks();
    return true;
  }
  return false;
}


text:
Home Plans & Features

	See Filter Options
		<form id="filters" class="custom hide-for-small">
		  <fieldset>
		    <legend>Filters</legend>

								Price Range
								  <select id="customDropdown">
								    <option>No Preference</option>
								    <option>Under $300K</option>
								    <option>$300K - $500K</option>
								    <option>Over $500K</option>
								  </select>

								Bedrooms
							  <select id="customDropdown">
							    <option>No Preference</option>
							    <option>2</option>
							    <option>3</option>
							    <option>4+</option>
							  </select>

								Bathrooms
							  <select id="customDropdown">
							    <option>No Preference</option>
							    <option>1 ½</option>
							    <option>2</option>
							    <option>3</option>
							  </select>

				    	<input type="submit" class=" small button" value="Apply Filters"/>

		  </fieldset>
		</form>

Spacious Saltbox

This delightful Saltbox is one of the most efficient designs we build and the "Best Bang for the Buck!"

View PlanGet A Price

Half Cape Ranch

But it doesn't look like a Ranch! Living doesn't have to lack style and beauty. We call this a Half Cape Ranch because of its authentic look.

View PlanGet A Price

Traditional Cape

But it doesn't look like a Ranch! Living doesn't have to lack style and beauty. We call this a Half Cape Ranch because of its authentic look.

View PlanGet A Price

Greek Revival

But it doesn't look like a Ranch! Living doesn't have to lack style and beauty. We call this a Half Cape Ranch because of its authentic look.

View PlanGet A Price

Traditional Modified Half Cape

But it doesn't look like a Ranch! Living doesn't have to lack style and beauty. We call this a Half Cape Ranch because of its authentic look.

View PlanGet A Price

Modified Victorian

But it doesn't look like a Ranch! Living doesn't have to lack style and beauty. We call this a Half Cape Ranch because of its authentic look.

View PlanGet A Price

			Get Our Free Construction Cost Guide

Need an extra bedroom? No problem.

All our homes are custom built. These plans are simply starting points. We'll work with you to customize your home to suit your needs and make sure it's exactly what you want.

Related Blog Posts

how to plan your dream home

lorem ipsum dolor sit amet, consectetur adipiscing elit


text:
<!doctype html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>
async_test(t => {
  // Wait for after the load event so that the navigation doesn't get converted
  // into a replace navigation.
  window.onload = () => t.step_timeout(async () => {
    let entry0 = navigation.currentEntry;

    let navState = { statevar: "state" };
    await navigation.navigate("#1", { state: navState }).committed;
    let entry1 = navigation.currentEntry;

    navState.startvar2 = "otherstate";
    await navigation.navigate("#2", { state: navState }).committed;
    let entry2 = navigation.currentEntry;

    t.step_func(() => {
      assert_equals(navigation.entries().length, 3);
      assert_equals(entry0, navigation.entries()[0]);
      assert_equals(entry1, navigation.entries()[1]);
      assert_equals(entry2, navigation.entries()[2]);

      assert_equals(entry0.getState(), undefined);

      let state1 = entry1.getState();
      assert_not_equals(state1, undefined);
      assert_not_equals(state1, navState);
      assert_equals(state1.statevar, "state");
      assert_equals(state1.startvar2, undefined);

      let state2 = entry2.getState();
      assert_not_equals(state2, undefined);
      assert_not_equals(state2, navState);
      assert_equals(state2.statevar, "state");
      assert_equals(state2.startvar2, "otherstate");

      navigation.back();
      window.onpopstate = t.step_func_done(() => {
        assert_equals(navigation.entries().length, 3);
        let back_entry = navigation.currentEntry;
        assert_equals(back_entry, navigation.entries()[1]);
        let back_state = back_entry.getState();
        assert_not_equals(back_state, state1);
        assert_not_equals(back_state, state2);
        assert_equals(back_state.statevar, "state");
        assert_equals(back_state.startvar2, undefined);
      });
    })();
  }, 0);
}, "entry.getState() behavior after navigating away using the navigation API, then back");
</script>


text:
using UnityEngine;
using System.Collections;

public class LevelSelect : MonoBehaviour {

	public LayerMask ClickableLayer;

	// Update is called once per frame
	void Update () {

		// Handle left click
		if (Input.GetMouseButton (0)) {

			Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
			RaycastHit hit;
			if (Physics.Raycast (ray, out hit, 1000, ClickableLayer)) {

				var selectedGameObject = hit.collider.gameObject.transform;
				var levelName = selectedGameObject.name;

				LevelSelection.LoadLevel(levelName);
			}
		}
	}
}


text:
package com.example.android.hcgallery;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;

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

public class CameraFragment extends Fragment {

    private Preview mPreview;
    Camera mCamera;
    int mNumberOfCameras;
    int mCurrentCamera;  // Camera ID currently chosen
    int mCameraCurrentlyLocked;  // Camera ID that's actually acquired

    // The first rear facing camera
    int mDefaultCameraId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create a container that will hold a SurfaceView for camera previews
        mPreview = new Preview(this.getActivity());

        // Find the total number of cameras available
        mNumberOfCameras = Camera.getNumberOfCameras();

        // Find the ID of the rear-facing ("default") camera
        CameraInfo cameraInfo = new CameraInfo();
        for (int i = 0; i < mNumberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
                mCurrentCamera = mDefaultCameraId = i;
            }
        }
        setHasOptionsMenu(mNumberOfCameras > 1);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Add an up arrow to the "home" button, indicating that the button will go "up"
        // one activity in the app's Activity heirarchy.
        // Calls to getActionBar() aren't guaranteed to return the ActionBar when called
        // from within the Fragment's onCreate method, because the Window's decor hasn't been
        // initialized yet.  Either call for the ActionBar reference in Activity.onCreate()
        // (after the setContentView(...) call), or in the Fragment's onActivityCreated method.
        Activity activity = this.getActivity();
        ActionBar actionBar = activity.getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        return mPreview;
    }

    @Override
    public void onResume() {
        super.onResume();

        // Use mCurrentCamera to select the camera desired to safely restore
        // the fragment after the camera has been changed
        mCamera = Camera.open(mCurrentCamera);
        mCameraCurrentlyLocked = mCurrentCamera;
        mPreview.setCamera(mCamera);
    }

    @Override
    public void onPause() {
        super.onPause();

        // Because the Camera object is a shared resource, it's very
        // important to release it when the activity is paused.
        if (mCamera != null) {
            mPreview.setCamera(null);
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if (mNumberOfCameras > 1) {
            // Inflate our menu which can gather user input for switching camera
            inflater.inflate(R.menu.camera_menu, menu);
        } else {
            super.onCreateOptionsMenu(menu, inflater);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu_switch_cam:
            // Release this camera -> mCameraCurrentlyLocked
            if (mCamera != null) {
                mCamera.stopPreview();
                mPreview.setCamera(null);
                mCamera.release();
                mCamera = null;
            }

            // Acquire the next camera and request Preview to reconfigure
            // parameters.
            mCurrentCamera = (mCameraCurrentlyLocked + 1) % mNumberOfCameras;
            mCamera = Camera.open(mCurrentCamera);
            mCameraCurrentlyLocked = mCurrentCamera;
            mPreview.switchCamera(mCamera);

            // Start the preview
            mCamera.startPreview();
            return true;
        case android.R.id.home:
            Intent intent = new Intent(this.getActivity(), MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

// ----------------------------------------------------------------------

/**
 * A simple wrapper around a Camera and a SurfaceView that renders a centered
 * preview of the Camera to the surface. We need to center the SurfaceView
 * because not all devices have cameras that support preview sizes at the same
 * aspect ratio as the device's display.
 */
class Preview extends ViewGroup implements SurfaceHolder.Callback {
    private final String TAG = "Preview";

    SurfaceView mSurfaceView;
    SurfaceHolder mHolder;
    Size mPreviewSize;
    List<Size> mSupportedPreviewSizes;
    Camera mCamera;
    boolean mSurfaceCreated = false;

    Preview(Context context) {
        super(context);

        mSurfaceView = new SurfaceView(context);
        addView(mSurfaceView);

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void setCamera(Camera camera) {
        mCamera = camera;
        if (mCamera != null) {
            mSupportedPreviewSizes = mCamera.getParameters()
                    .getSupportedPreviewSizes();
            if (mSurfaceCreated) requestLayout();
        }
    }

    public void switchCamera(Camera camera) {
        setCamera(camera);
        try {
            camera.setPreviewDisplay(mHolder);
        } catch (IOException exception) {
            Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // We purposely disregard child measurements because act as a
        // wrapper to a SurfaceView that centers the camera preview instead
        // of stretching it.
        final int width = resolveSize(getSuggestedMinimumWidth(),
                widthMeasureSpec);
        final int height = resolveSize(getSuggestedMinimumHeight(),
                heightMeasureSpec);
        setMeasuredDimension(width, height);

        if (mSupportedPreviewSizes != null) {
            mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width,
                    height);
        }

        if (mCamera != null) {
          Camera.Parameters parameters = mCamera.getParameters();
          parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);

          mCamera.setParameters(parameters);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (getChildCount() > 0) {
            final View child = getChildAt(0);

            final int width = r - l;
            final int height = b - t;

            int previewWidth = width;
            int previewHeight = height;
            if (mPreviewSize != null) {
                previewWidth = mPreviewSize.width;
                previewHeight = mPreviewSize.height;
            }

            // Center the child SurfaceView within the parent.
            if (width * previewHeight > height * previewWidth) {
                final int scaledChildWidth = previewWidth * height
                        / previewHeight;
                child.layout((width - scaledChildWidth) / 2, 0,
                        (width + scaledChildWidth) / 2, height);
            } else {
                final int scaledChildHeight = previewHeight * width
                        / previewWidth;
                child.layout(0, (height - scaledChildHeight) / 2, width,
                        (height + scaledChildHeight) / 2);
            }
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, acquire the camera and tell it where
        // to draw.
        try {
            if (mCamera != null) {
                mCamera.setPreviewDisplay(holder);
            }
        } catch (IOException exception) {
            Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
        }
        if (mPreviewSize == null) requestLayout();
        mSurfaceCreated = true;
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // Surface will be destroyed when we return, so stop the preview.
        if (mCamera != null) {
            mCamera.stopPreview();
        }
    }

    private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null)
            return null;

        Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and size
        for (Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // Now that the size is known, set up the camera parameters and begin
        // the preview.
        Camera.Parameters parameters = mCamera.getParameters();
        parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
        requestLayout();

        mCamera.setParameters(parameters);
        mCamera.startPreview();
    }

}