text:
/**
 * @fileoverview
 * Classes used for store configurations.
 * @author Partridge Jiang
 */

/*
 * requires /lan/classes.js
 * requires /lan/serializations.js
 * requires /core/kekule.common.js
 * requires /utils/kekule.utils.js
 */

/**
 * Represent an abstract configuration class to store a set of config items.
 * Configurations are stored in properties of class.
 * @class
 * @augments ObjectEx
 * @param autoInitDefValue Whether set properties to default value after object is created.
 */
Kekule.AbstractConfigs = Class.create(ObjectEx,
	/** @lends Kekule.AbstractConfigs# */
	{
	/** @private */
	CLASS_NAME: 'Kekule.AbstractConfigs',
	/** @private */
	CONFIG_PROP_FLAG: '__$config_prop__',
	/**
	 * @constructs
	 */
	initialize: function(/*$super, */autoInitDefValue)
	{
		this.tryApplySuper('initialize')  /* $super() */;
		if (typeof(autoInitDefValue) == 'undefined')
			autoInitDefValue = true;
		if (autoInitDefValue)
			this.initPropDefValues();
	},
	/**
	 * Add a config property item, actually define a new property.
	 * A config property usually has simple getter/setter and must be serializable.
	 * @param {Object} name
	 * @param {Object} dataType
	 * @param {Variant} defaultValue
	 * @param {Hash} additionalOptions
	 */
	addConfigProp: function(name, dataType, defaultValue, additionalOptions)
	{
		var options = {'dataType': dataType};
		if (additionalOptions)
			options = Object.extend(options, additionalOptions);
		if (typeof(defaultValue) != 'undefined')
			options.defaultValue = defaultValue;
		var result = this.defineProp(name, options);
		// add a special field to indicate that this is a config property
		result[this.CONFIG_PROP_FLAG] = true;
		return result;
	},
	/**
	 * Add a Hash config property item.
	 * @param {Object} name
	 * @param {Hash} defaultValue
	 * @param {Hash} additionalOptions
	 */
	addHashConfigProp: function(name, defaultValue, additionalOptions)
	{
		return this.addConfigProp(name, DataType.HASH, defaultValue, additionalOptions);
	},
	/**
	 * Add a string config property item.
	 * @param {Object} name
	 * @param {String} defaultValue
	 * @param {Hash} additionalOptions
	 */
	addStrConfigProp: function(name, defaultValue, additionalOptions)
	{
		return this.addConfigProp(name, DataType.STRING, defaultValue, additionalOptions);
	},
	/**
	 * Add a numberic config property item.
	 * @param {Object} name
	 * @param {Number} defaultValue
	 * @param {Hash} additionalOptions
	 */
	addNumConfigProp: function(name, defaultValue, additionalOptions)
	{
		return this.addConfigProp(name, DataType.NUM, defaultValue, additionalOptions);
	},
	/**
	 * Add an integer config property item.
	 * @param {Object} name
	 * @param {Int} defaultValue
	 * @param {Hash} additionalOptions
	 */
	addIntConfigProp: function(name, defaultValue, additionalOptions)
	{
		return this.addConfigProp(name, DataType.INT, defaultValue, additionalOptions);
	},
	/**
	 * Add a float config property item.
	 * @param {Object} name
	 * @param {Float} defaultValue
	 * @param {Hash} additionalOptions
	 */
	addFloatConfigProp: function(name, defaultValue, additionalOptions)
	{
		return this.addConfigProp(name, DataType.FLOAT, defaultValue, additionalOptions);
	},
	/**
	 * Add a boolean config property item.
	 * @param {Object} name
	 * @param {Bool} defaultValue
	 * @param {Hash} additionalOptions
	 */
	addBoolConfigProp: function(name, defaultValue, additionalOptions)
	{
		return this.addConfigProp(name, DataType.BOOL, defaultValue, additionalOptions);
	},
	/**
	 * Set properties to their default value.
	 * @private
	 */
	initPropDefValues: function()
	{
		this.beginUpdate();
		try
		{
			var props = this.getAllPropList();
			for (var i = 0, l = props.getLength(); i < l; ++i)
			{
				var prop = props.getPropInfoAt(i);
				var propName = prop.name;
				var defValue = prop.defaultValue;
				if (typeof(defValue) != 'undefined')
					this.setPropValue(propName, defValue);
			}
		}
		finally
		{
			this.endUpdate();
		}
	},
	/**
	 * Check if a property is defined as config property.
   * @param {Object} propInfo
	 * @returns {Bool}
	 */
	isConfigProp: function(propInfo)
	{
		return !!propInfo[this.CONFIG_PROP_FLAG];
	},
	/**
	 * Assign data of src to current config object.
	 * @param {Kekule.AbstractConfig} src
	 */
	assign: function(src)
	{
		src.copyPropsTo(this);
	},

	/**
	 * Convert property name to a new key when calling {@link Kekule.AbstractConfigs.toHash}.
	 * By default this method will attach a prefix from {@link Kekule.AbstractConfigs.doGetPropNameToHashPrefix} to property name。
	 * Descendants may override this method.
	 * @param {String} propName
	 * @returns {String}
	 * @private
	 */
	doTransformPropNameToHash: function(propName)
	{
		return this.doGetPropNameToHashPrefix() + propName;
	},
	/**
	 * Returns a prefix attaching to property name when export hash from config object.
	 * Desendants may override this method.
	 * @returns {String}
	 */
	doGetPropNameToHashPrefix: function()
	{
		return '';
	},
	/**
	 * Wrap all properties to a hash object.
	 * @param {Function} propNameTransformer A function(propName): string, to transform property name.
	 *   If not set, {@link Kekule.AbstractConfigs.doTransformPropNameToHash} will be used.
	 * @returns {Hash}
	 */
	toHash: function(propNameTransformer)
	{
		var obj = {};
		var propFlagName = this.CONFIG_PROP_FLAG;
		this.saveObj(obj, 'json', {
			'saveDefaultValues': true,
			'propFilter': function(prop, obj)
				{
					// save only config properties
					return prop[propFlagName];
				}
		});
		// delete '_type' field
		/*
		if (obj['_type'])
			delete obj['_type'];
		*/
		//console.log(obj);
		//return obj;
		var transformFunc = propNameTransformer || this.doTransformPropNameToHash.bind(this);
		var result = {};
		var keyNames = Kekule.ObjUtils.getOwnedFieldNames(obj, false);
		for (var i = 0, l = keyNames.length; i < l; ++i)
		{
			var transKeyName = transformFunc(keyNames[i]);
			result[transKeyName] = obj[keyNames[i]];
		}
		return result;
	}
});

/**
 * Represent a set of predefined named config values.
 * @class
 * @augments ObjectEx
 */
Kekule.ConfigPresetMap = Class.create(ObjectEx,
	/** @lends Kekule.ConfigPresetMap# */
	{
	/** @private */
	CLASS_NAME: 'Kekule.ConfigPresetMap',
	/** @constructs */
	initialize: function(/*$super*/)
	{
		this.tryApplySuper('initialize')  /* $super() */;
		this.map = new Kekule.MapEx(true);  // a non-weak map
	},
	/** @private */
	doFinalize: function(/*$super*/)
	{
		this.map = null;
		this.tryApplySuper('doFinalize')  /* $super() */;
	},
	/**
	 * Add a preset to map.
	 * @param {String} name
	 * @param {Object} configObj
	 */
	set: function(name, configObj)
	{
		this.map.set(name, configObj);
	},
	/**
	 * Get preset from map.
	 * @param {String} name
	 * @returns {Object}
	 */
	get: function(name)
	{
		return this.map.get(name);
	},
	/**
	 * Get preset from map and turn it into a simple hash object.
	 * @param {String} name
	 * @returns {Hash}
	 */
	getHash: function(name)
	{
		var obj = this.get(name);
		if (obj)
		{
			if (obj.toHash)  // Kekule.Configs
				return obj.toHash();
			else
				return obj;
		}
		else
			return null;
	},
	/**
	 * Remove a preset from map.
	 * @param {String} name
	 */
	remove: function(name)
	{
		this.map.remove(name);
	},
	/**
	 * Check if a preset in map.
	 * @param {String} name
	 * @returns {Bool}
	 */
	has: function(name)
	{
		return this.map.has(name);
	},
	/**
	 * Clear all presets.
	 */
	clear: function()
	{
		this.map.clear();
	}
});

redpajama_set_name: RedPajamaGithub


text: Lorem <header>ipsum</header> dolor sit amet,


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using DnsClient.Internal;
using DnsClient.Protocol;
using Xunit;

namespace DnsClient.Tests
{
    [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
    public class DnsRecordFactoryTest
    {
        static DnsRecordFactoryTest()
        {
            Tracing.Source.Switch.Level = System.Diagnostics.SourceLevels.All;
        }

        internal DnsRecordFactory GetFactory(byte[] data)
        {
            return new DnsRecordFactory(new DnsDatagramReader(new ArraySegment<byte>(data)));
        }

        internal DnsRecordFactory GetFactory(ArraySegment<byte> data)
        {
            return new DnsRecordFactory(new DnsDatagramReader(data));
        }

        [Fact]
        public void DnsRecordFactory_PTRRecordNotEnoughData()
        {
            var data = Array.Empty<byte>();
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.PTR, QueryClass.IN, 0, data.Length);

            Action act = () => factory.GetRecord(info);
            var ex = Assert.ThrowsAny<DnsResponseParseException>(act);
            Assert.Equal(0, ex.Index);
        }

        [Fact]
        public void DnsRecordFactory_PTRRecordEmptyName()
        {
            var data = new byte[] { 0 };
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.PTR, QueryClass.IN, 0, data.Length);

            var result = factory.GetRecord(info) as PtrRecord;

            Assert.Equal(".", result.PtrDomainName.Value);
        }

        [Fact]
        public void DnsRecordFactory_PTRRecord()
        {
            var name = DnsString.Parse("result.example.com");
            var writer = new DnsDatagramWriter();
            writer.WriteHostName(name.Value);
            var factory = GetFactory(writer.Data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.PTR, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as PtrRecord;

            Assert.Equal(result.PtrDomainName, name);
        }

        [Fact]
        public void DnsRecordFactory_MBRecord()
        {
            var name = DnsString.Parse("Müsli.de");
            var writer = new DnsDatagramWriter();
            writer.WriteHostName(name.Value);
            var factory = GetFactory(writer.Data);
            var info = new ResourceRecordInfo("Müsli.de", ResourceRecordType.MB, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as MbRecord;

            Assert.Equal(result.MadName, name);
            Assert.Equal("müsli.de.", result.MadName.Original);
        }

        [Fact]
        public void DnsRecordFactory_ARecordNotEnoughData()
        {
            var data = new byte[] { 23, 23, 23 };
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("example.com", ResourceRecordType.A, QueryClass.IN, 0, data.Length);

            var ex = Assert.ThrowsAny<DnsResponseParseException>(() => factory.GetRecord(info));
            Assert.Contains("IPv4", ex.Message);
            Assert.Equal(0, ex.Index);
            Assert.Equal(4, ex.ReadLength);
        }

        [Fact]
        public void DnsRecordFactory_ARecord()
        {
            var data = new byte[] { 23, 24, 25, 26 };
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("example.com", ResourceRecordType.A, QueryClass.IN, 0, data.Length);

            var result = factory.GetRecord(info) as ARecord;

            Assert.Equal(result.Address, IPAddress.Parse("23.24.25.26"));
        }

        [Fact]
        public void DnsRecordFactory_AAAARecordNotEnoughData()
        {
            var data = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("example.com", ResourceRecordType.AAAA, QueryClass.IN, 0, data.Length);

            var ex = Assert.ThrowsAny<DnsResponseParseException>(() => factory.GetRecord(info));
            Assert.Contains("IPv6", ex.Message);
            Assert.Equal(0, ex.Index);
            Assert.Equal(16, ex.ReadLength);
        }

        [Fact]
        public void DnsRecordFactory_AAAARecord()
        {
            var data = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("example.com", ResourceRecordType.AAAA, QueryClass.IN, 0, data.Length);

            var result = factory.GetRecord(info) as AaaaRecord;

            Assert.Equal(result.Address, IPAddress.Parse("102:304:506:708:90a:b0c:d0e:f10"));
            Assert.Equal(result.Address.GetAddressBytes(), data);
        }

        [Fact]
        public void DnsRecordFactory_NSRecordNotEnoughData()
        {
            var data = Array.Empty<byte>();
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.NS, QueryClass.IN, 0, data.Length);

            var ex = Assert.ThrowsAny<DnsResponseParseException>(() => factory.GetRecord(info));
            Assert.Equal(0, ex.Index);
        }

        [Fact]
        public void DnsRecordFactory_NSRecordEmptyName()
        {
            var data = new byte[] { 0 };
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.NS, QueryClass.IN, 0, data.Length);

            var result = factory.GetRecord(info) as NsRecord;

            Assert.Equal(".", result.NSDName.Value);
        }

        [Fact]
        public void DnsRecordFactory_NSRecord()
        {
            var writer = new DnsDatagramWriter();
            var name = DnsString.Parse("result.example.com");
            writer.WriteHostName(name.Value);
            var factory = GetFactory(writer.Data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.NS, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as NsRecord;

            Assert.Equal(result.NSDName, name);
        }

        [Fact]
        public void DnsRecordFactory_MXRecordOrderMissing()
        {
            var data = Array.Empty<byte>();
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.MX, QueryClass.IN, 0, data.Length);

            Assert.ThrowsAny<DnsResponseParseException>(() => factory.GetRecord(info));
        }

        [Fact]
        public void DnsRecordFactory_MXRecordNameMissing()
        {
            var data = new byte[] { 1, 2 };
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.MX, QueryClass.IN, 0, data.Length);

            Assert.ThrowsAny<DnsResponseParseException>(() => factory.GetRecord(info));
        }

        [Fact]
        public void DnsRecordFactory_MXRecordEmptyName()
        {
            var data = new byte[] { 1, 0, 0 };
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.MX, QueryClass.IN, 0, data.Length);

            var result = factory.GetRecord(info) as MxRecord;

            Assert.Equal(256, result.Preference);
            Assert.Equal(".", result.Exchange.Value);
        }

        [Fact]
        public void DnsRecordFactory_MXRecord()
        {
            var name = DnsString.Parse("result.example.com");
            var writer = new DnsDatagramWriter();
            writer.WriteByte(0);
            writer.WriteByte(1);
            writer.WriteHostName(name.Value);

            var factory = GetFactory(writer.Data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.MX, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as MxRecord;

            Assert.Equal(1, result.Preference);
            Assert.Equal(result.Exchange, name);
        }

        [Fact]
        public void DnsRecordFactory_SOARecordEmpty()
        {
            var data = Array.Empty<byte>();
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.SOA, QueryClass.IN, 0, data.Length);

            Assert.ThrowsAny<DnsResponseParseException>(() => factory.GetRecord(info));
        }

        [Fact]
        public void DnsRecordFactory_SOARecord()
        {
            var data = new byte[] { 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5 };
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.SOA, QueryClass.IN, 0, data.Length);

            var result = factory.GetRecord(info) as SoaRecord;

            Assert.Equal(".", result.MName.Value);
            Assert.Equal(".", result.RName.Value);
            Assert.True(result.Serial == 1);
            Assert.True(result.Refresh == 2);
            Assert.True(result.Retry == 3);
            Assert.True(result.Expire == 4);
            Assert.True(result.Minimum == 5);
        }

        [Fact]
        public void DnsRecordFactory_SRVRecordEmpty()
        {
            var data = Array.Empty<byte>();
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.SRV, QueryClass.IN, 0, data.Length);

            Assert.ThrowsAny<DnsResponseParseException>(() => factory.GetRecord(info));
        }

        [Fact]
        public void DnsRecordFactory_SRVRecord()
        {
            var name = DnsString.Parse("result.example.com");
            var writer = new DnsDatagramWriter();
            writer.WriteBytes(new byte[] { 0, 1, 1, 0, 2, 3 }, 6);
            writer.WriteHostName(name.Value);
            var factory = GetFactory(writer.Data);

            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.SRV, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as SrvRecord;

            Assert.Equal(result.Target, name);
            Assert.True(result.Priority == 1);
            Assert.True(result.Weight == 256);
            Assert.True(result.Port == 515);
        }

        [Fact]
        public void DnsRecordFactory_NAPTRRecord()
        {
            var name = DnsString.Parse("result.example.com");
            var writer = new DnsDatagramWriter();
            writer.WriteUInt16NetworkOrder(0x1e);
            writer.WriteUInt16NetworkOrder(0x00);
            writer.WriteStringWithLengthPrefix(NAPtrRecord.SFlag.ToString());
            writer.WriteStringWithLengthPrefix(NAPtrRecord.ServiceKeySipUdp);
            writer.WriteStringWithLengthPrefix("");
            writer.WriteHostName(name.Value);
            var factory = GetFactory(writer.Data);

            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.NAPTR, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as NAPtrRecord;

            Assert.Equal(name, result.Replacement);
            Assert.True(result.Order == 0x1e);
            Assert.True(result.Preference == 0x00);
            Assert.Equal(NAPtrRecord.SFlag.ToString(), result.Flags);
            Assert.Equal(NAPtrRecord.ServiceKeySipUdp, result.Services);
            Assert.Equal("", result.RegularExpression);
        }

        [Fact]
        public void DnsRecordFactory_TXTRecordEmpty()
        {
            var textA = "Some Text";
            var lineA = Encoding.ASCII.GetBytes(textA);
            var data = new List<byte> { 5 };
            data.AddRange(lineA);

            var factory = GetFactory(data.ToArray());
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.TXT, QueryClass.IN, 0, data.Count);

            Assert.ThrowsAny<DnsResponseParseException>(() => factory.GetRecord(info));
        }

        [Fact]
        public void DnsRecordFactory_TXTRecordWrongTextLength()
        {
            var data = Array.Empty<byte>();
            var factory = GetFactory(data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.TXT, QueryClass.IN, 0, data.Length);

            var result = factory.GetRecord(info) as TxtRecord;

            Assert.Empty(result.EscapedText);
        }

        [Fact]
        public void DnsRecordFactory_TXTRecord()
        {
            var textA = @"Some lines of text.";
            var textB = "Another line";
            var lineA = Encoding.ASCII.GetBytes(textA);
            var lineB = Encoding.ASCII.GetBytes(textB);
            var data = new List<byte>();
            data.Add((byte)lineA.Length);
            data.AddRange(lineA);
            data.Add((byte)lineB.Length);
            data.AddRange(lineB);

            var factory = GetFactory(data.ToArray());
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.TXT, QueryClass.IN, 0, data.Count);

            var result = factory.GetRecord(info) as TxtRecord;

            Assert.Equal(2, result.EscapedText.Count);
            Assert.Equal(result.EscapedText.ElementAt(0), textA);
            Assert.Equal(result.EscapedText.ElementAt(1), textB);
        }

        [Fact]
        public void DnsRecordFactory_TLSARecord()
        {
            var certificateUsage = 0;
            var selector = 1;
            var matchingType = 1;
            var certificateAssociationData = "CDE0D742D6998AA554A92D890F8184C698CFAC8A26FA59875A990C03E576343C";
            var expectedBytes = Enumerable.Range(0, certificateAssociationData.Length)
                .Where(x => x % 2 == 0)
                .Select(x => Convert.ToByte(certificateAssociationData.Substring(x, 2), 16))
                .ToArray();

            var data = new List<byte>()
            {
                (byte)certificateUsage,
                (byte)selector,
                (byte)matchingType,
            };

            data.AddRange(expectedBytes);

            var factory = GetFactory(data.ToArray());
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.TLSA, QueryClass.IN, 0, data.Count);

            var result = factory.GetRecord(info) as TlsaRecord;

            Assert.Equal((TlsaCertificateUsage)certificateUsage, result.CertificateUsage);
            Assert.Equal((TlsaSelector)selector, result.Selector);
            Assert.Equal((TlsaMatchingType)matchingType, result.MatchingType);
            // Checking this in both directions
            Assert.Equal(expectedBytes, result.CertificateAssociationData);
            Assert.Equal(certificateAssociationData, result.CertificateAssociationDataAsString);
        }

        [Fact]
        public void DnsRecordFactory_RRSIGRecord()
        {
            var type = ResourceRecordType.NSEC;
            var algorithmNumber = DnsSecurityAlgorithm.ECDSAP256SHA256;
            var labels = 5;
            var originalTtl = 300;
            var signatureExpiration = 1589414400;
            var signatureInception = 1587600000;
            short keytag = 3942;
            var signersName = DnsString.Parse("result.example.com");
            var signatureString = "kfyyKQoPZJFyOFSDqav7wj5XNRPqZssV2K2k8MJun28QSsCMHyWOjw9Hk4KofnEIUWNui3mMgAEFYbwoeRKkMf5uDAh6ryJ4veQNj86mgYJrpJppUplqlqJE8o1bx0I1VfwheL+M23bL5MnqSGiI5igmMDyeVUraVOO4RQyfGN0=";
            var signature = Convert.FromBase64String(signatureString);

            var writer = new DnsDatagramWriter();

            writer.WriteInt16NetworkOrder((short)type);
            writer.WriteByte((byte)algorithmNumber);
            writer.WriteByte((byte)labels);
            writer.WriteInt32NetworkOrder(originalTtl);
            writer.WriteInt32NetworkOrder(signatureExpiration);
            writer.WriteInt32NetworkOrder(signatureInception);
            writer.WriteInt16NetworkOrder(keytag);
            writer.WriteHostName(signersName.Value);
            writer.WriteBytes(signature, signature.Length);

            var factory = GetFactory(writer.Data);
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.RRSIG, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as RRSigRecord;
            Assert.Equal(type, result.CoveredType);
            Assert.Equal(algorithmNumber, result.Algorithm);
            Assert.Equal(labels, result.Labels);
            Assert.Equal(originalTtl, result.OriginalTtl);
            Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(signatureExpiration), result.SignatureExpiration);
            Assert.Equal(DateTimeOffset.FromUnixTimeSeconds(signatureInception), result.SignatureInception);
            Assert.Equal(signersName.Value, result.SignersName);

            Assert.Equal(signature, result.Signature);
            Assert.Equal(signatureString, result.SignatureAsString);
        }

        [Fact]
        public void DnsRecordFactory_SSHFPRecord()
        {
            var algo = SshfpAlgorithm.RSA;
            var type = SshfpFingerprintType.SHA1;
            var fingerprint = "9DBA55CEA3B8E15528665A6781CA7C35190CF0EC";
            // Value is stored as raw bytes in the record, so convert the HEX string above to it's original bytes
            var fingerprintBytes = Enumerable.Range(0, fingerprint.Length / 2)
                .Select(i => Convert.ToByte(fingerprint.Substring(i * 2, 2), 16));

            var data = new List<byte>
            {
                (byte)algo,
                (byte)type
            };
            data.AddRange(fingerprintBytes);

            var factory = GetFactory(data.ToArray());
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.SSHFP, QueryClass.IN, 0, data.Count);

            var result = factory.GetRecord(info) as SshfpRecord;

            Assert.Equal(SshfpAlgorithm.RSA, result.Algorithm);
            Assert.Equal(SshfpFingerprintType.SHA1, result.FingerprintType);
            Assert.Equal(fingerprint, result.Fingerprint);
        }

        [Fact]
        public void DnsRecordFactory_SpecialChars()
        {
            var textA = "\"äöü \\slash/! @bla.com \"";
            var textB = "(Another line)";
            var lineA = Encoding.UTF8.GetBytes(textA);
            var lineB = Encoding.UTF8.GetBytes(textB);
            var data = new List<byte>();
            data.Add((byte)lineA.Length);
            data.AddRange(lineA);
            data.Add((byte)lineB.Length);
            data.AddRange(lineB);

            var factory = GetFactory(data.ToArray());
            var info = new ResourceRecordInfo("query.example.com", ResourceRecordType.TXT, QueryClass.IN, 0, data.Count);

            var result = factory.GetRecord(info) as TxtRecord;

            Assert.Equal(2, result.EscapedText.Count);
            Assert.Equal(result.Text.ElementAt(0), textA);
            Assert.Equal("\\\"\\195\\164\\195\\182\\195\\188 \\\\slash/! @bla.com \\\"", result.EscapedText.ElementAt(0));
            Assert.Equal(result.Text.ElementAt(1), textB);
            Assert.Equal(result.EscapedText.ElementAt(1), textB);
        }

        [Fact]
        public void DnsRecordFactory_DnsKeyRecord()
        {
            var expectedPublicKey = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            var expectedBytes = Encoding.UTF8.GetBytes(expectedPublicKey);
            var name = DnsString.Parse("example.com");
            var writer = new DnsDatagramWriter();
            writer.WriteInt16NetworkOrder(256);
            writer.WriteByte(3);
            writer.WriteByte((byte)DnsSecurityAlgorithm.RSASHA256);
            writer.WriteBytes(expectedBytes, expectedBytes.Length);

            var factory = GetFactory(writer.Data);

            var info = new ResourceRecordInfo(name, ResourceRecordType.DNSKEY, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as DnsKeyRecord;
            Assert.Equal(expectedBytes, result.PublicKey);
            Assert.Equal(256, result.Flags);
            Assert.Equal(3, result.Protocol);
            Assert.Equal(DnsSecurityAlgorithm.RSASHA256, result.Algorithm);
        }

        [Fact]
        public void DnsRecordFactory_DsRecord()
        {
            var expectedDigest = "3490A6806D47F17A34C29E2CE80E8A999FFBE4BE";
            var expectedBytes = Enumerable.Range(0, expectedDigest.Length)
                     .Where(x => x % 2 == 0)
                     .Select(x => Convert.ToByte(expectedDigest.Substring(x, 2), 16))
                     .ToArray();

            var name = DnsString.Parse("example.com");
            var writer = new DnsDatagramWriter();
            writer.WriteInt16NetworkOrder(31589);
            writer.WriteByte(8); // algorithm
            writer.WriteByte(1); // type
            writer.WriteBytes(expectedBytes, expectedBytes.Length);

            var factory = GetFactory(writer.Data);

            var info = new ResourceRecordInfo(name, ResourceRecordType.DS, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as DsRecord;
            Assert.Equal(expectedBytes, result.Digest);
            Assert.Equal(expectedDigest, result.DigestAsString);
            Assert.Equal(31589, result.KeyTag);
            Assert.Equal(8, (int)result.Algorithm);
            Assert.Equal(1, result.DigestType);
        }

        [Fact]
        public void DnsRecordFactory_NSecRecord()
        {
            var expectedBitMap = new byte[] { 0, 7, 98, 1, 128, 8, 0, 3, 128 };
            var expectedTypes = new[]
            {
                ResourceRecordType.A,
                ResourceRecordType.NS,
                ResourceRecordType.SOA,
                ResourceRecordType.MX,
                ResourceRecordType.TXT,
                ResourceRecordType.AAAA,
                ResourceRecordType.RRSIG,
                ResourceRecordType.NSEC,
                ResourceRecordType.DNSKEY
            };

            var bitmap = NSecRecord.WriteBitmap(expectedTypes.Select(p => (ushort)p).ToArray()).ToArray();

            var name = DnsString.Parse("example.com");
            var writer = new DnsDatagramWriter();
            writer.WriteHostName(name);
            writer.WriteBytes(bitmap, bitmap.Length);

            var factory = GetFactory(writer.Data);

            var info = new ResourceRecordInfo(name, ResourceRecordType.NSEC, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as NSecRecord;
            Assert.Equal(expectedBitMap, bitmap);
            Assert.Equal(expectedBitMap, result.TypeBitMapsRaw);
            Assert.Equal(expectedTypes.Length, result.TypeBitMaps.Count);
            Assert.Equal(expectedTypes, result.TypeBitMaps);
            Assert.Equal(name, result.NextDomainName);
        }

        [Fact]
        public void DnsRecordFactory_NSec3Record()
        {
            var expectedTypes = new[]
            {
                ResourceRecordType.A,
                ResourceRecordType.NS,
                ResourceRecordType.SOA,
                ResourceRecordType.MX,
                ResourceRecordType.TXT,
                ResourceRecordType.AAAA,
                ResourceRecordType.RRSIG,
                ResourceRecordType.NSEC3PARAM
            };

            var expectedBitmap = NSecRecord.WriteBitmap(expectedTypes.Select(p => (ushort)p).ToArray()).ToArray();
            var salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            var nextName = Enumerable.Repeat(0, 50).Select((p, i) => (byte)i).ToArray();
            var nameEncoded = Base32Hex.ToBase32HexString(nextName);
            var name = DnsString.Parse("example.com");

            var writer = new DnsDatagramWriter();
            writer.WriteByte(1); // Algorithm
            writer.WriteByte(2); // Flags
            writer.WriteUInt16NetworkOrder(100); // Iterations
            writer.WriteByte((byte)salt.Length);
            writer.WriteBytes(salt, salt.Length);
            writer.WriteByte((byte)nextName.Length);
            writer.WriteBytes(nextName, nextName.Length);
            writer.WriteBytes(expectedBitmap, expectedBitmap.Length);

            var factory = GetFactory(writer.Data);

            var info = new ResourceRecordInfo(name, ResourceRecordType.NSEC3, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as NSec3Record;

            Assert.Equal(1, result.HashAlgorithm);
            Assert.Equal(2, result.Flags);
            Assert.Equal(100, result.Iterations);
            Assert.Equal(salt, result.Salt);
            Assert.Equal(nextName, result.NextOwnersName);
            Assert.Equal(nameEncoded, result.NextOwnersNameAsString);
            Assert.Equal(expectedTypes, result.TypeBitMaps);
        }

        [Fact]
        public void DnsRecordFactory_NSec3ParamRecord()
        {
            var salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            var name = DnsString.Parse("example.com");

            var writer = new DnsDatagramWriter();
            writer.WriteByte(1); // Algorithm
            writer.WriteByte(2); // Flags
            writer.WriteUInt16NetworkOrder(100); // Iterations
            writer.WriteByte((byte)salt.Length);
            writer.WriteBytes(salt, salt.Length);

            var factory = GetFactory(writer.Data);

            var info = new ResourceRecordInfo(name, ResourceRecordType.NSEC3PARAM, QueryClass.IN, 0, writer.Data.Count);

            var result = factory.GetRecord(info) as NSec3ParamRecord;

            Assert.Equal(1, result.HashAlgorithm);
            Assert.Equal(2, result.Flags);
            Assert.Equal(100, result.Iterations);
            Assert.Equal(salt, result.Salt);
        }

        [Fact]
        public void DnsRecord_TestBitmap_MaxWindows()
        {
            var data = Enumerable.Repeat(0, ushort.MaxValue).Select((v, i) => (ushort)i).ToArray();

            var bitmap = NSecRecord.WriteBitmap(data).ToArray();

            var result = NSecRecord.ReadBitmap(bitmap).OrderBy(p => p).Select(p => (ushort)p).ToArray();
            _ = NSecRecord.ReadBitmap(bitmap).OrderBy(p => p).Select(p => (ResourceRecordType)p).ToArray();

            Assert.Equal(data, result);
        }
    }
}


text:
var Promise = require('promise');

module.exports = function (a, b) {

	return new Promise(function (resolve, reject) {
		resolve(a + b);
	});
};


text:
package br.com.concretesolutions.audience.core.script;

public interface AssistantScript {}


text:
    require 'json'
    http = Net::HTTP.new('localhost', 8080)
    path = "/drools-server/knowledgebase/teamallocation"
    post_data = {"knowledgebase-request" => {
                  :globals => {"named-fact" => [{:id => "a", :fact => {"@class" => "teamallocation.Assignment"}}]},
                  :inFacts => {"anon-fact" => [{:fact => {"@class" => "teamallocation.Claim", "value" => 150}}]},
                  :inOutFacts => {"named-fact" => [{:id => "x", :fact => {"@class" => "teamallocation.Team", "specialty" => "FATAL"}},
                                                   {:id => "y", :fact => {"@class" => "teamallocation.Team"}}]}
                                            }
                 }
    headers = {
      "Content-Type" => "application/json"
    }
    resp, data = http.post(path, post_data.to_json, headers)

    answer = JSON.parse(data)
    #digging out the results:
    puts answer["knowledgebase-response"]["globals"]["named-fact"][0]["fact"]["teamName"]
    #if there is more then one fact, they are a list
    puts answer["knowledgebase-response"]["inOutFacts"]["named-fact"][0]["fact"]["specialty"]
    puts answer


text:
#region Using Statements
using System;
using System.Collections.Generic;

using Jitter.Dynamics;
using Jitter.LinearMath;
using Jitter.Collision.Shapes;
#endregion

namespace Jitter.Dynamics.Constraints
{

    #region Constraint Equations
    // Constraint formulation:
    //
    // C_1 = R1_x - R2_x
    // C_2 = ...
    // C_3 = ...
    //
    // Derivative:
    //
    // dC_1/dt = w1_x - w2_x
    // dC_2/dt = ...
    // dC_3/dt = ...
    //
    // Jacobian:
    //
    // dC/dt = J*v+b
    //
    // v = (v1x v1y v1z w1x w1y w1z v2x v2y v2z w2x w2y w2z)^(T)
    //
    //     v1x v1y v1z w1x w1y w1z v2x v2y v2z w2x w2y w2z
    //     -------------------------------------------------
    // J = 0   0   0   1   0    0   0   0   0   -1   0   0   <- dC_1/dt
    //     0   0   0   0   1    0   0   0   0    0  -1   0   <- ...
    //     0   0   0   0   0    1   0   0   0    0   0  -1   <- ...
    //
    // Effective Mass:
    //
    // 1/m_eff = [J^T * M^-1 * J] = I1^(-1) + I2^(-1)
    #endregion

    /// <summary>
    /// The AngleConstraint constraints two bodies to always have the same relative
    /// orientation to each other. Combine the AngleConstraint with a PointOnLine
    /// Constraint to get a prismatic joint.
    /// </summary>
    public class FixedAngle : Constraint
    {

        private float biasFactor = 0.05f;
        private float softness = 0.0f;

        private JVector accumulatedImpulse;

        private JMatrix initialOrientation1, initialOrientation2;

        /// <summary>
        /// Constraints two bodies to always have the same relative
        /// orientation to each other. Combine the AngleConstraint with a PointOnLine
        /// Constraint to get a prismatic joint.
        /// </summary>
        public FixedAngle(RigidBody body1, RigidBody body2) : base(body1, body2)
        {
            initialOrientation1 = body1.orientation;
            initialOrientation2 = body2.orientation;

            //orientationDifference = body1.orientation * body2.invOrientation;
            //orientationDifference = JMatrix.Transpose(orientationDifference);
        }

        public JVector AppliedImpulse { get { return accumulatedImpulse; } }

        public JMatrix InitialOrientationBody1 { get { return initialOrientation1; } set { initialOrientation1 = value; } }
        public JMatrix InitialOrientationBody2 { get { return initialOrientation2; } set { initialOrientation2 = value; } }

        /// <summary>
        /// Defines how big the applied impulses can get.
        /// </summary>
        public float Softness { get { return softness; } set { softness = value; } }

        /// <summary>
        /// Defines how big the applied impulses can get which correct errors.
        /// </summary>
        public float BiasFactor { get { return biasFactor; } set { biasFactor = value; } }

        JMatrix effectiveMass;
        JVector bias;
        float softnessOverDt;

        /// <summary>
        /// Called once before iteration starts.
        /// </summary>
        /// <param name="timestep">The 5simulation timestep</param>
        public override void PrepareForIteration(float timestep)
        {
            effectiveMass = body1.invInertiaWorld + body2.invInertiaWorld;

            softnessOverDt = softness / timestep;

            effectiveMass.M11 += softnessOverDt;
            effectiveMass.M22 += softnessOverDt;
            effectiveMass.M33 += softnessOverDt;

            JMatrix.Inverse(ref effectiveMass, out effectiveMass);

            JMatrix orientationDifference;
            JMatrix.Multiply(ref initialOrientation1, ref initialOrientation2, out orientationDifference);
            JMatrix.Transpose(ref orientationDifference, out orientationDifference);

            JMatrix q = orientationDifference * body2.invOrientation * body1.orientation;
            JVector axis;

            float x = q.M32 - q.M23;
            float y = q.M13 - q.M31;
            float z = q.M21 - q.M12;

            float r = JMath.Sqrt(x * x + y * y + z * z);
            float t = q.M11 + q.M22 + q.M33;

            float angle = (float)Math.Atan2(r, t - 1);
            axis = new JVector(x, y, z) * angle;

            if (r != 0.0f) axis = axis * (1.0f / r);

            bias = axis * biasFactor * (-1.0f / timestep);

            // Apply previous frame solution as initial guess for satisfying the constraint.
            if (!body1.IsStatic) body1.angularVelocity += JVector.Transform(accumulatedImpulse, body1.invInertiaWorld);
            if (!body2.IsStatic) body2.angularVelocity += JVector.Transform(-1.0f * accumulatedImpulse, body2.invInertiaWorld);
        }

        /// <summary>
        /// Iteratively solve this constraint.
        /// </summary>
        public override void Iterate()
        {
            JVector jv = body1.angularVelocity - body2.angularVelocity;

            JVector softnessVector = accumulatedImpulse * softnessOverDt;

            JVector lambda = -1.0f * JVector.Transform(jv+bias+softnessVector, effectiveMass);

            accumulatedImpulse += lambda;

            if(!body1.IsStatic) body1.angularVelocity += JVector.Transform(lambda, body1.invInertiaWorld);
            if(!body2.IsStatic) body2.angularVelocity += JVector.Transform(-1.0f * lambda, body2.invInertiaWorld);
        }

        /// <summary>
        /// This method is used to debug draw the constraints.
        /// </summary>
        /// <param name="lineList">A list of <see cref="JVector"/> to which lines (definied trough two points)
        /// are added.</param>
        /// <param name="pointList">A list of <see cref="JVector"/> defining points.</param>
        public override void AddToDebugDrawList(List<JVector> lineList, List<JVector> pointList)
        {
            // not used
        }
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/privacy/dlp/v2/storage.proto

namespace Google\Cloud\Dlp\V2;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Message for a unique key indicating a record that contains a finding.
 *
 * Generated from protobuf message google.privacy.dlp.v2.RecordKey
 */
class RecordKey extends \Google\Protobuf\Internal\Message
{
    protected $type;

    public function __construct() {
        \GPBMetadata\Google\Privacy\Dlp\V2\Storage::initOnce();
        parent::__construct();
    }

    /**
     * Generated from protobuf field .google.privacy.dlp.v2.DatastoreKey datastore_key = 2;
     * @return \Google\Cloud\Dlp\V2\DatastoreKey
     */
    public function getDatastoreKey()
    {
        return $this->readOneof(2);
    }

    /**
     * Generated from protobuf field .google.privacy.dlp.v2.DatastoreKey datastore_key = 2;
     * @param \Google\Cloud\Dlp\V2\DatastoreKey $var
     * @return $this
     */
    public function setDatastoreKey($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2\DatastoreKey::class);
        $this->writeOneof(2, $var);

        return $this;
    }

    /**
     * Generated from protobuf field .google.privacy.dlp.v2.BigQueryKey big_query_key = 3;
     * @return \Google\Cloud\Dlp\V2\BigQueryKey
     */
    public function getBigQueryKey()
    {
        return $this->readOneof(3);
    }

    /**
     * Generated from protobuf field .google.privacy.dlp.v2.BigQueryKey big_query_key = 3;
     * @param \Google\Cloud\Dlp\V2\BigQueryKey $var
     * @return $this
     */
    public function setBigQueryKey($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2\BigQueryKey::class);
        $this->writeOneof(3, $var);

        return $this;
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->whichOneof("type");
    }

}


text:
#ifndef dom_utils_hashtable_h_
#define dom_utils_hashtable_h_

#include <stdbool.h>
#include <dom/functypes.h>

typedef struct dom_hash_table dom_hash_table;

typedef struct dom_hash_vtable {
	uint32_t (*hash)(void *key, void *pw);
	void *(*clone_key)(void *key, void *pw);
	void (*destroy_key)(void *key, void *pw);
	void *(*clone_value)(void *value, void *pw);
	void (*destroy_value)(void *value, void *pw);
	bool (*key_isequal)(void *key1, void *key2, void *pw);
} dom_hash_vtable;

dom_hash_table *_dom_hash_create(unsigned int chains,
		const dom_hash_vtable *vtable, void *pw);
dom_hash_table *_dom_hash_clone(dom_hash_table *ht);
void _dom_hash_destroy(dom_hash_table *ht);
bool _dom_hash_add(dom_hash_table *ht, void *key, void *value,
		bool replace);
void *_dom_hash_get(dom_hash_table *ht, void *key);
void *_dom_hash_del(dom_hash_table *ht, void *key);
void *_dom_hash_iterate(dom_hash_table *ht, uintptr_t *c1, uintptr_t **c2);
uint32_t _dom_hash_get_length(dom_hash_table *ht);

#endif


text:
import os

import jobs
import settings

import flask

from flask import (
    flash,
    redirect,
    render_template,
    request,
    send_from_directory,
    url_for,
)

app = flask.Flask(__name__)
app.config.from_object(settings)

@app.context_processor
def available_jobs():
    """Make jobs available to templates through a context processor."""
    available_jobs = [jobs.Job(slug) for slug in settings.JOBS]
    return dict(jobs=available_jobs)

@app.errorhandler(404)
@app.route('/not-found')
def not_found(error=None):
    """Page not found."""
    return render_template('not_found.html'), 404

@app.route('/')
def index():
    """Jaime home."""
    return render_template('index.html')

@app.route('/job/<slug>/<instance_id>/logs/<filename>')
def output_file(slug, instance_id, filename):
    return send_from_directory(
        app.config['UPLOAD_FOLDER'],
        os.path.join(slug, instance_id, filename))

@app.route('/job/<slug>', methods=['GET', 'POST'])
def setup_new_instance(slug):
    """Set up a new job instance."""
    error = None

    try:
        job = jobs.Job(slug)
    except jobs.DoesNotExist:
        return redirect(url_for('not_found'))

    if request.method == 'POST':
        instance = jobs.Instance(job)
        compressed = request.files.get('compressed_file', None)
        if compressed:
            try:
                instance.setup_from_compressed_file(compressed)
            except Exception as e:
                error = str(e)
                instance.remove()
        elif job.individual_upload:
            uploaded_files = [f for f in request.files.values() if bool(f)]
            try:
                instance.setup_from_files(*uploaded_files)
            except Exception as e:
                error = str(e)
                instance.remove()
        else:
            error = 'Invalid job submission'

        if error is None:
            return redirect(
                url_for('run_output', instance_id=instance.id, slug=slug))

        flash(error, category='error')

    return render_template('detail.html', job=job)

@app.route('/job/<slug>/<instance_id>')
def run_output(slug, instance_id):
    """Run job instance and display output."""
    try:
        job = jobs.Job(slug)
        instance = job.get_instance(instance_id)
    except jobs.DoesNotExist:
        return redirect(url_for('not_found'))

    return_code = None
    refresh = request.args.get('refresh', None)

    if not instance.completed or refresh:
        timeout = getattr(settings, 'JOBS_TIMEOUT', None)
        return_code = instance.run(timeout=timeout)

    return render_template(
        'output.html', instance=instance, return_code=return_code)

if __name__ == '__main__':
    app.run(port=5000, host='0.0.0.0')


text:
/**
 * @fileoverview Entity collects a group of Components that define a game object and its behaviors
 *
 * @author Tony Parisi
 */
goog.provide('SB.Entity');
goog.require('SB.PubSub');

/**
 * Creates a new Entity.
 * @constructor
 * @extends {SB.PubSub}
 */
SB.Entity = function() {
    SB.PubSub.call(this);

    /**
     * @type {number}
     * @private
     */
    this._id = SB.Entity.nextId++;

    /**
     * @type {SB.Entity}
     * @private
     */
    this._parent = null;

    /**
     * @type {Array.<SB.Entity>}
     * @private
     */
    this._children = [];

    /**
     * @type {Array}
     * @private
     */
    this._components = [];

    /**
     * @type {Boolean}
     * @private
     */
    this._realized = false;
}

goog.inherits(SB.Entity, SB.PubSub);

/**
 * The next identifier to hand out.
 * @type {number}
 * @private
 */
SB.Entity.nextId = 0;

SB.Entity.prototype.getID = function() {
    return this._id;
}

//---------------------------------------------------------------------
// Hierarchy methods
//---------------------------------------------------------------------

/**
 * Sets the parent of the Entity.
 * @param {SB.Entity} parent The parent of the Entity.
 * @private
 */
SB.Entity.prototype.setParent = function(parent) {
    this._parent = parent;
}

/**
 * Adds a child to the Entity.
 * @param {SB.Entity} child The child to add.
 */
SB.Entity.prototype.addChild = function(child) {
    if (!child)
    {
        throw new Error('Cannot add a null child');
    }

    if (child._parent)
    {
        throw new Error('Child is already attached to an Entity');
    }

    child.setParent(this);
    this._children.push(child);

    if (this._realized && !child._realized)
    {
    	child.realize();
    }

}

/**
 * Removes a child from the Entity
 * @param {SB.Entity} child The child to remove.
 */
SB.Entity.prototype.removeChild = function(child) {
    var i = this._children.indexOf(child);

    if (i != -1)
    {
        this._children.splice(i, 1);
        child.setParent(null);
    }
}

/**
 * Removes a child from the Entity
 * @param {SB.Entity} child The child to remove.
 */
SB.Entity.prototype.getChild = function(index) {
	if (index >= this._children.length)
		return null;

	return this._children[index];
}

//---------------------------------------------------------------------
// Component methods
//---------------------------------------------------------------------

/**
 * Adds a Component to the Entity.
 * @param {SB.Component} component.
 */
SB.Entity.prototype.addComponent = function(component) {
    if (!component)
    {
        throw new Error('Cannot add a null component');
    }

    if (component._entity)
    {
        throw new Error('Component is already attached to an Entity')
    }

    if (component instanceof SB.Transform)
    {
    	if (this.transform != null && component != this.transform)
    	{
            throw new Error('Entity already has a Transform component')
    	}

    	this.transform = component;
    }

    this._components.push(component);
    component.setEntity(this);

    if (this._realized && !component._realized)
    {
    	component.realize();
    }
}

/**
 * Removes a Component from the Entity.
 * @param {SB.Component} component.
 */
SB.Entity.prototype.removeComponent = function(component) {
    var i = this._components.indexOf(component);

    if (i != -1)
    {
    	if (component.removeFromScene)
    	{
    		component.removeFromScene();
    	}

        this._components.splice(i, 1);
        component.setEntity(null);
    }
}

/**
 * Retrieves a Component of a given type in the Entity.
 * @param {Object} type.
 */
SB.Entity.prototype.getComponent = function(type) {
	var i, len = this._components.length;

	for (i = 0; i < len; i++)
	{
		var component = this._components[i];
		if (component instanceof type)
		{
			return component;
		}
	}

	return null;
}

/**
 * Retrieves a Component of a given type in the Entity.
 * @param {Object} type.
 */
SB.Entity.prototype.getComponents = function(type) {
	var i, len = this._components.length;

	var components = [];

	for (i = 0; i < len; i++)
	{
		var component = this._components[i];
		if (component instanceof type)
		{
			components.push(component);
		}
	}

	return components;
}

//---------------------------------------------------------------------
//Initialize methods
//---------------------------------------------------------------------

SB.Entity.prototype.realize = function() {
    this.realizeComponents();
    this.realizeChildren();

    this._realized = true;
}

/**
 * @private
 */
SB.Entity.prototype.realizeComponents = function() {
    var component;
    var count = this._components.length;
    var i = 0;

    for (; i < count; ++i)
    {
        this._components[i].realize();
    }
}

/**
 * @private
 */
SB.Entity.prototype.realizeChildren = function() {
    var child;
    var count = this._children.length;
    var i = 0;

    for (; i < count; ++i)
    {
        this._children[i].realize();
    }
}

//---------------------------------------------------------------------
// Update methods
//---------------------------------------------------------------------

SB.Entity.prototype.update = function() {
    this.handleMessages();
    this.updateComponents();
    this.updateChildren();
}

/**
 * @private
 */
SB.Entity.prototype.updateComponents = function() {
    var component;
    var count = this._components.length;
    var i = 0;

    for (; i < count; ++i)
    {
        this._components[i].update();
    }
}

/**
 * @private
 */
SB.Entity.prototype.updateChildren = function() {
    var child;
    var count = this._children.length;
    var i = 0;

    for (; i < count; ++i)
    {
        this._children[i].update();
    }
}


text:
/**
    @author Benjamin Livshits <livshits@cs.stanford.edu>

    $Id: Basic10.java,v 1.5 2006/04/04 20:00:40 livshits Exp $
 */
package securibench.micro.basic;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import securibench.micro.BasicTestCase;
import securibench.micro.MicroTestCase;

/**
 *  @servlet description="chains of value assignments"
 *  @servlet vuln_count = "1"
 *  */
public class Basic10 extends BasicTestCase implements MicroTestCase {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String s1 = req.getParameter("name");
        String s2 = s1;
        String s3 = s2;
        String s4 = s3;
        StringBuffer b1 = new StringBuffer(s4);
        //StringBuffer b2 = b1;
        StringBuffer b3 = b1;
        String s5 = b3.toString();
        String s6 = s5;

        PrintWriter writer = resp.getWriter();
        writer.println(s6);    /* BAD */
    }

    public String getDescription() {
        return "chains of value assignments";
    }

    public int getVulnerabilityCount() {
        return 1;
    }
}


text:
require 'test/test_helper'

## SimpleEngine
context do
  include SimpleRouter::Engines::SimpleEngine

  # matches static paths
  test do
    Base.match('/',    ['/', '/foo']).first.must == '/'
    Base.match('/foo', ['/', '/foo']).first.must == '/foo'
    Base.match('/bar', ['/', '/foo']).first.must == nil
  end

  # matches variable paths
  test do
    path, vars = Base.match('/80/07', ['/foo', '/:year/:month'])
    path.must == '/:year/:month'
    vars.must == ['80','07']
  end

  # matches hybrid paths
  test do
    path, vars = Base.match('/archives/80/07', ['/foo', '/archives/:year/:month'])
    path.must == '/archives/:year/:month'
    vars.must == ['80','07']
  end

  # ignores leading slash in path
  test do
    path, vars = Base.match('archives/80/07', ['/foo', '/archives/:year/:month'])
    path.must == '/archives/:year/:month'
    vars.must == ['80','07']
  end

  # no matches
  test do
    path, vars = Base.match('/80/07/01', ['/foo', '/:year/:month'])
    path.must == nil
    vars.must == []
  end

  # treats extension as pattern part
  test do
    path, vars = Base.match('/a/b.xml', ['/:foo/:bar', '/:foo/:bar.:type'])
    path.must == '/:foo/:bar.:type'
    vars.must == ['a','b','xml']
  end
end

## Pattern
context do
  include SimpleRouter::Engines::SimpleEngine

  # static pattern matches a path
  test do
    path    = Path.new('/foo/bar')
    pattern = Pattern.new('/foo/bar')

    assert { pattern == path }
  end

  # variable pattern matches a path
  test do
    path    = Path.new('/foo/bar')
    pattern = Pattern.new('/:foo/:bar')

    assert { pattern == path }
  end

  # pattern variables
  test do
    path    = Path.new('/foo/bar/baz')
    pattern = Pattern.new('/:a/:b/:c')

    assert { pattern == path }
    pattern.vars.must == %w( foo bar baz )
  end

  # pattern variables with extension
  test do
    path    = Path.new('/foo/bar/baz.xml')
    pattern = Pattern.new('/:a/:b/:c.:type')

    assert { pattern == path }
    pattern.vars.must == %w( foo bar baz xml )
  end

  # variable pattern matches a path with static extension
  test do
    path    = Path.new('/foo/bar.xml')
    pattern = Pattern.new('/:foo/:bar.xml')

    assert { pattern == path }
  end

  # variable pattern matches a path with variable extension
  test do
    path    = Path.new('/foo/bar.xml')
    pattern = Pattern.new('/:foo/:bar.:type')

    assert { pattern == path }
  end

  # pattern without extension doesn't match path with extension
  test do
    path    = Path.new('/foo/bar.xml')
    pattern = Pattern.new('/:foo/:bar')

    assert { pattern != path }
  end

  # pattern with static extension doesn't match path without extension
  test do
    path    = Path.new('/foo/bar')
    pattern = Pattern.new('/:foo/:bar.xml')

    assert { pattern != path }
  end

  # pattern with variable extension doesn't match path without extension
  test do
    path    = Path.new('/foo/bar')
    pattern = Pattern.new('/:foo/:bar.:type')

    assert { pattern != path }
  end

  # doesn't ignore dots in path parts
  test do
    path    = Path.new('/foo/bar.baz/abc')
    pattern = Pattern.new('/:a/:b/:c')

    assert { pattern == path }
    pattern.variables.must == %w( foo bar.baz abc )
  end

  # doesn't get confused with extension when path contains other dots
  test do
    path    = Path.new('/foo/bar.baz/abc.xml')
    pattern = Pattern.new('/:a/:b/:c.:type')

    assert { pattern == path }
    pattern.variables.must == %w( foo bar.baz abc xml )
  end
end


text:
var serviceName;
// Switch between the dev in-memory service and mongo service by
// setting env var MONGO=1 or mentioning "mongo" as on of the args
// ex (for bash/zsh): MONGO=1 npm start
// or (for fish): env MONGO=1 npm start
// or node bin/www mongo
// or node-debug bin/www mongo
var useMongoDb = process.env.MONGO ||                    // environment var
                 /~mongo/i.test(process.argv.join('~')); // launch argument

if (useMongoDb) {
    console.log('Using MongoDb database');
    serviceName = './mongoQuestionsService';
} else {
    console.log('Using in-memory database');
    serviceName = './memQuestionsService';
}

module.exports = require(serviceName);


text:
NS_ASSUME_NONNULL_BEGIN

@class ZNGUser;
@class ZNGUserV2;

@interface ZNGUserClient : ZNGBaseClientAccount

- (void) userWithId:(NSString *)userId
            success:(void (^)(ZNGUser* user, ZNGStatus* status))success
            failure:(void (^)(ZNGError* error))failure;

- (void) getAllUsersInServiceId:(NSString *)serviceId
                        success:(void (^)(NSArray<ZNGUserV2 *> * users))success
                        failure:(void (^ _Nullable)(ZNGError * error))failure;

#pragma mark - Avatars
- (void) deleteAvatarForUserWithId:(NSString *)userId
                           success:(void (^ _Nullable)(void))success
                           failure:(void (^ _Nullable)(ZNGError * error))failure;

- (void) uploadAvatar:(UIImage *)avatarImage
        forUserWithId:(NSString *)userId
              success:(void (^ _Nullable)(void))success
              failure:(void (^ _Nullable)(ZNGError * error))failure;

NS_ASSUME_NONNULL_END

@end


text:
package hex.generic;

import hex.ModelBuilder;
import hex.ModelCategory;
import hex.genmodel.ModelMojoReader;
import hex.genmodel.MojoModel;
import hex.genmodel.MojoReaderBackend;
import hex.genmodel.MojoReaderBackendFactory;
import water.H2O;
import water.Key;
import water.fvec.ByteVec;
import water.fvec.Frame;
import water.util.Log;

import java.io.IOException;
import java.util.*;

/**
 * Generic model able to do scoring with any underlying model deserializable into a format known by the {@link GenericModel}.
 * Only H2O Mojos are currently supported.
 */
public class Generic extends ModelBuilder<GenericModel, GenericModelParameters, GenericModelOutput> {

    /**
     * Unmodifiable {@link Set} of Algorithm MOJOs which are allowed to be imported as generic model
     */
    private static final Set<String> ALLOWED_MOJO_ALGOS;
    static{
        final Set<String> allowedAlgos = new HashSet<>(6);
        allowedAlgos.add("gbm");
        allowedAlgos.add("glm");
        allowedAlgos.add("xgboost");
        allowedAlgos.add("isolationforest");
        allowedAlgos.add("drf");
        allowedAlgos.add("deeplearning");
        allowedAlgos.add("stackedensemble");
        allowedAlgos.add("coxph");

        ALLOWED_MOJO_ALGOS = Collections.unmodifiableSet(allowedAlgos);
    }

    public Generic(GenericModelParameters genericParameters){
        super(genericParameters);
        init(false);
    }

    public Generic(boolean startup_once) {
        super(new GenericModelParameters(), startup_once);
    }

    @Override
    protected Driver trainModelImpl() {
        return new MojoDelegatingModelDriver();
    }

    @Override
    public ModelCategory[] can_build() {
        return ModelCategory.values();
    }

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

    @Override
    public boolean isSupervised() {
        return false;
    }

    class MojoDelegatingModelDriver extends Driver {

        @Override
        public void compute2() {
            if (_parms._path != null) { // If there is a file to be imported, do the import before the scope is entered
                _parms._model_key = importFile();
            }
            super.compute2();
        }

        @Override
        public void computeImpl() {
            final Key<Frame> dataKey;
            if (_parms._model_key != null) {
                dataKey = _parms._model_key;
            } else {
                throw new IllegalArgumentException("Either MOJO zip path or key to the uploaded MOJO frame must be specified");
            }
            final ByteVec mojoBytes = getUploadedMojo(dataKey);
            final MojoModel mojoModel;
            try {
                final MojoReaderBackend readerBackend = MojoReaderBackendFactory.createReaderBackend(mojoBytes.openStream(_job._key), MojoReaderBackendFactory.CachingStrategy.MEMORY);
                mojoModel = ModelMojoReader.readFrom(readerBackend, true);

                if(! ALLOWED_MOJO_ALGOS.contains(mojoModel._modelDescriptor.algoName().toLowerCase())) {
                    if (_parms._disable_algo_check)
                        Log.warn(String.format("MOJO model '%s' is not supported but user disabled white-list check. Trying to load anyway.", mojoModel._modelDescriptor.algoName()));
                    else
                        throw new IllegalArgumentException(String.format("Unsupported MOJO model '%s'. ", mojoModel._modelDescriptor.algoName()));
                }

                final GenericModelOutput genericModelOutput = new GenericModelOutput(mojoModel._modelDescriptor, mojoModel._modelAttributes, mojoModel._reproducibilityInformation);
                final GenericModel genericModel = new GenericModel(_result, _parms, genericModelOutput, mojoModel, dataKey);

                genericModel.write_lock(_job);
                genericModel.unlock(_job);
            } catch (IOException e) {
                throw new IllegalStateException("Unreachable MOJO file: " + dataKey, e);
            }
        }
    }

    private Key<Frame> importFile() {
        ArrayList<String> files = new ArrayList<>();
        ArrayList<String> keys = new ArrayList<>();
        ArrayList<String> fails = new ArrayList<>();
        ArrayList<String> dels = new ArrayList<>();
        H2O.getPM().importFiles(_parms._path, null, files, keys, fails, dels);
        if (!fails.isEmpty()) {
            throw new RuntimeException("Failed to import file: " + Arrays.toString(fails.toArray()));
        }
        assert keys.size() == 1;
        return Key.make(keys.get(0));
    }

    /**
     * Retrieves pre-uploaded MOJO archive and performs basic verifications, if present.
     *
     * @param key Key to MOJO bytes in DKV
     * @return An instance of {@link ByteVec} containing the bytes of an uploaded MOJO, if present. Or exception. Never returns null.
     * @throws IllegalArgumentException In case the supplied key is invalid (MOJO missing, empty key etc.)
     */
    private ByteVec getUploadedMojo(final Key<Frame> key) throws IllegalArgumentException {
        Objects.requireNonNull(key); // Nicer null pointer exception in case null key is accidentally provided

        Frame mojoFrame = key.get();
        if (mojoFrame.numCols() > 1)
            throw new IllegalArgumentException(String.format("Given MOJO frame with key '%s' should contain only 1 column with MOJO bytes. More columns found. Incorrect key provided ?", key));
        ByteVec mojoData = (ByteVec) mojoFrame.anyVec();

        if (mojoData.length() < 1)
            throw new IllegalArgumentException(String.format("Given MOJO frame with key '%s' is empty (0 bytes). Please provide a non-empty MOJO file.", key));

        return mojoData;
    }

    @Override
    public BuilderVisibility builderVisibility() {
        return BuilderVisibility.Stable;
    }

    /**
     * Convenience method for importing MOJO into H2O.
     *
     * @param location absolute path to MOJO file
     * @param disableAlgoCheck if true skip the check of white-listed MOJO models, use at your own risk - some features might not work.
     * @return instance of H2O Model wrapping a MOJO
     */
    public static GenericModel importMojoModel(String location, boolean disableAlgoCheck) {
        GenericModelParameters p = new GenericModelParameters();
        p._path = location;
        p._disable_algo_check = disableAlgoCheck;
        return new Generic(p).trainModel().get();
    }

}


text:
class CreateForums < ActiveRecord::Migration
  def self.up
    create_table :forums do |t|
      t.string :name
      t.string :description
      t.timestamps
    end
  end

  def self.down
    drop_table :forums
  end
end


text:
if (IsTurboCRM()) {
    // Show page action
    chrome.extension.sendMessage({showAction:1,profilerOn:(1 == $.cookie('cookie_profiler_on') ? 1:0)}, function(response){
        console.log('TurboCRM Profiler plugin activated !');
    });
    // Add listener for page action clicks
    chrome.extension.onMessage.addListener(function(request,sender,sendResponse){
        if (1 == request.toggleProfiler) {
            // Toggle profiler
            console.log('Start to toggle profiler.');
            $.cookie('cookie_profiler_on', 1 == $.cookie('cookie_profiler_on') ? 0:1);
            // Set settings into cookies
            var profilerOn = $.cookie('cookie_profiler_on');
            var msg = '';
            if (1 == profilerOn) {
                chrome.extension.sendMessage({getSettings:1}, function(response){
                    UpdateCookies(response.settings);
                });
                msg = 'TurboCRM Profiler is on now.';
            } else {
                msg = 'TurboCRM Profiler is off now.';
            }
            console.log(msg);
            sendResponse({profilerOn:profilerOn,msg:msg});
        } else if (1 == request.updateCookies) {
            UpdateCookies(request.settings);
            sendResponse({msg:'Cookies updated !'});
        }
    });
}

/*
 * Whether to turn the profiler on
 */
function IsTurboCRM() {
    return document.title.indexOf('TurboCRM') > 0 && $.cookie('PHPSESSID').length > 0;
}

/*
 * Set cookies
 */
function UpdateCookies(settings) {
    for ( var key in settings ) {
        if (key.indexOf('cookie') === 0) {
            $.cookie(key, settings[key]);
        }
    }
}


text:
import template from 'templates/item';

export default Marionette.View.extend({
    tagName: 'tr',
    template: template,

    initialize() {
        if (this.model.get('isLeader')) {
            this.$el.addClass('table-info');
        } else if (this.model.get('isOutsider')) {
            this.$el.addClass('table-danger');
        }
    }
});


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

namespace RogueSharp.Algorithms
{
   /// <summary>
   /// The DepthFirstPaths class represents a data type for finding paths from a source vertex to
   /// every other vertex in an undirected graph using depth-first search.
   /// </summary>
   /// <seealso href="http://algs4.cs.princeton.edu/41undirected/DepthFirstPaths.java.html">DepthFirstPaths class from Princeton University's Java Algorithms</seealso>
   public class DepthFirstPaths
   {
      private readonly int[] _edgeTo;
      private readonly bool[] _marked;
      private readonly int _sourceVertex;

      /// <summary>
      /// Computes a path between the specified sourceVertex and every other vertex in the Graph
      /// </summary>
      /// <param name="graph">The Graph</param>
      /// <param name="sourceVertex">The source vertex to compute a path from</param>
      /// <exception cref="ArgumentException">Thrown on null or invalid Graph</exception>
      public DepthFirstPaths( Graph graph, int sourceVertex )
      {
         if ( graph == null || graph.NumberOfVertices < 0 )
         {
            throw new ArgumentException( "Invalid Graph", "graph" );
         }

         _sourceVertex = sourceVertex;
         _edgeTo = new int[graph.NumberOfVertices];
         _marked = new bool[graph.NumberOfVertices];
         DepthFirstSeach( graph, sourceVertex );
      }

      private void DepthFirstSeach( Graph graph, int sourceVertex )
      {
         _marked[sourceVertex] = true;
         foreach ( int vertex in graph.Adjacent( sourceVertex ) )
         {
            if ( !_marked[vertex] )
            {
               _edgeTo[vertex] = sourceVertex;
               DepthFirstSeach( graph, vertex );
            }
         }
      }

      /// <summary>
      /// Is there a path between the sourceVertex and the specified destinationVertex?
      /// </summary>
      /// <param name="destinationVertex">The destination vertex</param>
      /// <returns>True if there is a path between the sourceVertex and the specified destinationVertex, false otherwise</returns>
      public bool HasPathTo( int destinationVertex )
      {
         return _marked[destinationVertex];
      }

      /// <summary>
      /// Returns a path between the sourceVertex and the specified destinationVertex or null if no such path exists
      /// </summary>
      /// <param name="destinationVertex">The destination vertex</param>
      /// <returns>An IEnumerable sequence of vertices representing the path between the sourceVertex and the specified destinationVertex or null if no such path exists</returns>
      public IEnumerable<int> PathTo( int destinationVertex )
      {
         if ( !HasPathTo( destinationVertex ) )
         {
            return null;
         }
         var path = new Stack<int>();
         for ( int x = destinationVertex; x != _sourceVertex; x = _edgeTo[x] )
         {
            path.Push( x );
         }
         return path;
      }
   }
}


text:
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using Afnor.Silverlight.Toolkit.ViewModels;
using System.Collections.ObjectModel;

namespace Afnor.Silverlight.Toolkit.Tests.ViewModels.TestViewModels
{
    public class ParentNestedObservableCollectionOfViewModel : ISupportCommitRollbackTrackable
    {
        private string _property;
        private ObservableCollection<ChildNestedViewModel> _children;

        [TrackProperty(TrackType.Track)]
        public string Property
        {
            get
            {
                return _property;
            }

            set
            {
                if (_property != value)
                {
                    _property = value;
                    NotifyPropertyChanged("Property");
                }
            }
        }

        [TrackProperty(TrackType.Track)]
        public ObservableCollection<ChildNestedViewModel> Children
        {
            get
            {
                return _children;
            }

            set
            {
                if (_children != value)
                {
                    _children = value;
                    NotifyPropertyChanged("Children");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        public ICommand CommitCommand
        {
            get { return null; }
        }

        public void Commit()
        {
            throw new NotImplementedException();
        }

        public ICommand RollbackCommand
        {
            get { return null; }
        }

        public void Rollback()
        {
            throw new NotImplementedException();
        }

        public bool IsDirty
        {
            get;
            set;
        }

        public IChangeTracker ChangeTracker
        {
            get { throw new NotImplementedException(); }
        }
    }
}


text:
<?php
namespace Picamator\SteganographyKit\Tests\Unit;

use PHPUnit\Framework\TestCase;
use Picamator\SteganographyKit\InvalidArgumentException;
use Picamator\SteganographyKit\ObjectManager\ObjectManager;

abstract class BaseTest extends TestCase
{

    /**
     * Path to the data folder
     *
     * @var string
     */
    private $dataPath = '/data/';

    /**
     * Gets full path to data
     *
     * @param string $path
     *
     * @return string | boolean - full path or false if failed
     */
    protected function getDataPath($path)
    {
        return __DIR__ . $this->dataPath . $path;
    }

    /**
     * Stub object manager
     *
     * @param array $data
     *
     * @return \Picamator\SteganographyKit\ObjectManager\ObjectManagerInterface | \PHPUnit_Framework_MockObject_MockObject
     */
    protected function stubObjectManager(array $data)
    {
        $objectManager = $this->getMockBuilder('Picamator\SteganographyKit\ObjectManager\ObjectManagerInterface')
            ->getMock();
        ObjectManager::setInstance($objectManager);

        $objectManager->expects($this->any())
            ->method('create')
            ->willReturnCallback(function($className) use ($data) {
                if (!isset($data[$className])) {
                    throw new InvalidArgumentException(
                        sprintf('Undefined class name "%s"', $className)
                    );
                }

                if (!isset($data[$className]['object'])) {
                    throw new InvalidArgumentException('Invalid data structure. Required parameter "object" was not set.');
                }

                $arguments = isset($data[$className]['arguments']) ? $data[$className]['arguments'] : [];
                $objectMock = is_string($data[$className]['object'])
                    ? $this->getMockBuilder($data[$className]['object'])
                        ->setConstructorArgs($arguments)
                        ->getMock()
                    : $data[$className]['object'];

                return $objectMock;
            });
    }
}


text:
using System.Collections.Generic;
using AutoMapper;
using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models;

namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery
{
    /// <summary>
    ///     Recovery services convenience client.
    /// </summary>
    public partial class PSRecoveryServicesClient
    {
        /// <summary>
        ///     Creates Azure Site Recovery Policy.
        /// </summary>
        /// <param name="policyName">Policy name</param>
        /// <param name="CreatePolicyInput">Policy Input</param>
        /// <returns>Long operation response</returns>
        public PSSiteRecoveryLongRunningOperation CreatePolicy(
            string policyName,
            CreatePolicyInput input)
        {
            var op = this.GetSiteRecoveryClient()
                .ReplicationPolicies.BeginCreateWithHttpMessagesAsync(
                    policyName,
                    input,
                    this.GetRequestHeaders(true))
                .GetAwaiter()
                .GetResult();
            var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op);
            return result;
        }

        /// <summary>
        ///     Deletes Azure Site Recovery Policy.
        /// </summary>
        /// <param name="createAndAssociatePolicyInput">Policy Input</param>
        /// <returns>Long operation response</returns>
        public PSSiteRecoveryLongRunningOperation DeletePolicy(
            string policyName)
        {
            var op = this.GetSiteRecoveryClient()
                .ReplicationPolicies.BeginDeleteWithHttpMessagesAsync(
                    policyName,
                    this.GetRequestHeaders(true))
                .GetAwaiter()
                .GetResult();
            var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op);
            return result;
        }

        /// <summary>
        ///     Gets Azure Site Recovery Policy.
        /// </summary>
        /// <returns>Policy list response</returns>
        public List<Policy> GetAzureSiteRecoveryPolicy()
        {
            var firstPage = this.GetSiteRecoveryClient()
                .ReplicationPolicies.ListWithHttpMessagesAsync(this.GetRequestHeaders(true))
                .GetAwaiter()
                .GetResult()
                .Body;
            var pages = Utilities.GetAllFurtherPages(
                this.GetSiteRecoveryClient()
                    .ReplicationPolicies.ListNextWithHttpMessagesAsync,
                firstPage.NextPageLink,
                this.GetRequestHeaders(true));
            pages.Insert(
                0,
                firstPage);

            return Utilities.IpageToList(pages);
        }

        /// <summary>
        ///     Gets Azure Site Recovery Policy given the ID.
        /// </summary>
        /// <param name="PolicyId">Policy Name</param>
        /// <returns>Policy response</returns>
        public Policy GetAzureSiteRecoveryPolicy(
            string PolicyName)
        {
            return this.GetSiteRecoveryClient()
                .ReplicationPolicies.GetWithHttpMessagesAsync(
                    PolicyName,
                    this.GetRequestHeaders(true))
                .GetAwaiter()
                .GetResult()
                .Body;
        }

        /// <summary>
        ///     Update Azure Site Recovery Policy.
        /// </summary>
        /// <param name="UpdatePolicyInput">Policy Input</param>
        /// <param name="policyName">Policy Name</param>
        /// <returns>Long operation response</returns>
        public PSSiteRecoveryLongRunningOperation UpdatePolicy(
            string policyName,
            UpdatePolicyInput input)
        {
            var op = this.GetSiteRecoveryClient()
                .ReplicationPolicies.BeginUpdateWithHttpMessagesAsync(
                    policyName,
                    input,
                    this.GetRequestHeaders(true))
                .GetAwaiter()
                .GetResult();
            var result = SiteRecoveryAutoMapperProfile.Mapper.Map<PSSiteRecoveryLongRunningOperation>(op);
            return result;
        }
    }
}


text:
FROM centos:centos7
MAINTAINER Sheroz Khaydarov "http://sheroz.com"

RUN yum -y update && yum -y --nogpgcheck install epel-release && yum clean all
RUN yum install -y gcc make && yum clean all

ENV	POSTGRES_VERSION=10.0 \
	POSTGRES_DOWNLOAD_SHA256=86c83a664b770114861bc96a9eca3c3efe28c0384c6a71c610426cd42b0164fb \
	POSTGRES_DOWNLOAD_MIRROR=https://ftp.postgresql.org/pub/source \
	POSTGRES_HOME=/opt/postgres

# RUN yum -y install tcl

RUN yum install -y readline-devel.x86_64 zlib-devel.x86_64 && \
mkdir -p /tmp/build && \
cd /tmp/build && \
curl -o postgresql.tar.gz "$POSTGRES_DOWNLOAD_MIRROR/v$POSTGRES_VERSION/postgresql-$POSTGRES_VERSION.tar.gz" && \
echo "$POSTGRES_DOWNLOAD_SHA256 postgresql.tar.gz" | sha256sum -c && \
mkdir postgresql && \
tar xzf postgresql.tar.gz -C postgresql --strip-components=1 && \
cd /tmp/build/postgresql && \
./configure -prefix=$POSTGRES_HOME/$POSTGRES_VERSION && \
make && \
make install && \
rm -rf /tmp/build && \
yum -y remove make gcc && \
rm -rf /var/cache/yum && \
yum clean all && \
groupadd -r postgres && \
useradd --no-log-init -r -g postgres postgres && \
mkdir -p $POSTGRES_HOME/$POSTGRES_VERSION/data && \
chown postgres $POSTGRES_HOME/$POSTGRES_VERSION/data

# RUN systemctl status firewalld

# open docker network interface on firewalld
# RUN firewall-cmd --permanent --zone=trusted --change-interface=docker0
# or disable firewalld

# RUN systemctl stop firewalld && \
# systemctl disable firewalld && \
# systemctl mask firewalld

USER postgres

# allow remote connections
RUN $POSTGRES_HOME/$POSTGRES_VERSION/bin/initdb -E UTF8 -D $POSTGRES_HOME/$POSTGRES_VERSION/data && \
echo "host all  all    0.0.0.0/0  trust" >> $POSTGRES_HOME/$POSTGRES_VERSION/data/pg_hba.conf && \
echo "listen_addresses='*'" >> $POSTGRES_HOME/$POSTGRES_VERSION/data/postgresql.conf

# add VOLUME
VOLUME  ["/opt/postgres/10.0"]
EXPOSE 5432

# default command to run on start
CMD ["/opt/postgres/10.0/bin/postgres", "-D", "/opt/postgres/10.0/data", "-c", "config_file=/opt/postgres/10.0/data/postgresql.conf"]

# docker build -t postgres:10 .
# docker run -p 5432:5432 --name postgres-10 -d postgres:10
# docker pull dpage/pgadmin4
# docker run -p 80:80 --name pgadmin --link postgres-10:postgres-10 -d dpage/pgadmin4

# PGADMIN_DEFAULT_EMAIL: container@pgadmin.org
# PGADMIN_DEFAULT_PASSWORD: Conta1ner


text:
    <meta name="pdfkit-orientation" content="Landscape"/>

Software Vulnerability Report

2015-03-03 15:42

Top Ten CVEs:

Top Ten Critically Vulnerable Packages:

Top Ten Non-Critically Vulnerable Packages:

Host Name: ip-10-197-117-50

Label: None

Group: AWS Servers

Software Vulnerability Assessment Summary:

Critical: 0

Non-critical: 0

Software Vulnerabilities:

Package	Version	Critical	CVEs

NO SOFTWARE VULNERABILITY RESULTS AVAILABLE


text:
import boto
import base64
import json
from datetime import datetime

def seconds_from_hours(hours):
    return hours * 60 * 60

def should_kill(instance):
    attributes = instance.get_attribute("userData")

    if attributes['userData'] == None:
        print "Instance has no userdata"
        return False

    user_data = base64.b64decode(attributes['userData'])

    try:
        data = json.loads(user_data)
    except ValueError:
        print "User Data isn't json"
        return False

    if not data.get("popfly"):
        print "No key popfly"
        return False

    if instance.state != "running":
        print "Instance isn't running"
        return False

    start = datetime.strptime(instance.launch_time, "%Y-%m-%dT%H:%M:%S.%fZ")
    end = datetime.utcnow()
    life = end - start

    print "Current {}".format(life.total_seconds())
    print "Machine {}".format(seconds_from_hours(data['duration']))

    return life.total_seconds() >= seconds_from_hours(data['duration'])

def kill(instance):
    instance.terminate()
    print "BOOM"

conn = boto.connect_ec2()
for reservation in conn.get_all_instances():
    for instance in reservation.instances:
        print "Checking {}".format(instance.id)
        if should_kill(instance):
            kill(instance)
            print "Killing {}".format(instance.id)
        else:
            print "Sparing {}".format(instance.id)


text:
'use strict';

//put this in its own seperate file becuase it is only validator shared by two schemas...
module.exports = function (val) {
  //accepts strings for now,
  //but in future will need to validate our recurring strings
  return (val instanceof String || val === null);
};


text:
using System.Collections.Generic;

namespace _09_Book_Library
{
    public class Library
    {
        public string Name { get; set; }
        public List<Book> Books { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Injection;
using Unity.Registration;
using Unity.Policy;
using Unity.Builder;

namespace Abmes.UnityExtensions
{
    internal interface IInjectionParameterizedFactory
    {
        Delegate FactoryFunc { get; }
        IEnumerable<ResolvedParameter> ResolvedParameters { get; }
    }

    public class InjectionParameterizedFactory : InjectionMember, IInjectionParameterizedFactory
    {
        private readonly Delegate _factoryFunc;
        private readonly IEnumerable<ResolvedParameter> _resolvedParameters;

        public InjectionParameterizedFactory(Delegate factoryFunc, params ResolvedParameter[] resolvedParameters)
        {
            _factoryFunc = factoryFunc;
            _resolvedParameters = resolvedParameters;
        }

        public Delegate FactoryFunc { get { return _factoryFunc; } }
        public IEnumerable<ResolvedParameter> ResolvedParameters { get { return _resolvedParameters; } }

        public override void AddPolicies(Type serviceType, Type implementationType, string name, IPolicyList policies)
        {
            if (implementationType == null)
            {
                throw new ArgumentNullException(nameof(implementationType));
            }

            if (policies == null)
            {
                throw new ArgumentNullException(nameof(policies));
            }

            var policy = new ParameterizedFactoryDelegateBuildPlanPolicy(_factoryFunc, _resolvedParameters.ToArray());
            policies.Set<IBuildPlanPolicy>(policy, new NamedTypeBuildKey(implementationType, name));
        }
    }
}


text:
package org.jboss.netty.example.localtime;

import static java.util.Calendar.*;

import java.util.Calendar;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.example.localtime.LocalTimeProtocol.Continent;
import org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek;
import org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime;
import org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes;
import org.jboss.netty.example.localtime.LocalTimeProtocol.Location;
import org.jboss.netty.example.localtime.LocalTimeProtocol.Locations;

public class LocalTimeServerHandler extends SimpleChannelUpstreamHandler {

    private static final Logger logger = Logger.getLogger(
            LocalTimeServerHandler.class.getName());

    @Override
    public void handleUpstream(
            ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
        if (e instanceof ChannelStateEvent) {
            logger.info(e.toString());
        }
        super.handleUpstream(ctx, e);
    }

    @Override
    public void messageReceived(
            ChannelHandlerContext ctx, MessageEvent e) {

        Locations locations = (Locations) e.getMessage();
        long currentTime = System.currentTimeMillis();

        LocalTimes.Builder builder = LocalTimes.newBuilder();
        for (Location l: locations.getLocationList()) {
            TimeZone tz = TimeZone.getTimeZone(
                    toString(l.getContinent()) + '/' + l.getCity());
            Calendar calendar = Calendar.getInstance(tz);
            calendar.setTimeInMillis(currentTime);

            builder.addLocalTime(LocalTime.newBuilder().
                    setYear(calendar.get(YEAR)).
                    setMonth(calendar.get(MONTH) + 1).
                    setDayOfMonth(calendar.get(DAY_OF_MONTH)).
                    setDayOfWeek(DayOfWeek.valueOf(calendar.get(DAY_OF_WEEK))).
                    setHour(calendar.get(HOUR_OF_DAY)).
                    setMinute(calendar.get(MINUTE)).
                    setSecond(calendar.get(SECOND)).build());
        }

        e.getChannel().write(builder.build());
    }

    @Override
    public void exceptionCaught(
            ChannelHandlerContext ctx, ExceptionEvent e) {
        logger.log(
                Level.WARNING,
                "Unexpected exception from downstream.",
                e.getCause());
        e.getChannel().close();
    }

    private static String toString(Continent c) {
        return "" + c.name().charAt(0) + c.name().toLowerCase().substring(1);
    }
}


text:
'use strict';
/**
 * @module TAP
 */
/**
 * Module dependencies.
 */

var util = require('util');
var Base = require('./base');
var constants = require('../runner').constants;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
var EVENT_RUN_END = constants.EVENT_RUN_END;
var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
var EVENT_TEST_END = constants.EVENT_TEST_END;
var inherits = require('../utils').inherits;
var sprintf = util.format;

/**
 * Expose `TAP`.
 */

exports = module.exports = TAP;

/**
 * Constructs a new `TAP` reporter instance.
 *
 * @public
 * @class
 * @memberof Mocha.reporters
 * @extends Mocha.reporters.Base
 * @param {Runner} runner - Instance triggers reporter actions.
 * @param {Object} [options] - runner options
 */
function TAP(runner, options) {
  Base.call(this, runner, options);

  var self = this;
  var n = 1;

  var tapVersion = '12';
  if (options && options.reporterOptions) {
    if (options.reporterOptions.tapVersion) {
      tapVersion = options.reporterOptions.tapVersion.toString();
    }
  }

  this._producer = createProducer(tapVersion);

  runner.once(EVENT_RUN_BEGIN, function () {
    self._producer.writeVersion();
  });

  runner.on(EVENT_TEST_END, function () {
    ++n;
  });

  runner.on(EVENT_TEST_PENDING, function (test) {
    self._producer.writePending(n, test);
  });

  runner.on(EVENT_TEST_PASS, function (test) {
    self._producer.writePass(n, test);
  });

  runner.on(EVENT_TEST_FAIL, function (test, err) {
    self._producer.writeFail(n, test, err);
  });

  runner.once(EVENT_RUN_END, function () {
    self._producer.writeEpilogue(runner.stats);
  });
}

/**
 * Inherit from `Base.prototype`.
 */
inherits(TAP, Base);

/**
 * Returns a TAP-safe title of `test`.
 *
 * @private
 * @param {Test} test - Test instance.
 * @return {String} title with any hash character removed
 */
function title(test) {
  return test.fullTitle().replace(/#/g, '');
}

/**
 * Writes newline-terminated formatted string to reporter output stream.
 *
 * @private
 * @param {string} format - `printf`-like format string
 * @param {...*} [varArgs] - Format string arguments
 */
function println(format, varArgs) {
  var vargs = Array.from(arguments);
  vargs[0] += '\n';
  process.stdout.write(sprintf.apply(null, vargs));
}

/**
 * Returns a `tapVersion`-appropriate TAP producer instance, if possible.
 *
 * @private
 * @param {string} tapVersion - Version of TAP specification to produce.
 * @returns {TAPProducer} specification-appropriate instance
 * @throws {Error} if specification version has no associated producer.
 */
function createProducer(tapVersion) {
  var producers = {
    12: new TAP12Producer(),
    13: new TAP13Producer()
  };
  var producer = producers[tapVersion];

  if (!producer) {
    throw new Error(
      'invalid or unsupported TAP version: ' + JSON.stringify(tapVersion)
    );
  }

  return producer;
}

/**
 * @summary
 * Constructs a new TAPProducer.
 *
 * @description
 * Only to be used as an abstract base class.
 *
 * @private
 * @constructor
 */
function TAPProducer() {}

/**
 * Writes the TAP version to reporter output stream.
 *
 * @abstract
 */
TAPProducer.prototype.writeVersion = function () {};

/**
 * Writes the plan to reporter output stream.
 *
 * @abstract
 * @param {number} ntests - Number of tests that are planned to run.
 */
TAPProducer.prototype.writePlan = function (ntests) {
  println('%d..%d', 1, ntests);
};

/**
 * Writes that test passed to reporter output stream.
 *
 * @abstract
 * @param {number} n - Index of test that passed.
 * @param {Test} test - Instance containing test information.
 */
TAPProducer.prototype.writePass = function (n, test) {
  println('ok %d %s', n, title(test));
};

/**
 * Writes that test was skipped to reporter output stream.
 *
 * @abstract
 * @param {number} n - Index of test that was skipped.
 * @param {Test} test - Instance containing test information.
 */
TAPProducer.prototype.writePending = function (n, test) {
  println('ok %d %s # SKIP -', n, title(test));
};

/**
 * Writes that test failed to reporter output stream.
 *
 * @abstract
 * @param {number} n - Index of test that failed.
 * @param {Test} test - Instance containing test information.
 * @param {Error} err - Reason the test failed.
 */
TAPProducer.prototype.writeFail = function (n, test, err) {
  println('not ok %d %s', n, title(test));
};

/**
 * Writes the summary epilogue to reporter output stream.
 *
 * @abstract
 * @param {Object} stats - Object containing run statistics.
 */
TAPProducer.prototype.writeEpilogue = function (stats) {
  // :TBD: Why is this not counting pending tests?
  println('# tests ' + (stats.passes + stats.failures));
  println('# pass ' + stats.passes);
  // :TBD: Why are we not showing pending results?
  println('# fail ' + stats.failures);
  this.writePlan(stats.passes + stats.failures + stats.pending);
};

/**
 * @summary
 * Constructs a new TAP12Producer.
 *
 * @description
 * Produces output conforming to the TAP12 specification.
 *
 * @private
 * @constructor
 * @extends TAPProducer
 * @see {@link https://testanything.org/tap-specification.html|Specification}
 */
function TAP12Producer() {
  /**
   * Writes that test failed to reporter output stream, with error formatting.
   * @override
   */
  this.writeFail = function (n, test, err) {
    TAPProducer.prototype.writeFail.call(this, n, test, err);
    if (err.message) {
      println(err.message.replace(/^/gm, '  '));
    }
    if (err.stack) {
      println(err.stack.replace(/^/gm, '  '));
    }
  };
}

/**
 * Inherit from `TAPProducer.prototype`.
 */
inherits(TAP12Producer, TAPProducer);

/**
 * @summary
 * Constructs a new TAP13Producer.
 *
 * @description
 * Produces output conforming to the TAP13 specification.
 *
 * @private
 * @constructor
 * @extends TAPProducer
 * @see {@link https://testanything.org/tap-version-13-specification.html|Specification}
 */
function TAP13Producer() {
  /**
   * Writes the TAP version to reporter output stream.
   * @override
   */
  this.writeVersion = function () {
    println('TAP version 13');
  };

  /**
   * Writes that test failed to reporter output stream, with error formatting.
   * @override
   */
  this.writeFail = function (n, test, err) {
    TAPProducer.prototype.writeFail.call(this, n, test, err);
    var emitYamlBlock = err.message != null || err.stack != null;
    if (emitYamlBlock) {
      println(indent(1) + '---');
      if (err.message) {
        println(indent(2) + 'message: |-');
        println(err.message.replace(/^/gm, indent(3)));
      }
      if (err.stack) {
        println(indent(2) + 'stack: |-');
        println(err.stack.replace(/^/gm, indent(3)));
      }
      println(indent(1) + '...');
    }
  };

  function indent(level) {
    return Array(level + 1).join('  ');
  }
}

/**
 * Inherit from `TAPProducer.prototype`.
 */
inherits(TAP13Producer, TAPProducer);

TAP.description = 'TAP-compatible output';


text:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms'

import { AppComponent } from './app.component';
import { ValidatorModule } from '../../modules/validator.module';
import { ButtonModule } from '../../modules/button.module';
import { CheckBoxModule } from '../../modules/checkbox.module';
import { DateTimeInputModule } from '../../modules/datetimeinput.module';
import { ExpanderModule } from '../../modules/expander.module';
import { InputModule } from '../../modules/input.module';
import { MaskedInputModule } from '../../modules/maskedinput.module';
import { PasswordInputModule } from '../../modules/passwordinput.module';

@NgModule({
  declarations: [
      AppComponent
  ],
  imports: [
      BrowserModule, CommonModule, FormsModule, ValidatorModule, ButtonModule, CheckBoxModule,
	  DateTimeInputModule, ExpanderModule, InputModule, MaskedInputModule, PasswordInputModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }


text:
set -e pipefail

mkdir -p tmp-projects
cd tmp-projects
echo '{}' > package.json
npm install react-native-cli@2.0.1 --save
./node_modules/.bin/react-native init --version="react-native@0.61.5" MyProject61
cd MyProject61
npm install ../../bugsnag-react-native-*.tgz --save
cd ios
pod install

xcodebuild -workspace MyProject61.xcworkspace \
           -scheme MyProject61 build \
           -sdk iphonesimulator -quiet


text:
 UM FRAMEWORK PARA AVALIAR MÉTRICAS

 Kaner e Bond em um artigo para o "10th International Software Metrics Symposium", de 2004, descrevem um framework para avaliar uma métrica de software, e ajudar a definir melhor uma métrica, e o seu uso no projeto. Foram definidos 10 pontos baseados no critério de métrica de software do IEEE Padrão 1061. São eles:

Qual o propósito da medida?

            Ajuda a entender os riscos associados a um medição, de modo a determinar o quanto deve ser investido em assegurar sua validação. Quanto maior o risco associado a uma medição, mais importante é a sua validação.

Qual o escopo da medida?

           Abrange um desenvolvedor ou a equipe? Ou múltiplas partes do projeto? Escopos muito grandes podem incluir variáveis que confundam a medição, potencialmente impactando ou invalidando a métrica. Uma métrica que funciona bem localmente pode não se sustentar <globalmente class=""></globalmente>

Qual atributo do software está sendo medido?

Um ideia pouco aprimorada do que se deseja medir, irá resultar em medidas com relação pouco clara ao que você deseja medir.

Qual a escala natural do atributo que tentamos medir?

Que tipo de escala pode ser usada para a medição de habilidade de programação, ou ao rigor dos testes, ao tamanho do software, etc.?

Qual a variabilidade natural do atributo?

Quais números são esperados da medição?

Qual instrumento de medição deve ser utilizado?

Será utilizado algum software de apoio, função, ferramenta de trabalho, etc.?

Qual a escala natural dessa métrica?

muitas das medições, espera-se ter tirar conclusões comparativas dos resultado. Por isso, normalmente, espera-se que a escala das métricas seja ordinal.

Qual a variabilidade natural de leituras vinda do instrumento?

Pequenas variações são esperadas? Ou até a menor alteração indica que uma grande melhoria foi alcançada?

Qual a relação entre o atributo e o valor da métrica?

Essa é a questão da "validade de construção". Como saber se uma métrica mede tal atributo?

Quais os efeitos colaterais naturais e previsíveis da utilização desse instrumento?

Para uma métrica utilizada, os efeitos de escrever o código da maneira indicada, irão melhorar essa métrica da maneira que esperamos? Uma melhoria na métrica deve indicar uma melhoria na qualidade do código, caso contrário, há alguma coisa que a métrica não está evidenciando.