text:
// CanvasContextWebGL.cs
// Script#/Libraries/Web
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
// Added by Delta Engine for Web Support - see http://deltaengine.net
//

using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Html.Media.Graphics.WebGL;

namespace System.Html.Media.Graphics
{
	[IgnoreNamespace]
	[Imported]
	// ReSharper disable InconsistentNaming
	public sealed class CanvasContextWebGL : CanvasContext
	{
		private CanvasContextWebGL()
		{
		}

		[PreserveCase] public readonly int DEPTH_BUFFER_BIT = 0x00000100;
		[PreserveCase] public readonly int STENCIL_BUFFER_BIT = 0x00000400;
		[PreserveCase] public readonly int COLOR_BUFFER_BIT = 0x00004000;
		[PreserveCase] public readonly int POINTS = 0x0000;
		[PreserveCase] public readonly int LINES = 0x0001;
		[PreserveCase] public readonly int LINE_LOOP = 0x0002;
		[PreserveCase] public readonly int LINE_STRIP = 0x0003;
		[PreserveCase] public readonly int TRIANGLES = 0x0004;
		[PreserveCase] public readonly int TRIANGLE_STRIP = 0x0005;
		[PreserveCase] public readonly int TRIANGLE_FAN = 0x0006;
		[PreserveCase] public readonly int ZERO = 0;
		[PreserveCase] public readonly int ONE = 1;
		[PreserveCase] public readonly int SRC_COLOR = 0x0300;
		[PreserveCase] public readonly int ONE_MINUS_SRC_COLOR = 0x0301;
		[PreserveCase] public readonly int SRC_ALPHA = 0x0302;
		[PreserveCase] public readonly int ONE_MINUS_SRC_ALPHA = 0x0303;
		[PreserveCase] public readonly int DST_ALPHA = 0x0304;
		[PreserveCase] public readonly int ONE_MINUS_DST_ALPHA = 0x0305;
		[PreserveCase] public readonly int DST_COLOR = 0x0306;
		[PreserveCase] public readonly int ONE_MINUS_DST_COLOR = 0x0307;
		[PreserveCase] public readonly int SRC_ALPHA_SATURATE = 0x0308;
		[PreserveCase] public readonly int FUNC_ADD = 0x8006;
		[PreserveCase] public readonly int BLEND_EQUATION = 0x8009;
		[PreserveCase] public readonly int BLEND_EQUATION_RGB = 0x8009 /* same as BLEND_EQUATION */;
		[PreserveCase] public readonly int BLEND_EQUATION_ALPHA = 0x883D;
		[PreserveCase] public readonly int FUNC_SUBTRACT = 0x800A;
		[PreserveCase] public readonly int FUNC_REVERSE_SUBTRACT = 0x800B;
		[PreserveCase] public readonly int BLEND_DST_RGB = 0x80C8;
		[PreserveCase] public readonly int BLEND_SRC_RGB = 0x80C9;
		[PreserveCase] public readonly int BLEND_DST_ALPHA = 0x80CA;
		[PreserveCase] public readonly int BLEND_SRC_ALPHA = 0x80CB;
		[PreserveCase] public readonly int CONSTANT_COLOR = 0x8001;
		[PreserveCase] public readonly int ONE_MINUS_CONSTANT_COLOR = 0x8002;
		[PreserveCase] public readonly int CONSTANT_ALPHA = 0x8003;
		[PreserveCase] public readonly int ONE_MINUS_CONSTANT_ALPHA = 0x8004;
		[PreserveCase] public readonly int BLEND_COLOR = 0x8005;
		[PreserveCase] public readonly int ARRAY_BUFFER = 0x8892;
		[PreserveCase] public readonly int ELEMENT_ARRAY_BUFFER = 0x8893;
		[PreserveCase] public readonly int ARRAY_BUFFER_BINDING = 0x8894;
		[PreserveCase] public readonly int ELEMENT_ARRAY_BUFFER_BINDING = 0x8895;
		[PreserveCase] public readonly int STREAM_DRAW = 0x88E0;
		[PreserveCase] public readonly int STATIC_DRAW = 0x88E4;
		[PreserveCase] public readonly int DYNAMIC_DRAW = 0x88E8;
		[PreserveCase] public readonly int BUFFER_SIZE = 0x8764;
		[PreserveCase] public readonly int BUFFER_USAGE = 0x8765;
		[PreserveCase] public readonly int CURRENT_VERTEX_ATTRIB = 0x8626;
		[PreserveCase] public readonly int FRONT = 0x0404;
		[PreserveCase] public readonly int BACK = 0x0405;
		[PreserveCase] public readonly int FRONT_AND_BACK = 0x0408;
		[PreserveCase] public readonly int CULL_FACE = 0x0B44;
		[PreserveCase] public readonly int BLEND = 0x0BE2;
		[PreserveCase] public readonly int DITHER = 0x0BD0;
		[PreserveCase] public readonly int STENCIL_TEST = 0x0B90;
		[PreserveCase] public readonly int DEPTH_TEST = 0x0B71;
		[PreserveCase] public readonly int SCISSOR_TEST = 0x0C11;
		[PreserveCase] public readonly int POLYGON_OFFSET_FILL = 0x8037;
		[PreserveCase] public readonly int SAMPLE_ALPHA_TO_COVERAGE = 0x809E;
		[PreserveCase] public readonly int SAMPLE_COVERAGE = 0x80A0;
		[PreserveCase] public readonly int NO_ERROR = 0;
		[PreserveCase] public readonly int INVALID_ENUM = 0x0500;
		[PreserveCase] public readonly int INVALID_VALUE = 0x0501;
		[PreserveCase] public readonly int INVALID_OPERATION = 0x0502;
		[PreserveCase] public readonly int OUT_OF_MEMORY = 0x0505;
		[PreserveCase] public readonly int CW = 0x0900;
		[PreserveCase] public readonly int CCW = 0x0901;
		[PreserveCase] public readonly int LINE_WIDTH = 0x0B21;
		[PreserveCase] public readonly int ALIASED_POINT_SIZE_RANGE = 0x846D;
		[PreserveCase] public readonly int ALIASED_LINE_WIDTH_RANGE = 0x846E;
		[PreserveCase] public readonly int CULL_FACE_MODE = 0x0B45;
		[PreserveCase] public readonly int FRONT_FACE = 0x0B46;
		[PreserveCase] public readonly int DEPTH_RANGE = 0x0B70;
		[PreserveCase] public readonly int DEPTH_WRITEMASK = 0x0B72;
		[PreserveCase] public readonly int DEPTH_CLEAR_VALUE = 0x0B73;
		[PreserveCase] public readonly int DEPTH_FUNC = 0x0B74;
		[PreserveCase] public readonly int STENCIL_CLEAR_VALUE = 0x0B91;
		[PreserveCase] public readonly int STENCIL_FUNC = 0x0B92;
		[PreserveCase] public readonly int STENCIL_FAIL = 0x0B94;
		[PreserveCase] public readonly int STENCIL_PASS_DEPTH_FAIL = 0x0B95;
		[PreserveCase] public readonly int STENCIL_PASS_DEPTH_PASS = 0x0B96;
		[PreserveCase] public readonly int STENCIL_value = 0x0B97;
		[PreserveCase] public readonly int STENCIL_VALUE_MASK = 0x0B93;
		[PreserveCase] public readonly int STENCIL_WRITEMASK = 0x0B98;
		[PreserveCase] public readonly int STENCIL_BACK_FUNC = 0x8800;
		[PreserveCase] public readonly int STENCIL_BACK_FAIL = 0x8801;
		[PreserveCase] public readonly int STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802;
		[PreserveCase] public readonly int STENCIL_BACK_PASS_DEPTH_PASS = 0x8803;
		[PreserveCase] public readonly int STENCIL_BACK_value = 0x8CA3;
		[PreserveCase] public readonly int STENCIL_BACK_VALUE_MASK = 0x8CA4;
		[PreserveCase] public readonly int STENCIL_BACK_WRITEMASK = 0x8CA5;
		[PreserveCase] public readonly int VIEWPORT = 0x0BA2;
		[PreserveCase] public readonly int SCISSOR_BOX = 0x0C10;
		[PreserveCase] public readonly int COLOR_CLEAR_VALUE = 0x0C22;
		[PreserveCase] public readonly int COLOR_WRITEMASK = 0x0C23;
		[PreserveCase] public readonly int UNPACK_ALIGNMENT = 0x0CF5;
		[PreserveCase] public readonly int PACK_ALIGNMENT = 0x0D05;
		[PreserveCase] public readonly int MAX_TEXTURE_SIZE = 0x0D33;
		[PreserveCase] public readonly int MAX_VIEWPORT_DIMS = 0x0D3A;
		[PreserveCase] public readonly int SUBPIXEL_BITS = 0x0D50;
		[PreserveCase] public readonly int RED_BITS = 0x0D52;
		[PreserveCase] public readonly int GREEN_BITS = 0x0D53;
		[PreserveCase] public readonly int BLUE_BITS = 0x0D54;
		[PreserveCase] public readonly int ALPHA_BITS = 0x0D55;
		[PreserveCase] public readonly int DEPTH_BITS = 0x0D56;
		[PreserveCase] public readonly int STENCIL_BITS = 0x0D57;
		[PreserveCase] public readonly int POLYGON_OFFSET_UNITS = 0x2A00;
		[PreserveCase] public readonly int POLYGON_OFFSET_FACTOR = 0x8038;
		[PreserveCase] public readonly int TEXTURE_BINDING_2D = 0x8069;
		[PreserveCase] public readonly int SAMPLE_BUFFERS = 0x80A8;
		[PreserveCase] public readonly int SAMPLES = 0x80A9;
		[PreserveCase] public readonly int SAMPLE_COVERAGE_VALUE = 0x80AA;
		[PreserveCase] public readonly int SAMPLE_COVERAGE_INVERT = 0x80AB;
		[PreserveCase] public readonly int COMPRESSED_TEXTURE_FORMATS = 0x86A3;
		[PreserveCase] public readonly int DONT_CARE = 0x1100;
		[PreserveCase] public readonly int FASTEST = 0x1101;
		[PreserveCase] public readonly int NICEST = 0x1102;
		[PreserveCase] public readonly int GENERATE_MIPMAP_HINT = 0x8192;
		[PreserveCase] public readonly int BYTE = 0x1400;
		[PreserveCase] public readonly int UNSIGNED_BYTE = 0x1401;
		[PreserveCase] public readonly int SHORT = 0x1402;
		[PreserveCase] public readonly int UNSIGNED_SHORT = 0x1403;
		[PreserveCase] public readonly int INT = 0x1404;
		[PreserveCase] public readonly int UNSIGNED_INT = 0x1405;
		[PreserveCase] public readonly int FLOAT = 0x1406;
		[PreserveCase] public readonly int DEPTH_COMPONENT = 0x1902;
		[PreserveCase] public readonly int ALPHA = 0x1906;
		[PreserveCase] public readonly int RGB = 0x1907;
		[PreserveCase] public readonly int RGBA = 0x1908;
		[PreserveCase] public readonly int LUMINANCE = 0x1909;
		[PreserveCase] public readonly int LUMINANCE_ALPHA = 0x190A;
		[PreserveCase] public readonly int UNSIGNED_SHORT_4_4_4_4 = 0x8033;
		[PreserveCase] public readonly int UNSIGNED_SHORT_5_5_5_1 = 0x8034;
		[PreserveCase] public readonly int UNSIGNED_SHORT_5_6_5 = 0x8363;
		[PreserveCase] public readonly int FRAGMENT_SHADER = 0x8B30;
		[PreserveCase] public readonly int VERTEX_SHADER = 0x8B31;
		[PreserveCase] public readonly int MAX_VERTEX_ATTRIBS = 0x8869;
		[PreserveCase] public readonly int MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB;
		[PreserveCase] public readonly int MAX_VARYING_VECTORS = 0x8DFC;
		[PreserveCase] public readonly int MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D;
		[PreserveCase] public readonly int MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C;
		[PreserveCase] public readonly int MAX_TEXTURE_IMAGE_UNITS = 0x8872;
		[PreserveCase] public readonly int MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD;
		[PreserveCase] public readonly int SHADER_TYPE = 0x8B4F;
		[PreserveCase] public readonly int DELETE_STATUS = 0x8B80;
		[PreserveCase] public readonly int LINK_STATUS = 0x8B82;
		[PreserveCase] public readonly int VALIDATE_STATUS = 0x8B83;
		[PreserveCase] public readonly int ATTACHED_SHADERS = 0x8B85;
		[PreserveCase] public readonly int ACTIVE_UNIFORMS = 0x8B86;
		[PreserveCase] public readonly int ACTIVE_ATTRIBUTES = 0x8B89;
		[PreserveCase] public readonly int SHADING_LANGUAGE_VERSION = 0x8B8C;
		[PreserveCase] public readonly int CURRENT_PROGRAM = 0x8B8D;
		[PreserveCase] public readonly int NEVER = 0x0200;
		[PreserveCase] public readonly int LESS = 0x0201;
		[PreserveCase] public readonly int EQUAL = 0x0202;
		[PreserveCase] public readonly int LEQUAL = 0x0203;
		[PreserveCase] public readonly int GREATER = 0x0204;
		[PreserveCase] public readonly int NOTEQUAL = 0x0205;
		[PreserveCase] public readonly int GEQUAL = 0x0206;
		[PreserveCase] public readonly int ALWAYS = 0x0207;
		[PreserveCase] public readonly int KEEP = 0x1E00;
		[PreserveCase] public readonly int REPLACE = 0x1E01;
		[PreserveCase] public readonly int INCR = 0x1E02;
		[PreserveCase] public readonly int DECR = 0x1E03;
		[PreserveCase] public readonly int INVERT = 0x150A;
		[PreserveCase] public readonly int INCR_WRAP = 0x8507;
		[PreserveCase] public readonly int DECR_WRAP = 0x8508;
		[PreserveCase] public readonly int VENDOR = 0x1F00;
		[PreserveCase] public readonly int RENDERER = 0x1F01;
		[PreserveCase] public readonly int VERSION = 0x1F02;
		[PreserveCase] public readonly int NEAREST = 0x2600;
		[PreserveCase] public readonly int LINEAR = 0x2601;
		[PreserveCase] public readonly int NEAREST_MIPMAP_NEAREST = 0x2700;
		[PreserveCase] public readonly int LINEAR_MIPMAP_NEAREST = 0x2701;
		[PreserveCase] public readonly int NEAREST_MIPMAP_LINEAR = 0x2702;
		[PreserveCase] public readonly int LINEAR_MIPMAP_LINEAR = 0x2703;
		[PreserveCase] public readonly int TEXTURE_MAG_FILTER = 0x2800;
		[PreserveCase] public readonly int TEXTURE_MIN_FILTER = 0x2801;
		[PreserveCase] public readonly int TEXTURE_WRAP_S = 0x2802;
		[PreserveCase] public readonly int TEXTURE_WRAP_T = 0x2803;
		[PreserveCase] public readonly int TEXTURE_2D = 0x0DE1;
		[PreserveCase] public readonly int TEXTURE = 0x1702;
		[PreserveCase] public readonly int TEXTURE_CUBE_MAP = 0x8513;
		[PreserveCase] public readonly int TEXTURE_BINDING_CUBE_MAP = 0x8514;
		[PreserveCase] public readonly int TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515;
		[PreserveCase] public readonly int TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516;
		[PreserveCase] public readonly int TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517;
		[PreserveCase] public readonly int TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518;
		[PreserveCase] public readonly int TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519;
		[PreserveCase] public readonly int TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A;
		[PreserveCase] public readonly int MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C;
		[PreserveCase] public readonly int TEXTURE0 = 0x84C0;
		[PreserveCase] public readonly int TEXTURE1 = 0x84C1;
		[PreserveCase] public readonly int TEXTURE2 = 0x84C2;
		[PreserveCase] public readonly int TEXTURE3 = 0x84C3;
		[PreserveCase] public readonly int TEXTURE4 = 0x84C4;
		[PreserveCase] public readonly int TEXTURE5 = 0x84C5;
		[PreserveCase] public readonly int TEXTURE6 = 0x84C6;
		[PreserveCase] public readonly int TEXTURE7 = 0x84C7;
		[PreserveCase] public readonly int TEXTURE8 = 0x84C8;
		[PreserveCase] public readonly int TEXTURE9 = 0x84C9;
		[PreserveCase] public readonly int TEXTURE10 = 0x84CA;
		[PreserveCase] public readonly int TEXTURE11 = 0x84CB;
		[PreserveCase] public readonly int TEXTURE12 = 0x84CC;
		[PreserveCase] public readonly int TEXTURE13 = 0x84CD;
		[PreserveCase] public readonly int TEXTURE14 = 0x84CE;
		[PreserveCase] public readonly int TEXTURE15 = 0x84CF;
		[PreserveCase] public readonly int TEXTURE16 = 0x84D0;
		[PreserveCase] public readonly int TEXTURE17 = 0x84D1;
		[PreserveCase] public readonly int TEXTURE18 = 0x84D2;
		[PreserveCase] public readonly int TEXTURE19 = 0x84D3;
		[PreserveCase] public readonly int TEXTURE20 = 0x84D4;
		[PreserveCase] public readonly int TEXTURE21 = 0x84D5;
		[PreserveCase] public readonly int TEXTURE22 = 0x84D6;
		[PreserveCase] public readonly int TEXTURE23 = 0x84D7;
		[PreserveCase] public readonly int TEXTURE24 = 0x84D8;
		[PreserveCase] public readonly int TEXTURE25 = 0x84D9;
		[PreserveCase] public readonly int TEXTURE26 = 0x84DA;
		[PreserveCase] public readonly int TEXTURE27 = 0x84DB;
		[PreserveCase] public readonly int TEXTURE28 = 0x84DC;
		[PreserveCase] public readonly int TEXTURE29 = 0x84DD;
		[PreserveCase] public readonly int TEXTURE30 = 0x84DE;
		[PreserveCase] public readonly int TEXTURE31 = 0x84DF;
		[PreserveCase] public readonly int ACTIVE_TEXTURE = 0x84E0;
		[PreserveCase] public readonly int REPEAT = 0x2901;
		[PreserveCase] public readonly int CLAMP_TO_EDGE = 0x812F;
		[PreserveCase] public readonly int MIRRORED_REPEAT = 0x8370;
		[PreserveCase] public readonly int FLOAT_VEC2 = 0x8B50;
		[PreserveCase] public readonly int FLOAT_VEC3 = 0x8B51;
		[PreserveCase] public readonly int FLOAT_VEC4 = 0x8B52;
		[PreserveCase] public readonly int INT_VEC2 = 0x8B53;
		[PreserveCase] public readonly int INT_VEC3 = 0x8B54;
		[PreserveCase] public readonly int INT_VEC4 = 0x8B55;
		[PreserveCase] public readonly int BOOL = 0x8B56;
		[PreserveCase] public readonly int BOOL_VEC2 = 0x8B57;
		[PreserveCase] public readonly int BOOL_VEC3 = 0x8B58;
		[PreserveCase] public readonly int BOOL_VEC4 = 0x8B59;
		[PreserveCase] public readonly int FLOAT_MAT2 = 0x8B5A;
		[PreserveCase] public readonly int FLOAT_MAT3 = 0x8B5B;
		[PreserveCase] public readonly int FLOAT_MAT4 = 0x8B5C;
		[PreserveCase] public readonly int SAMPLER_2D = 0x8B5E;
		[PreserveCase] public readonly int SAMPLER_CUBE = 0x8B60;
		[PreserveCase] public readonly int VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622;
		[PreserveCase] public readonly int VERTEX_ATTRIB_ARRAY_SIZE = 0x8623;
		[PreserveCase] public readonly int VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624;
		[PreserveCase] public readonly int VERTEX_ATTRIB_ARRAY_TYPE = 0x8625;
		[PreserveCase] public readonly int VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A;
		[PreserveCase] public readonly int VERTEX_ATTRIB_ARRAY_POINTER = 0x8645;
		[PreserveCase] public readonly int VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F;
		[PreserveCase] public readonly int COMPILE_STATUS = 0x8B81;
		[PreserveCase] public readonly int LOW_FLOAT = 0x8DF0;
		[PreserveCase] public readonly int MEDIUM_FLOAT = 0x8DF1;
		[PreserveCase] public readonly int HIGH_FLOAT = 0x8DF2;
		[PreserveCase] public readonly int LOW_INT = 0x8DF3;
		[PreserveCase] public readonly int MEDIUM_INT = 0x8DF4;
		[PreserveCase] public readonly int HIGH_INT = 0x8DF5;
		[PreserveCase] public readonly int FRAMEBUFFER = 0x8D40;
		[PreserveCase] public readonly int RENDERBUFFER = 0x8D41;
		[PreserveCase] public readonly int RGBA4 = 0x8056;
		[PreserveCase] public readonly int RGB5_A1 = 0x8057;
		[PreserveCase] public readonly int RGB565 = 0x8D62;
		[PreserveCase] public readonly int DEPTH_COMPONENT16 = 0x81A5;
		[PreserveCase] public readonly int STENCIL_INDEX = 0x1901;
		[PreserveCase] public readonly int STENCIL_INDEX8 = 0x8D48;
		[PreserveCase] public readonly int DEPTH_STENCIL = 0x84F9;
		[PreserveCase] public readonly int RENDERBUFFER_WIDTH = 0x8D42;
		[PreserveCase] public readonly int RENDERBUFFER_HEIGHT = 0x8D43;
		[PreserveCase] public readonly int RENDERBUFFER_INTERNAL_FORMAT = 0x8D44;
		[PreserveCase] public readonly int RENDERBUFFER_RED_SIZE = 0x8D50;
		[PreserveCase] public readonly int RENDERBUFFER_GREEN_SIZE = 0x8D51;
		[PreserveCase] public readonly int RENDERBUFFER_BLUE_SIZE = 0x8D52;
		[PreserveCase] public readonly int RENDERBUFFER_ALPHA_SIZE = 0x8D53;
		[PreserveCase] public readonly int RENDERBUFFER_DEPTH_SIZE = 0x8D54;
		[PreserveCase] public readonly int RENDERBUFFER_STENCIL_SIZE = 0x8D55;
		[PreserveCase] public readonly int FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0;
		[PreserveCase] public readonly int FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1;
		[PreserveCase] public readonly int FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2;
		[PreserveCase] public readonly int FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3;
		[PreserveCase] public readonly int COLOR_ATTACHMENT0 = 0x8CE0;
		[PreserveCase] public readonly int DEPTH_ATTACHMENT = 0x8D00;
		[PreserveCase] public readonly int STENCIL_ATTACHMENT = 0x8D20;
		[PreserveCase] public readonly int DEPTH_STENCIL_ATTACHMENT = 0x821A;
		[PreserveCase] public readonly int NONE = 0;
		[PreserveCase] public readonly int FRAMEBUFFER_COMPLETE = 0x8CD5;
		[PreserveCase] public readonly int FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6;
		[PreserveCase] public readonly int FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7;
		[PreserveCase] public readonly int FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9;
		[PreserveCase] public readonly int FRAMEBUFFER_UNSUPPORTED = 0x8CDD;
		[PreserveCase] public readonly int FRAMEBUFFER_BINDING = 0x8CA6;
		[PreserveCase] public readonly int RENDERBUFFER_BINDING = 0x8CA7;
		[PreserveCase] public readonly int MAX_RENDERBUFFER_SIZE = 0x84E8;
		[PreserveCase] public readonly int INVALID_FRAMEBUFFER_OPERATION = 0x0506;
		[PreserveCase] public readonly int UNPACK_FLIP_Y_WEBGL = 0x9240;
		[PreserveCase] public readonly int UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241;
		[PreserveCase] public readonly int CONTEXT_LOST_WEBGL = 0x9242;
		[PreserveCase] public readonly int UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243;
		[PreserveCase] public readonly int BROWSER_DEFAULT_WEBGL = 0x9244;

		//[WebGLHandlesContextLoss]
		public WebGLContextAttributes GetContextAttributes()
		{
			return null;
		}

		//[WebGLHandlesContextLoss]
		public bool IsContextLost()
		{
			return false;
		}

		public string[] GetSupportedExtensions()
		{
			return new string[0];
		}

		public object GetExtension(string name)
		{
			return null;
		}

		public void ActiveTexture(int texture)
		{
		}

		public void AttachShader(WebGLProgram program, WebGLShader shader)
		{
		}

		public void BindAttribLocation(WebGLProgram program, int index, string name)
		{
		}

		public void BindBuffer(int target, WebGLBuffer buffer)
		{
		}

		public void BindFramebuffer(int target, WebGLFramebuffer framebuffer)
		{
		}

		public void BindRenderbuffer(int target, WebGLRenderbuffer renderbuffer)
		{
		}

		public void BindTexture(int target, WebGLTexture texture)
		{
		}

		public void BlendColor(float red, float green, float blue, float alpha)
		{
		}

		public void BlendEquation(int mode)
		{
		}

		public void BlendEquationSeparate(int modeRGB, int modeAlpha)
		{
		}

		public void BlendFunc(int sfactor, int dfactor)
		{
		}

		public void BlendFuncSeparate(int srcRGB, int dstRGB, int srcAlpha, int dstAlpha)
		{
		}

		public void BufferData(int target, int size, int usage)
		{
		}

		public void BufferData(int target, ArrayBufferView data, int usage)
		{
		}

		public void BufferData(int target, ArrayBuffer data, int usage)
		{
		}

		public void BufferSubData(int target, int offset, ArrayBufferView data)
		{
		}

		public void BufferSubData(int target, int offset, ArrayBuffer data)
		{
		}

		//[WebGLHandlesContextLoss]
		public int CheckFramebufferStatus(int target)
		{
			return 0;
		}

		public void Clear(int mask)
		{
		}

		public void ClearColor(float red, float green, float blue, float alpha)
		{
		}

		public void ClearDepth(float depth)
		{
		}

		public void ClearStencil(int s)
		{
		}

		public void ColorMask(bool red, bool green, bool blue, bool alpha)
		{
		}

		public void CompileShader(WebGLShader shader)
		{
		}

		public void CompressedTexImage2D(int target, int level, int internalformat, int width,
		                                 int height, int border, ArrayBufferView data)
		{
		}

		public void CompressedTexSubImage2D(int target, int level, int xoffset, int yoffset,
		                                    int width, int height, int format, ArrayBufferView data)
		{
		}

		public void CopyTexImage2D(int target, int level, int internalformat, int x, int y, int width,
		                           int height, int border)
		{
		}

		public void CopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y,
		                              int width, int height)
		{
		}

		public WebGLBuffer CreateBuffer()
		{
			return null;
		}

		public WebGLFramebuffer CreateFramebuffer()
		{
			return null;
		}

		public WebGLProgram CreateProgram()
		{
			return null;
		}

		public WebGLRenderbuffer CreateRenderbuffer()
		{
			return null;
		}

		public WebGLShader CreateShader(int type)
		{
			return null;
		}

		public WebGLTexture CreateTexture()
		{
			return null;
		}

		public void CullFace(int mode)
		{
		}

		public void DeleteBuffer(WebGLBuffer buffer)
		{
		}

		public void DeleteFramebuffer(WebGLFramebuffer framebuffer)
		{
		}

		public void DeleteProgram(WebGLProgram program)
		{
		}

		public void DeleteRenderbuffer(WebGLRenderbuffer renderbuffer)
		{
		}

		public void DeleteShader(WebGLShader shader)
		{
		}

		public void DeleteTexture(WebGLTexture texture)
		{
		}

		public void DepthFunc(int func)
		{
		}

		public void DepthMask(bool flag)
		{
		}

		public void DepthRange(float zNear, float zFar)
		{
		}

		public void DetachShader(WebGLProgram program, WebGLShader shader)
		{
		}

		public void Disable(int cap)
		{
		}

		public void DisableVertexAttribArray(int index)
		{
		}

		public void DrawArrays(int mode, int first, int count)
		{
		}

		public void DrawElements(int mode, int count, int type, int offset)
		{
		}

		public void Enable(int cap)
		{
		}

		public void EnableVertexAttribArray(int index)
		{
		}

		public void Finish()
		{
		}

		public void Flush()
		{
		}

		public void FramebufferRenderbuffer(int target, int attachment, int renderbuffertarget,
		                                    WebGLRenderbuffer renderbuffer)
		{
		}

		public void FramebufferTexture2D(int target, int attachment, int textarget,
		                                 WebGLTexture texture, int level)
		{
		}

		public void FrontFace(int mode)
		{
		}

		public void GenerateMipmap(int target)
		{
		}

		public WebGLActiveInfo GetActiveAttrib(WebGLProgram program, int index)
		{
			return null;
		}

		public WebGLActiveInfo GetActiveUniform(WebGLProgram program, int index)
		{
			return null;
		}

		public WebGLShader[] GetAttachedShaders(WebGLProgram program)
		{
			return new WebGLShader[0];
		}

		//[WebGLHandlesContextLoss]
		public int GetAttribLocation(WebGLProgram program, string name)
		{
			return 0;
		}

		public object GetBufferParameter(int target, int pname)
		{
			return null;
		}

		public object GetParameter(int pname)
		{
			return null;
		}

		//[WebGLHandlesContextLoss]
		public int GetError()
		{
			return 0;
		}

		public object GetFramebufferAttachmentParameter(int target, int attachment, int pname)
		{
			return null;
		}

		public object GetProgramParameter(WebGLProgram program, int pname)
		{
			return null;
		}

		public string GetProgramInfoLog(WebGLProgram program)
		{
			return "";
		}

		public object GetRenderbufferParameter(int target, int pname)
		{
			return null;
		}

		public object GetShaderParameter(WebGLShader shader, int pname)
		{
			return null;
		}

		public WebGLShaderPrecisionFormat GetShaderPrecisionFormat(int shadertype, int precisiontype)
		{
			return null;
		}

		public string GetShaderInfoLog(WebGLShader shader)
		{
			return "";
		}

		public string GetShaderSource(WebGLShader shader)
		{
			return "";
		}

		public object GetTexParameter(int target, int pname)
		{
			return null;
		}

		public object GetUniform(WebGLProgram program, WebGLUniformLocation location)
		{
			return null;
		}

		public WebGLUniformLocation GetUniformLocation(WebGLProgram program, string name)
		{
			return null;
		}

		public object GetVertexAttrib(int index, int pname)
		{
			return null;
		}

		//[WebGLHandlesContextLoss]
		public int GetVertexAttribOffset(int index, int pname)
		{
			return 0;
		}

		public void Hint(int target, int mode)
		{
		}

		//[WebGLHandlesContextLoss]
		public bool IsBuffer(WebGLBuffer buffer)
		{
			return false;
		}

		//[WebGLHandlesContextLoss]
		public bool IsEnabled(int cap)
		{
			return false;
		}

		//[WebGLHandlesContextLoss]
		public bool IsFramebuffer(WebGLFramebuffer framebuffer)
		{
			return false;
		}

		//[WebGLHandlesContextLoss]
		public bool IsProgram(WebGLProgram program)
		{
			return false;
		}

		//[WebGLHandlesContextLoss]
		public bool IsRenderbuffer(WebGLRenderbuffer renderbuffer)
		{
			return false;
		}

		//[WebGLHandlesContextLoss]
		public bool IsShader(WebGLShader shader)
		{
			return false;
		}

		//[WebGLHandlesContextLoss]
		public bool IsTexture(WebGLTexture texture)
		{
			return false;
		}

		public void LineWidth(float width)
		{
		}

		public void LinkProgram(WebGLProgram program)
		{
		}

		public void PixelStorei(int pname, int param)
		{
		}

		public void PolygonOffset(float factor, float units)
		{
		}

		public void ReadPixels(int x, int y, int width, int height, int format, int type,
		                       ArrayBufferView pixels)
		{
		}

		public void RenderbufferStorage(int target, int internalformat, int width, int height)
		{
		}

		public void SampleCoverage(float value, bool invert)
		{
		}

		public void Scissor(int x, int y, int width, int height)
		{
		}

		public void ShaderSource(WebGLShader shader, string source)
		{
		}

		public void StencilFunc(int func, int value, int mask)
		{
		}

		public void StencilFuncSeparate(int face, int func, int value, int mask)
		{
		}

		public void StencilMask(int mask)
		{
		}

		public void StencilMaskSeparate(int face, int mask)
		{
		}

		public void StencilOp(int fail, int zfail, int zpass)
		{
		}

		public void StencilOpSeparate(int face, int fail, int zfail, int zpass)
		{
		}

		public void TexImage2D(int target, int level, int internalformat, int width, int height,
		                       int border, int format, int type, ArrayBufferView pixels)
		{
		}

		public void TexImage2D(int target, int level, int internalformat, int format, int type,
		                       ImageData pixels)
		{
		}

		public void TexImage2D(int target, int level, int internalformat, int format, int type,
		                       ImageElement image)
		{
		}

		// May throw DOMException
		public void TexImage2D(int target, int level, int internalformat, int format, int type,
		                       CanvasElement canvas)
		{
		}

		// TODO
		//// May throw DOMException
		//public void TexImage2D(int target, int level, int internalformat, int format, int type,
		//	VideoElement video) { }

		// May throw DOMException

		public void TexParameterf(int target, int pname, float param)
		{
		}

		public void TexParameteri(int target, int pname, int param)
		{
		}

		public void TexSubImage2D(int target, int level, int xoffset, int yoffset, int width,
		                          int height, int format, int type, ArrayBufferView pixels)
		{
		}

		public void TexSubImage2D(int target, int level, int xoffset, int yoffset, int format,
		                          int type, ImageData pixels)
		{
		}

		public void TexSubImage2D(int target, int level, int xoffset, int yoffset, int format,
		                          int type, ImageElement image)
		{
		}

		// May throw DOMException
		public void TexSubImage2D(int target, int level, int xoffset, int yoffset, int format,
		                          int type, CanvasElement canvas)
		{
		}

		// TODO
		//// May throw DOMException
		//public void TexSubImage2D(int target, int level, int xoffset, int yoffset, int format,
		//	int type, VideoElement video) { }

		// May throw DOMException

		public void Uniform1f(WebGLUniformLocation location, float x)
		{
		}

		public void Uniform1fv(WebGLUniformLocation location, Float32Array v)
		{
		}

		public void Uniform1fv(WebGLUniformLocation location, float[] v)
		{
		}

		public void Uniform1i(WebGLUniformLocation location, int x)
		{
		}

		public void Uniform1iv(WebGLUniformLocation location, Int32Array v)
		{
		}

		public void Uniform1iv(WebGLUniformLocation location, int[] v)
		{
		}

		public void Uniform2f(WebGLUniformLocation location, float x, float y)
		{
		}

		public void Uniform2fv(WebGLUniformLocation location, Float32Array v)
		{
		}

		public void Uniform2fv(WebGLUniformLocation location, float[] v)
		{
		}

		public void Uniform2i(WebGLUniformLocation location, int x, int y)
		{
		}

		public void Uniform2iv(WebGLUniformLocation location, Int32Array v)
		{
		}

		public void Uniform2iv(WebGLUniformLocation location, int[] v)
		{
		}

		public void Uniform3f(WebGLUniformLocation location, float x, float y, float z)
		{
		}

		public void Uniform3fv(WebGLUniformLocation location, Float32Array v)
		{
		}

		public void Uniform3fv(WebGLUniformLocation location, float[] v)
		{
		}

		public void Uniform3i(WebGLUniformLocation location, int x, int y, int z)
		{
		}

		public void Uniform3iv(WebGLUniformLocation location, Int32Array v)
		{
		}

		public void Uniform3iv(WebGLUniformLocation location, int[] v)
		{
		}

		public void Uniform4f(WebGLUniformLocation location, float x, float y, float z, float w)
		{
		}

		public void Uniform4fv(WebGLUniformLocation location, Float32Array v)
		{
		}

		public void Uniform4fv(WebGLUniformLocation location, float[] v)
		{
		}

		public void Uniform4i(WebGLUniformLocation location, int x, int y, int z, int w)
		{
		}

		public void Uniform4iv(WebGLUniformLocation location, Int32Array v)
		{
		}

		public void Uniform4iv(WebGLUniformLocation location, int[] v)
		{
		}

		public void UniformMatrix2fv(WebGLUniformLocation location, bool transpose,
		                             Float32Array value)
		{
		}

		public void UniformMatrix2fv(WebGLUniformLocation location, bool transpose, float[] value)
		{
		}

		public void UniformMatrix3fv(WebGLUniformLocation location, bool transpose,
		                             Float32Array value)
		{
		}

		public void UniformMatrix3fv(WebGLUniformLocation location, bool transpose, float[] value)
		{
		}

		public void UniformMatrix4fv(WebGLUniformLocation location, bool transpose,
		                             Float32Array value)
		{
		}

		public void UniformMatrix4fv(WebGLUniformLocation location, bool transpose, float[] value)
		{
		}

		public void UseProgram(WebGLProgram program)
		{
		}

		public void ValidateProgram(WebGLProgram program)
		{
		}

		public void VertexAttrib1f(int indx, float x)
		{
		}

		public void VertexAttrib1fv(int indx, Float32Array values)
		{
		}

		public void VertexAttrib1fv(int indx, float[] values)
		{
		}

		public void VertexAttrib2f(int indx, float x, float y)
		{
		}

		public void VertexAttrib2fv(int indx, Float32Array values)
		{
		}

		public void VertexAttrib2fv(int indx, float[] values)
		{
		}

		public void VertexAttrib3f(int indx, float x, float y, float z)
		{
		}

		public void VertexAttrib3fv(int indx, Float32Array values)
		{
		}

		public void VertexAttrib3fv(int indx, float[] values)
		{
		}

		public void VertexAttrib4f(int indx, float x, float y, float z, float w)
		{
		}

		public void VertexAttrib4fv(int indx, Float32Array values)
		{
		}

		public void VertexAttrib4fv(int indx, float[] values)
		{
		}

		public void VertexAttribPointer(int indx, int size, int type, bool normalized, int stride,
		                                int offset)
		{
		}

		public void Viewport(int x, int y, int width, int height)
		{
		}
	}
}


text:
"""

A simple Solr client for python.

Features
--------
 * Supports SOLR 1.2+
 * Supports http/https and SSL client-side certificates
 * Uses persistent HTTP connections by default
 * Properly converts to/from SOLR data types, including datetime objects
 * Supports both querying and update commands (add, delete).
 * Supports batching of commands
 * Requires Python 2.3+

Connections
-----------
`SolrConnection` can be passed in the following parameters.
Only `url` is required,.

    url -- URI pointing to the SOLR instance. Examples:

        http://localhost:8080/solr
        https://solr-server/solr

        Your python install must be compiled with SSL support for the
        https:// schemes to work. (Most pre-packaged pythons are.)

    persistent -- Keep a persistent HTTP connection open.
        Defaults to true.

    timeout -- Timeout, in seconds, for the server to response.
        By default, use the python default timeout (of none?)
        NOTE: This changes the python-wide timeout.

    ssl_key, ssl_cert -- If using client-side key files for
        SSL authentication,  these should be, respectively,
        your PEM key file and certificate file

Once created, a connection object has the following public methods:

    query (q, fields=None, highlight=None,
           score=True, sort=None, **params)

            q -- the query string.

            fields -- optional list of fields to include. It can be either
                a string in the format that SOLR expects ('id,f1,f2'), or
                a python list/tuple of field names.   Defaults to returning
                all fields. ("*")

            score -- boolean indicating whether "score" should be included
                in the field list.  Note that if you explicitly list
                "score" in your fields value, then this parameter is
                effectively ignored.  Defaults to true.

            highlight -- indicates whether highlighting should be included.
                `highlight` can either be `False`, indicating "No" (the
                default),  `True`, incidating to highlight any fields
                included in "fields", or a list of field names.

            sort -- list of fields to sort by.

            Any parameters available to SOLR 'select' calls can also be
            passed in as named parameters (e.g., fq='...', rows=20, etc).

            Many SOLR parameters are in a dotted notation (e.g.,
            `hl.simple.post`).  For such parameters, replace the dots with
            underscores when calling this method. (e.g.,
            hl_simple_post='</pre'>)

            Returns a Response object

    add(**params)

            Add a document.  Pass in all document fields as
            keyword parameters:

                add(id='foo', notes='bar')

            You must "commit" for the addition to be saved.
            This command honors begin_batch/end_batch.

    add_many(lst)

            Add a series of documents at once.  Pass in a list of
            dictionaries, where each dictionary is a mapping of document
            fields:

                add_many( [ {'id': 'foo1', 'notes': 'foo'},
                            {'id': 'foo2', 'notes': 'w00t'} ] )

            You must "commit" for the addition to be saved.
            This command honors begin_batch/end_batch.

    delete(id)

            Delete a document by id.

            You must "commit" for the deletion to be saved.
            This command honors begin_batch/end_batch.

    delete_many(lst)

            Delete a series of documents.  Pass in a list of ids.

            You must "commit" for the deletion to be saved.
            This command honors begin_batch/end_batch.

    delete_query(query)

            Delete any documents returned by issuing a query.

            You must "commit" for the deletion to be saved.
            This command honors begin_batch/end_batch.

    commit(wait_flush=True, wait_searcher=True)

            Issue a commit command.

            This command honors begin_batch/end_batch.

    optimize(wait_flush=True, wait_searcher=True)

            Issue an optimize command.

            This command honors begin_batch/end_batch.

    begin_batch()

            Begin "batch" mode, in which all commands to be sent
            to the SOLR server are queued up and sent all at once.

            No update commands will be sent to the backend server
            until end_batch() is called. Not that "query" commands
            are not batched.

            begin_batch/end_batch transactions can be nested.
            The transaction will not be sent to the backend server
            until as many end_batch() calls have been made as
            begin_batch()s.

            Batching is completely optional. Any update commands
            issued outside of a begin_batch()/end_batch() pair will
            be immediately processed.

    end_batch(commit=False)

            End a batching pair.  Any pending commands are sent
            to the backend server.  If "True" is passed in to
            end_batch, a <commit> is also sent.

    raw_query(**params)

            Send a query command (unprocessed by this library) to
            the SOLR server. The resulting text is returned un-parsed.

                raw_query(q='id:1', wt='python', indent='on')

            Many SOLR parameters are in a dotted notation (e.g.,
            `hl.simple.post`).  For such parameters, replace the dots with
            underscores when calling this method. (e.g.,
            hl_simple_post='</pre'>)

    close()
            Close the underlying HTTP(S) connection.

Query Responses
---------------

    Calls to connection.query() return a Response object.

    Response objects always have the following properties:

        results -- A list of matching documents. Each document will be a
            dict of field values.

        results.start -- An integer indicating the starting # of documents

        results.numFound -- An integer indicating the total # of matches.

        results.maxScore -- An integer indicating the maximum score assigned
                            to a document. Takes into account all of documents
                            found by the query, not only the current batch.

        header -- A dict containing any responseHeaders.  Usually:

            header['params'] -- dictionary of original parameters used to
                        create this response set.

            header['QTime'] -- time spent on the query

            header['status'] -- status code.

            See SOLR documentation for other/typical return values.
            This may be settable at the SOLR-level in your config files.

        next_batch() -- If only a partial set of matches were returned
            (by default, 10 documents at a time), then calling
            .next_batch() will return a new Response object containing
            the next set of matching documents. Returns None if no
            more matches.

            This works by re-issuing the same query to the backend server,
            with a new 'start' value.

        previous_batch() -- Same as next_batch, but return the previous
            set of matches.  Returns None if this is the first batch.

    Response objects also support __len__ and iteration. So, the following
    shortcuts work:

        responses = connection.query('q=foo')
        print len(responses)
        for document in responses:
            print document['id'], document['score']

    If you pass in `highlight` to the SolrConnection.query call,
    then the response object will also have a "highlighting" property,
    which will be a dictionary.

Quick examples on use:
----------------------

Example showing basic connection/transactions

    >>> from solr import *
    >>> c = SolrConnection('http://localhost:8983/solr')
    >>> c.add(id='500', name='python test doc', inStock=True)
    >>> c.delete('123')
    >>> c.commit()

Examples showing the search wrapper

    >>> response = c.query('test', rows=20)
    >>> print response.results.start
     0
    >>> for match in response:
    ...     print match['id'],
      0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
    >>> response = response.next_batch()
    >>> print response.results.start
     20

Add 3 documents and delete 1, but send all of them as a single transaction.

    >>> c.begin_batch()
    >>> c.add(id="1")
    >>> c.add(id="2")
    >>> c.add(id="3")
    >>> c.delete(id="0")
    >>> c.end_batch(True)

Enter a raw query, without processing the returned HTML contents.

    >>> print c.raw_query(q='id:[* TO *]', wt='python', rows='10')

"""
import sys
import socket
import httplib
import urlparse
import codecs
import urllib
import datetime
from StringIO import StringIO
from xml.sax import make_parser
from xml.sax.handler import ContentHandler
from xml.sax.saxutils import escape, quoteattr
from xml.dom.minidom import parseString

__version__ = "0.5"

__all__ = ['SolrException', 'SolrConnection', 'Response']

_python_version = sys.version_info[0] + (sys.version_info[1] / 10.0)

# ===================================================================
# Exceptions
# ===================================================================

class SolrException(Exception):
    """ An exception thrown by solr connections """
    def __init__(self, httpcode, reason=None, body=None):
        self.httpcode = httpcode
        self.reason = reason
        self.body = body

    def __repr__(self):
        return 'HTTP code=%s, Reason=%s, body=%s' % (
                    self.httpcode, self.reason, self.body)

    def __str__(self):
        return 'HTTP code=%s, reason=%s' % (self.httpcode, self.reason)

# ===================================================================
# Connection Object
# ===================================================================
class SolrConnection:
    """
    Represents a Solr connection.

    Designed to work with the 2.2 response format (SOLR 1.2+).
    (though 2.1 will likely work.)
    """

    def __init__(self, url,
                 persistent=True,
                 timeout=None,
                 ssl_key=None,
                 ssl_cert=None,
                 post_headers={}):

        """
            url -- URI pointing to the SOLR instance. Examples:

                http://localhost:8080/solr
                https://solr-server/solr

                Your python install must be compiled with SSL support for the
                https:// schemes to work. (Most pre-packaged pythons are.)

            persistent -- Keep a persistent HTTP connection open.
                Defaults to true

            timeout -- Timeout, in seconds, for the server to response.
                By default, use the python default timeout (of none?)

            ssl_key, ssl_cert -- If using client-side key files for
                SSL authentication,  these should be, respectively,
                your PEM key file and certificate file

        """

        self.scheme, self.host, self.path = urlparse.urlparse(url, 'http')[:3]
        self.url = url

        assert self.scheme in ('http', 'https')

        self.persistent = persistent
        self.reconnects = 0
        self.timeout = timeout
        self.ssl_key = ssl_key
        self.ssl_cert = ssl_cert

        kwargs = {}

        if self.timeout and _python_version >= 2.6 and _python_version < 3:
            kwargs['timeout'] = self.timeout

        if self.scheme == 'https':
            self.conn = httplib.HTTPSConnection(self.host,
                   key_file=ssl_key, cert_file=ssl_cert, **kwargs)
        else:
            self.conn = httplib.HTTPConnection(self.host, **kwargs)

        # this is int, not bool!
        self.batch_cnt = 0
        self.response_version = 2.2
        self.encoder = codecs.getencoder('utf-8')

        # Responses from Solr will always be in UTF-8
        self.decoder = codecs.getdecoder('utf-8')

        # Set timeout, if applicable.
        if self.timeout and _python_version < 2.6:
            self.conn.connect()
            if self.scheme == 'http':
                self.conn.sock.settimeout(self.timeout)
            elif self.scheme == 'https':
                self.conn.sock.sock.settimeout(self.timeout)

        self.xmlheaders = {'Content-Type': 'text/xml; charset=utf-8'}
        self.xmlheaders.update(post_headers)
        if not self.persistent:
            self.xmlheaders['Connection'] = 'close'

        self.form_headers = {
                'Content-Type':
                'application/x-www-form-urlencoded; charset=utf-8'}

        if not self.persistent:
            self.form_headers['Connection'] = 'close'

    def close(self):
        self.conn.close()

    def query(self, q, fields=None, highlight=None,
              score=True, sort=None, sort_order="asc", **params):
        """
        q is the query string.

        fields is an optional list of fields to include. It can
        be either a string in the format that SOLR expects, or
        a python list/tuple of field names.   Defaults to
        all fields. ("*")

        score indicates whether "score" should be included
        in the field list.  Note that if you explicitly list
        "score" in your fields value, then score is
        effectively ignored.  Defaults to true.

        highlight indicates whether highlighting should be included.
        highlight can either be False, indicating "No" (the default),
        a list of fields in the same format as "fields" or True, indicating
        to highlight any fields included in "fields". If True and no "fields"
        are given, raise a ValueError.

        sort is a list of fields to sort by. See "fields" for
        formatting.

        sort_order defaults to "asc" and specifies the order to sort the fields
        in. sort_order must be "asc" or "desc", otherwise a ValueError is
        raised.

        Optional parameters can also be passed in.  Many SOLR
        parameters are in a dotted notation (e.g., hl.simple.post).
        For such parameters, replace the dots with underscores when
        calling this method. (e.g., hl_simple_post='</pre'>)

        Returns a Response instance.
        """

        # Clean up optional parameters to match SOLR spec.
        params = dict([(key.replace('_', '.'), value)
                      for key, value in params.items()])

        if highlight:
            params['hl'] = 'true'
            if not isinstance(highlight, (bool, int, float)):
                if not isinstance(highlight, basestring):
                    highlight = ",".join(highlight)
                params['hl.fl'] = highlight
            else:
                if not fields:
                    raise ValueError(
                        "highlight is True and no fields were given")
                elif isinstance(fields, basestring):
                    params['hl.fl'] = [fields]
                else:
                    params['hl.fl'] = ",".join(fields)

        if q is not None:
            params['q'] = q

        if fields:
            if not isinstance(fields, basestring):
                fields = ",".join(fields)
        if not fields:
            fields = '*'

        if sort:
            if not sort_order or sort_order not in ("asc", "desc"):
                raise ValueError("sort_order must be 'asc' or 'desc'")
            if not isinstance(sort, basestring):
                sort = ",".join(sort)
            params['sort'] = "%s %s" % (sort, sort_order)

        if score and not 'score' in fields.replace(',', ' ').split():
            fields += ',score'

        params['fl'] = fields
        params['version'] = self.response_version
        params['wt'] = 'standard'

        request = urllib.urlencode(params, doseq=True)

        try:
            rsp = self._post(self.path + '/select',
                              request, self.form_headers)
            # If we pass in rsp directly, instead of using rsp.read())
            # and creating a StringIO, then Persistence breaks with
            # an internal python error.
            xml = StringIO(rsp.read())
            data = parse_query_response(xml,  params=params, connection=self)

        finally:
            if not self.persistent:
                self.close()

        return data

    def begin_batch(self):
        """
        Denote the beginning of a batch update.

        No update commands will be sent to the backend server
        until end_batch() is called.

        Any update commands issued outside of a begin_batch()/
        end_batch() series will be immediately processed.

        begin_batch/end_batch transactions can be nested.
        The transaction will not be sent to the backend server
        until as many end_batch() calls have been made as
        begin_batch()s.
        """
        if not self.batch_cnt:
            self.__batch_queue = []

        self.batch_cnt += 1

        return self.batch_cnt

    def end_batch(self, commit=False):
        """
        Denote the end of a batch update.

        Sends any queued commands to the backend server.

        If `commit` is True, then a <commit/> command is included
        at the end of the list of commands sent.
        """
        batch_cnt = self.batch_cnt - 1
        if batch_cnt < 0:
            raise SolrException(
                "end_batch called without a corresponding begin_batch")

        self.batch_cnt = batch_cnt
        if batch_cnt:
            return False

        if commit:
            self.__batch_queue.append('<commit/>')

        return self._update("".join(self.__batch_queue))

    def delete(self, id):
        """
        Delete a specific document by id.
        """
        xstr = u'<delete><id>%s</id></delete>' % escape(unicode(id))
        return self._update(xstr)

    def delete_many(self, ids):
        """
        Delete documents using a list of IDs.
        """
        [self.delete(id) for id in ids]

    def delete_query(self, query):
        """
        Delete all documents returned by a query.
        """
        xstr = u'<delete><query>%s</query></delete>' % escape(query)
        return self._update(xstr)

    def add(self, _commit=False, **fields):
        """
        Add a document to the SOLR server.  Document fields
        should be specified as arguments to this function

        Example:
            connection.add(id="mydoc", author="Me")
        """
        lst = [u'<add>']
        self.__add(lst, fields)
        lst.append(u'</add>')
        xstr = ''.join(lst)
        if not _commit:
            return self._update(xstr)
        else:
            self._update(xstr)
            return self.commit()

    def add_many(self, docs, _commit=False):
        """
        Add several documents to the SOLR server.

        docs -- a list of dicts, where each dict is a document to add
            to SOLR.
        """
        lst = [u'<add>']
        for doc in docs:
            self.__add(lst, doc)
        lst.append(u'</add>')
        xstr = ''.join(lst)
        if not _commit:
            return self._update(xstr)
        else:
            self._update(xstr)
            return self.commit()

    def commit(self, wait_flush=True, wait_searcher=True, _optimize=False):
        """
        Issue a commit command to the SOLR server.
        """
        # just handle deviations from the default
        if not wait_searcher:
            if not wait_flush:
                options = 'waitFlush="false" waitSearcher="false"'
            else:
                options = 'waitSearcher="false"'
        else:
            options = ''

        if _optimize:
            xstr = u'<optimize %s/>' % options
        else:
            xstr = u'<commit %s/>' % options

        return self._update(xstr)

    def optimize(self, wait_flush=True, wait_searcher=True, ):
        """
        Issue an optimize command to the SOLR server.
        """
        self.commit(wait_flush, wait_searcher, _optimize=True)

    def raw_query(self, **params):
        """
        Issue a query against a SOLR server.

        Return the raw result.  No pre-processing or
        post-processing happens to either
        input parameters or responses
        """

        # Clean up optional parameters to match SOLR spec.
        params = dict([(key.replace('_', '.'), value)
                       for key, value in params.items()])

        request = urllib.urlencode(params, doseq=True)

        try:
            rsp = self._post(self.path + '/select',
                              request, self.form_headers)
            data = rsp.read()
        finally:
            if not self.persistent:
                self.close()

        return data

    def _update(self, request):

        # If we're in batching mode, just queue up the requests for later.
        if self.batch_cnt:
            self.__batch_queue.append(request)
            return

        try:
            rsp = self._post(self.path + '/update',
                              request, self.xmlheaders)
            data = rsp.read()
        finally:
            if not self.persistent:
                self.close()

        # Detect old-style error response (HTTP response code
        # of 200 with a non-zero status.
        if data.startswith('<result status="') and \
           not data.startswith('<result status="0"'):
            data = self.decoder(data)[0]
            parsed = parseString(data)
            status = parsed.documentElement.getAttribute('status')
            if status != 0:
                reason = parsed.documentElement.firstChild.nodeValue
                raise SolrException(rsp.status, reason)
        return data

    def __add(self, lst, fields):
        lst.append(u'<doc>')
        for field, value in fields.items():
            # Handle multi-valued fields if values
            # is passed in as a list/tuple
            if not isinstance(value, (list, tuple)):
                values = [value]
            else:
                values = value

            for value in values:
                # ignore values that are not defined
                if value == None:
                    continue
                # Do some basic data conversion
                if isinstance(value, datetime.date):
                    value = datetime.datetime.combine(
                        value,
                        datetime.time(tzinfo=UTC()))
                if isinstance(value, datetime.datetime):
                    value = utc_to_string(value)
                elif isinstance(value, bool):
                    value = value and 'true' or 'false'

                lst.append('<field name=%s>%s</field>' % (
                    (quoteattr(field),
                    escape(unicode(value)))))
        lst.append('</doc>')

    def __repr__(self):
        return ('<SolrConnection (url=%s, '
                'persistent=%s, post_headers=%s, reconnects=%s)>') % (
            self.url, self.persistent,
            self.xmlheaders, self.reconnects)

    def _reconnect(self):
        self.reconnects += 1
        self.close()
        self.conn.connect()
        if self.timeout and _python_version < 2.6:
            if self.scheme == 'http':
                self.conn.sock.settimeout(self.timeout)
            elif self.scheme == 'https':
                self.conn.sock.sock.settimeout(self.timeout)

    def _post(self, url, body, headers):
        attempts = 2  # allow up to 2 attempts
        while attempts:
            try:
                self.conn.request('POST', url, body.encode('UTF-8'), headers)
                return check_response_status(self.conn.getresponse())
            except (socket.error,
                    httplib.ImproperConnectionState,
                    httplib.BadStatusLine):
                    # We include BadStatusLine as they are spurious
                    # and may randomly happen on an otherwise fine
                    # SOLR connection (though not often)
                self._reconnect()
                attempts -= 1
                if not attempts:
                    raise

# ===================================================================
# Response objects
# ===================================================================
class Response(object):
    """
    A container class for a

    A Response object will have the following properties:

          header -- a dict containing any responseHeader values

          results -- a list of matching documents. Each list item will
              be a dict.
    """
    def __init__(self, connection):
        # These are set in ResponseContentHandler.endElement()
        self.header = {}
        self.results = []

        # These are set by parse_query_response().
        # Used only if .next_batch()/previous_batch() is called
        self._connection = connection
        self._params = {}

    def __len__(self):
        """
        Return the number of matching documents contained in this set.
        """
        return len(self.results)

    def __iter__(self):
        """
        Return an iterator of matching documents.
        """
        return iter(self.results)

    def next_batch(self):
        """
        Load the next set of matches.

        By default, SOLR returns 10 at a time.
        """
        try:
            start = int(self.results.start)
        except AttributeError:
            start = 0

        start += len(self.results)
        params = dict(self._params)
        params['start'] = start
        q = params['q']
        del params['q']
        return self._connection.query(q, **params)

    def previous_batch(self):
        """
        Return the previous set of matches
        """
        try:
            start = int(self.results.start)
        except AttributeError:
            start = 0

        if not start:
            return None

        rows = int(self.header.get('rows', len(self.results)))
        start = max(0, start - rows)
        params = dict(self._params)
        params['start'] = start
        params['rows'] = rows
        q = params['q']
        del params['q']
        return self._connection.query(q, **params)

# ===================================================================
# XML Parsing support
# ===================================================================
def parse_query_response(data, params, connection):
    """
    Parse the XML results of a /select call.
    """
    parser = make_parser()
    handler = ResponseContentHandler()
    parser.setContentHandler(handler)
    parser.parse(data)
    if handler.stack[0].children:
        response = handler.stack[0].children[0].final
        response._params = params
        response._connection = connection
        return response
    else:
        return None

class ResponseContentHandler(ContentHandler):
    """
    ContentHandler for the XML results of a /select call.
    (Versions 2.2 (and possibly 2.1))
    """
    def __init__(self):
        self.stack = [Node(None, {})]
        self.in_tree = False

    def startElement(self, name, attrs):
        if not self.in_tree:
            if name != 'response':
                raise SolrException(
                    "Unknown XML response from server: <%s ..." % (
                        name))
            self.in_tree = True

        element = Node(name, attrs)

        # Keep track of new node
        self.stack.append(element)

        # Keep track of children
        self.stack[-2].children.append(element)

    def characters(self, ch):
        self.stack[-1].chars.append(ch)

    def endElement(self, name):
        node = self.stack.pop()

        name = node.name
        value = "".join(node.chars)

        if name == 'int':
            node.final = int(value.strip())

        elif name == 'str':
            node.final = value

        elif name == 'null':
            node.final = None

        elif name == 'long':
            node.final = long(value.strip())

        elif name == 'bool':
            node.final = value.strip().lower().startswith('t')

        elif name == 'date':
            node.final = utc_from_string(value.strip())

        elif name in ('float', 'double', 'status', 'QTime'):
            node.final = float(value.strip())

        elif name == 'response':
            node.final = response = Response(self)
            for child in node.children:
                name = child.attrs.get('name', child.name)
                if name == 'responseHeader':
                    name = 'header'
                elif child.name == 'result':
                    name = 'results'
                    for attr_name in child.attrs.getNames():
                        # We already know it is a response
                        if attr_name != "name":
                            setattr(
                                response,
                                attr_name,
                                child.attrs.get(attr_name))

                setattr(response, name, child.final)

        elif name in ('lst', 'doc'):
            # Represent these with a dict
            node.final = dict(
                    [(cnode.attrs['name'], cnode.final)
                        for cnode in node.children])

        elif name in ('arr',):
            node.final = [cnode.final for cnode in node.children]

        elif name == 'result':
            node.final = Results([cnode.final for cnode in node.children])

        elif name in ('responseHeader',):
            node.final = dict([(cnode.name, cnode.final)
                        for cnode in node.children])
        else:
            raise SolrException("Unknown tag: %s" % name)

        for attr, val in node.attrs.items():
            if attr != 'name':
                setattr(node.final, attr, val)

class Results(list):
    """
    Convenience class containing <result> items
    """
    pass

class Node(object):
    """
    A temporary object used in XML processing. Not seen by end user.
    """
    def __init__(self, name, attrs):
        """
        Final will eventually be the "final" representation of
        this node, whether an int, list, dict, etc.
        """
        self.chars = []
        self.name = name
        self.attrs = attrs
        self.final = None
        self.children = []

    def __repr__(self):
        return '<%s val="%s" %s>' % (
            self.name,
            "".join(self.chars).strip(),
            ' '.join(['%s="%s"' % (attr, val)
                            for attr, val in self.attrs.items()]))

# ===================================================================
# Misc utils
# ===================================================================
def check_response_status(response):
    if response.status != 200:
        ex = SolrException(response.status, response.reason)
        try:
            ex.body = response.read()
        except:
            pass
        raise ex
    return response

# -------------------------------------------------------------------
# Datetime extensions to parse/generate SOLR date formats
# -------------------------------------------------------------------
# A UTC class, for parsing SOLR's returned dates.
class UTC(datetime.tzinfo):
    """
    UTC timezone.
    """
    def utcoffset(self, dt):
        return datetime.timedelta(0)

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return datetime.timedelta(0)

utc = UTC()

def utc_to_string(value):
    """
    Convert datetimes to the subset of ISO 8601 that SOLR expects.
    """
    value = value.astimezone(utc).isoformat()
    if '+' in value:
        value = value.split('+')[0]
    value += 'Z'
    return value

def utc_from_string(value):
    """
    Parse a string representing an ISO 8601 date.
    Note: this doesn't process the entire ISO 8601 standard,
    onle the specific format SOLR promises to generate.
    """
    try:
        if not value.endswith('Z') and value[10] == 'T':
            raise ValueError(value)
        year = int(value[0:4])
        month = int(value[5:7])
        day = int(value[8:10])
        hour = int(value[11:13])
        minute = int(value[14:16])
        microseconds = int(float(value[17:-1]) * 1000000.0)
        second, microsecond = divmod(microseconds, 1000000)
        return datetime.datetime(year, month, day, hour,
            minute, second, microsecond, utc)
    except ValueError:
        raise ValueError("'%s' is not a valid ISO 8601 SOLR date" % value)

redpajama_set_name: RedPajamaGithub


text:
package data;

import org.multij.Module;

@Module
public interface DifferentReturnType {
	public default String test(Object o) {
		return "asdf";
	}
	public default Double test(Integer o) {
		return 5.3;
	}
}


text:
package im.actor.model.modules;

import java.util.ArrayList;

import im.actor.model.ApiConfiguration;
import im.actor.model.AuthState;
import im.actor.model.api.EmailActivationType;
import im.actor.model.api.Sex;
import im.actor.model.api.rpc.RequestCompleteOAuth2;
import im.actor.model.api.rpc.RequestGetOAuth2Params;
import im.actor.model.api.rpc.RequestSendAuthCodeObsolete;
import im.actor.model.api.rpc.RequestSignInObsolete;
import im.actor.model.api.rpc.RequestSignUp;
import im.actor.model.api.rpc.RequestSignUpObsolete;
import im.actor.model.api.rpc.RequestStartEmailAuth;
import im.actor.model.api.rpc.RequestStartPhoneAuth;
import im.actor.model.api.rpc.RequestValidateCode;
import im.actor.model.api.rpc.ResponseAuth;
import im.actor.model.api.rpc.ResponseGetOAuth2Params;
import im.actor.model.api.rpc.ResponseSendAuthCodeObsolete;
import im.actor.model.api.rpc.ResponseStartEmailAuth;
import im.actor.model.api.rpc.ResponseStartPhoneAuth;
import im.actor.model.concurrency.Command;
import im.actor.model.concurrency.CommandCallback;
import im.actor.model.crypto.CryptoUtils;
import im.actor.model.entity.ContactRecord;
import im.actor.model.entity.ContactRecordType;
import im.actor.model.entity.User;
import im.actor.model.modules.updates.internal.LoggedIn;
import im.actor.model.network.RpcCallback;
import im.actor.model.network.RpcException;

public class Auth extends BaseModule {

    private static final String KEY_DEVICE_HASH = "device_hash";

    private static final String KEY_AUTH = "auth_yes";
    private static final String KEY_AUTH_UID = "auth_uid";
    private static final String KEY_PHONE = "auth_phone";
    public static final String KEY_EMAIL = "auth_email";
    private static final String KEY_SMS_HASH = "auth_sms_hash";
    private static final String KEY_SMS_CODE = "auth_sms_code";
    private static final String KEY_TRANSACTION_HASH = "auth_transaction_hash";
    private static final String KEY_CODE = "auth_code";
    public static final String KEY_OAUTH_REDIRECT_URL = "oauth_redirect_url";

    private AuthState state;

    private byte[] deviceHash;
    private ApiConfiguration apiConfiguration;

    private int myUid;

    public Auth(Modules modules) {
        super(modules);

        this.myUid = preferences().getInt(KEY_AUTH_UID, 0);

        // Keep device hash always stable across launch
        deviceHash = preferences().getBytes(KEY_DEVICE_HASH);
        if (deviceHash == null) {
            deviceHash = CryptoUtils.SHA256(modules.getConfiguration().getApiConfiguration().getDeviceString().getBytes());
            preferences().putBytes(KEY_DEVICE_HASH, deviceHash);
        }

        apiConfiguration = modules.getConfiguration().getApiConfiguration();
    }

    public void run() {
        if (preferences().getBool(KEY_AUTH, false)) {
            state = AuthState.LOGGED_IN;
            modules().onLoggedIn();

            // Notify Analytics
            User user = modules().getUsersModule().getUsers().getValue(myUid);
            ArrayList<Long> records = new ArrayList<Long>();
            for (ContactRecord contactRecord : user.getRecords()) {
                if (contactRecord.getRecordType() == ContactRecordType.PHONE) {
                    records.add(Long.parseLong(contactRecord.getRecordData()));
                }
            }
            modules().getAnalytics().onLoggedIn(CryptoUtils.hex(deviceHash), user.getUid(),
                    records.toArray(new Long[records.size()]), user.getName());
        } else {
            state = AuthState.AUTH_START;

            // Notify Analytics
            modules().getAnalytics().onLoggedOut(CryptoUtils.hex(deviceHash));
        }
    }

    private void onLoggedIn(final CommandCallback<AuthState> callback, ResponseAuth response) {

        preferences().putBool(KEY_AUTH, true);
        state = AuthState.LOGGED_IN;
        myUid = response.getUser().getId();
        preferences().putInt(KEY_AUTH_UID, myUid);
        modules().onLoggedIn();
        updates().onUpdateReceived(new LoggedIn(response, new Runnable() {
            @Override
            public void run() {
                state = AuthState.LOGGED_IN;

                callback.onResult(state);

                // Notify Analytics
                User user = modules().getUsersModule().getUsers().getValue(myUid);
                ArrayList<Long> records = new ArrayList<Long>();
                for (ContactRecord contactRecord : user.getRecords()) {
                    if (contactRecord.getRecordType() == ContactRecordType.PHONE) {
                        records.add(Long.parseLong(contactRecord.getRecordData()));
                    }
                }
                modules().getAnalytics().onLoggedInPerformed(CryptoUtils.hex(deviceHash), user.getUid(),
                        records.toArray(new Long[records.size()]), user.getName());
            }
        }), 500L);
    }

    public int myUid() {
        return myUid;
    }

    public AuthState getAuthState() {
        return state;
    }

    public Command<AuthState> requestSmsObsolete(final long phone) {
        return new Command<AuthState>() {
            @Override
            public void start(final CommandCallback<AuthState> callback) {
                modules().getAnalytics().trackCodeRequest(phone);

                request(new RequestSendAuthCodeObsolete(phone, apiConfiguration.getAppId(),
                                apiConfiguration.getAppKey()),
                        new RpcCallback<ResponseSendAuthCodeObsolete>() {
                            @Override
                            public void onResult(final ResponseSendAuthCodeObsolete response) {
                                preferences().putLong(KEY_PHONE, phone);
                                preferences().putString(KEY_SMS_HASH, response.getSmsHash());
                                state = AuthState.CODE_VALIDATION_PHONE;

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        callback.onResult(state);
                                    }
                                });
                            }

                            @Override
                            public void onError(final RpcException e) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        callback.onError(e);
                                    }
                                });
                            }
                        });
            }
        };
    }

    public Command<AuthState> sendCodeObsolete(final int code) {
        return new Command<AuthState>() {
            @Override
            public void start(final CommandCallback<AuthState> callback) {
                request(
                        new RequestSignInObsolete(
                                preferences().getLong(KEY_PHONE, 0),
                                preferences().getString(KEY_SMS_HASH),
                                code + "",
                                deviceHash,
                                apiConfiguration.getDeviceTitle(),
                                apiConfiguration.getAppId(), apiConfiguration.getAppKey()),
                        new RpcCallback<ResponseAuth>() {

                            @Override
                            public void onResult(ResponseAuth response) {
                                onLoggedIn(callback, response);
                            }

                            @Override
                            public void onError(final RpcException e) {
                                if ("PHONE_CODE_EXPIRED".equals(e.getTag())) {
                                    resetAuth();
                                } else if ("PHONE_NUMBER_UNOCCUPIED".equals(e.getTag())) {
                                    preferences().putInt(KEY_SMS_CODE, code);
                                    state = AuthState.SIGN_UP;
                                    callback.onResult(AuthState.SIGN_UP);
                                    return;
                                }
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        callback.onError(e);
                                    }
                                });
                            }
                        });
            }
        };
    }

    public Command<AuthState> signUpObsolete(final String firstName, final String avatarPath, final boolean isSilent) {
        return new Command<AuthState>() {
            @Override
            public void start(final CommandCallback<AuthState> callback) {
                request(new RequestSignUpObsolete(preferences().getLong(KEY_PHONE, 0),
                        preferences().getString(KEY_SMS_HASH),
                        preferences().getInt(KEY_SMS_CODE, 0) + "",
                        firstName,
                        deviceHash,
                        apiConfiguration.getDeviceTitle(),
                        apiConfiguration.getAppId(), apiConfiguration.getAppKey(),
                        isSilent), new RpcCallback<ResponseAuth>() {
                    @Override
                    public void onResult(ResponseAuth response) {
                        onLoggedIn(callback, response);
                        if (avatarPath != null) {
                            modules().getProfile().changeAvatar(avatarPath);
                        }
                    }

                    @Override
                    public void onError(final RpcException e) {
                        if ("PHONE_CODE_EXPIRED".equals(e.getTag())) {
                            resetAuth();
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError(e);
                            }
                        });
                    }
                });
            }
        };
    }

    public Command<AuthState> requestStartEmailAuth(final String email) {
        return new Command<AuthState>() {
            @Override
            public void start(final CommandCallback<AuthState> callback) {
                request(new RequestStartEmailAuth(email,
                        apiConfiguration.getAppId(),
                        apiConfiguration.getAppKey(),
                        deviceHash,
                        apiConfiguration.getDeviceTitle()
                ), new RpcCallback<ResponseStartEmailAuth>() {
                    @Override
                    public void onResult(ResponseStartEmailAuth response) {
                        preferences().putString(KEY_EMAIL, email);
                        preferences().putString(KEY_TRANSACTION_HASH, response.getTransactionHash());
                        EmailActivationType emailActivationType = response.getActivationType();
                        if(emailActivationType.equals(EmailActivationType.OAUTH2)){
                            state = AuthState.GET_OAUTH_PARAMS;
                        }else if(emailActivationType.equals(EmailActivationType.CODE)){
                            state = AuthState.CODE_VALIDATION_EMAIL;
                        }

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onResult(state);
                            }
                        });
                    }

                    @Override
                    public void onError(final RpcException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError(e);
                                e.printStackTrace();
                            }
                        });
                    }
                });
            }
        };
    }

    public Command<AuthState> requestStartPhoneAuth(final long phone) {
        return new Command<AuthState>() {
            @Override
            public void start(final CommandCallback<AuthState> callback) {
                request(new RequestStartPhoneAuth(phone,
                        apiConfiguration.getAppId(),
                        apiConfiguration.getAppKey(),
                        deviceHash,
                        apiConfiguration.getDeviceTitle()
                ), new RpcCallback<ResponseStartPhoneAuth>() {
                    @Override
                    public void onResult(ResponseStartPhoneAuth response) {
                        preferences().putLong(KEY_PHONE, phone);
                        preferences().putString(KEY_TRANSACTION_HASH, response.getTransactionHash());

                        state = AuthState.CODE_VALIDATION_PHONE;

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onResult(state);
                            }
                        });
                    }

                    @Override
                    public void onError(final RpcException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError(e);
                                e.printStackTrace();
                            }
                        });
                    }
                });
            }
        };
    }

    public Command<AuthState> requestGetOAuth2Params() {
        return new Command<AuthState>() {
            @Override
            public void start(final CommandCallback<AuthState> callback) {
                request(new RequestGetOAuth2Params(preferences().getString(KEY_TRANSACTION_HASH), "https://actor.im/auth/oauth2callback"),
                        new RpcCallback<ResponseGetOAuth2Params>() {
                            @Override
                            public void onResult(final ResponseGetOAuth2Params response) {
                                state = AuthState.COMPLETE_OAUTH;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        preferences().putString(KEY_OAUTH_REDIRECT_URL, response.getAuthUrl());
                                        callback.onResult(state);
                                    }
                                });
                            }

                            @Override
                            public void onError(final RpcException e) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        callback.onError(e);
                                        e.printStackTrace();
                                    }
                                });
                            }
                        });
            }
        };
    }

    public Command<AuthState> requestCompleteOauth(final String code){
        return new Command<AuthState>() {
            @Override
            public void start(final CommandCallback<AuthState> callback) {
                request(new RequestCompleteOAuth2(preferences().getString(KEY_TRANSACTION_HASH), code), new RpcCallback<ResponseAuth>() {
                    @Override
                    public void onResult(ResponseAuth response) {
                        onLoggedIn(callback, response);
                    }

                    @Override
                    public void onError(final RpcException e) {
                        if ("EMAIL_EXPIRED".equals(e.getTag())) {
                            resetAuth();
                        } else if ("EMAIL_UNOCCUPIED".equals(e.getTag())) {
                            preferences().putString(KEY_CODE, code);
                            state = AuthState.SIGN_UP;
                            callback.onResult(AuthState.SIGN_UP);
                            return;
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError(e);
                            }
                        });
                    }
                });
            }
        };
    }

    public Command<AuthState> signUp(final String name, final Sex sex, final String avatarPath){
        return new Command<AuthState>() {
            @Override
            public void start(final CommandCallback<AuthState> callback) {
                request(new RequestSignUp(preferences().getString(KEY_TRANSACTION_HASH), name, sex), new RpcCallback<ResponseAuth>() {
                    @Override
                    public void onResult(ResponseAuth response) {
                        onLoggedIn(callback, response);
                        if (avatarPath != null) {
                            modules().getProfile().changeAvatar(avatarPath);
                        }
                    }

                    @Override
                    public void onError(final RpcException e) {
                        if ("EMAIL_CODE_EXPIRED".equals(e.getTag())) {
                            resetAuth();
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError(e);
                            }
                        });
                    }
                });
            }
        };
    }

    public Command<AuthState> requestValidateCode(final String code){
        return new Command<AuthState>() {
            @Override
            public void start(final CommandCallback<AuthState> callback) {
                request(new RequestValidateCode(preferences().getString(KEY_TRANSACTION_HASH), code), new RpcCallback<ResponseAuth>() {
                    @Override
                    public void onResult(ResponseAuth response) {
                        onLoggedIn(callback, response);
                    }

                    @Override
                    public void onError(final RpcException e) {
                        if ("PHONE_CODE_EXPIRED".equals(e.getTag()) || "EMAIL_CODE_EXPIRED".equals(e.getTag())) {
                            resetAuth();
                        } else if ("PHONE_NUMBER_UNOCCUPIED".equals(e.getTag()) || "EMAIL_UNOCCUPIED".equals(e.getTag())) {
                            preferences().putString(KEY_CODE, code);
                            state = AuthState.SIGN_UP;
                            callback.onResult(AuthState.SIGN_UP);
                            return;
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                callback.onError(e);
                            }
                        });
                    }
                });
            }
        };
    }

    public void resetAuth() {
        state = AuthState.AUTH_START;
    }

    public long getPhone() {
        return preferences().getLong(KEY_PHONE, 0);
    }

    public void resetModule() {
        // Clearing authentication
        state = AuthState.AUTH_START;
        myUid = 0;
        preferences().putBool(KEY_AUTH, false);
        preferences().putInt(KEY_AUTH_UID, 0);
        preferences().putLong(KEY_PHONE, 0);
        preferences().putString(KEY_SMS_HASH, null);
        preferences().putInt(KEY_SMS_CODE, 0);
    }

    public String getEmail() {
        return preferences().getString(KEY_EMAIL);
    }

}


text:
<?php

	/**
	 * Created by PhpStorm.
	 * User: Mark Simonds
	 * Date: 4/25/16
	 * Time: 10:27 AM
	 */

	namespace Zaycon\Whatcounts_Rest;

	use Zaycon\Whatcounts_Rest\Models\Campaign;
    use Zaycon\Whatcounts_Rest\Models\MailingList;

    class CampaignTest extends WhatCountsTest
	{
		private $campaign;
		private $campaigns;

		public function setUp()
		{
			parent::setUp();
		}

		public function tearDown()
		{
			parent::tearDown();

			unset($this->campaigns);

			if (isset($this->campaign))
			{
				unset($this->campaign);
			}
		}

		public function testGetCampaigns()
		{
			/** @var WhatCounts $whatcounts */
			$whatcounts = $this->whatcounts;

			$this->campaigns = $whatcounts->getCampaigns();

			$this->assertInternalType('array',$this->campaigns);

			foreach ($this->campaigns as $campaign)
			{
				/** @var Models\Campaign $campaign */
				$this->assertInstanceOf('Zaycon\Whatcounts_Rest\Models\Campaign', $campaign);
			}
		}

		public function testGetCampaignById()
		{
			/** @var WhatCounts $whatcounts */
			$whatcounts = $this->whatcounts;
			/** @var Models\Campaign $campaign */
			$campaign = $this->campaign;

			$campaign = $whatcounts->getCampaignById($campaign->getId());

			$this->assertInstanceOf('Zaycon\Whatcounts_Rest\Models\Campaign', $campaign);
		}

		public function testGetCampaignByDateRange()
        {
            /** @var WhatCounts $whatcounts */
            $whatcounts = $this->whatcounts;

            $start_date = '2016-03-01';
            $end_date = '2016-04-01';

            $this->campaigns = $whatcounts->getCampaignsByDateRange($start_date, $end_date);

            $this->assertInternalType('array',$this->campaigns);

            foreach ($this->campaigns as $campaign)
            {
                /** @var Models\Campaign $campaign */
                $this->assertInstanceOf('Zaycon\Whatcounts_Rest\Models\Campaign', $campaign);
            }
        }

		public function testSendSingleCampaign()
        {
            /** @var WhatCounts $whatcounts */
            $whatcounts = $this->whatcounts;

            $campaign = new Campaign();
            $campaign
                ->setName('Single Campaign Test')
                ->setForcedFormat(99);

            $list = $whatcounts->getListById(34);
            $subscriber = $whatcounts->findSubscribers(NULL, 'mark@zayconfresh.com');
            $subscriber = $subscriber[0];
            $template = $whatcounts->getTemplateById(75);

            $sendSingleCampaign = new Campaign($sendSingleCampaign = $whatcounts->sendSingleCampaign($campaign, $list, $subscriber, $template));
            $this->assertInstanceOf('Zaycon\Whatcounts_Rest\Models\Campaign', $sendSingleCampaign);
        }

        public function testQuickSendSingleCampaign()
        {
            /** @var WhatCounts $whatcounts */
            $whatcounts = $this->whatcounts;

            $campaign_name = 'Quick Single Campaign Test';
            $list_id = 34;
            $template_id = 75;
            $to_email = 'mark@zayconfresh.com';

            $quickSendSingleCampaign = new Campaign($whatcounts->quickSendSingleCampaign($campaign_name, $list_id, $template_id, $to_email));
            $this->assertInstanceOf('Zaycon\Whatcounts_Rest\Models\Campaign', $quickSendSingleCampaign);
        }
	}


text:
#include <ExampleObjects/ValueObjects/customervalueobject.hpp>
#include <rp/exception.hpp>
#include <iostream>
#include <string>
#include <boost/algorithm/string/case_conv.hpp>

namespace AccountExample {

    const char* CustomerValueObject::mPropertyNames[] = {
        // The two values below are not desired in the return value of ohObjectPropertyNames().
        // For now we just comment them out as this seems not to break anything.
        //"ObjectId",
        //"ClassName",
        "Name",
        "Age",
        "Permanent"};

    const std::set<std::string>& CustomerValueObject::getSystemPropertyNames() const {
        static std::set<std::string> ret;
        if(ret.empty())
            ret = std::set<std::string>(mPropertyNames,
                mPropertyNames + sizeof(mPropertyNames)/sizeof(const char*));
        return ret;
    }

	std::vector<std::string> CustomerValueObject::getPropertyNamesVector() const {
        std::vector<std::string> ret(mPropertyNames,
            mPropertyNames + sizeof(mPropertyNames)/sizeof(const char*));
        for (std::map<std::string, reposit::property_t>::const_iterator i
            = userProperties.begin(); i != userProperties.end(); ++i)
            ret.push_back(i->first);
        return ret;
	}

    reposit::property_t CustomerValueObject::getSystemProperty(const std::string& name) const {
        std::string nameUpper = boost::algorithm::to_upper_copy(name);
        if (strcmp(nameUpper.c_str(), "OBJECTID")==0)
            return objectId_;
        else if (strcmp(nameUpper.c_str(), "CLASSNAME")==0)
            return className_;
        else if (strcmp(nameUpper.c_str(), "PERMANENT")==0)
            //return (long)permanent_;
            return (bool)permanent_;
        else if (strcmp(nameUpper.c_str(), "NAME")==0)
            return name_;
        else if (strcmp(nameUpper.c_str(), "AGE")==0)
            return age_;
        else
            RP_FAIL("Error: attempt to retrieve non-existent Property: '" + name + "'");
    }

    void CustomerValueObject::setSystemProperty(const std::string& name, const reposit::property_t& value) {
        std::string nameUpper = boost::algorithm::to_upper_copy(name);
        if (strcmp(nameUpper.c_str(), "OBJECTID")==0)
            objectId_ = boost::get<std::string>(value);
        else if (strcmp(nameUpper.c_str(), "CLASSNAME")==0)
            className_ = boost::get<std::string>(value);
        else if (strcmp(nameUpper.c_str(), "PERMANENT")==0)
            permanent_ = boost::get<bool>(value);
        else if (strcmp(nameUpper.c_str(), "NAME")==0)
            name_ = boost::get<std::string>(value);
        else if (strcmp(nameUpper.c_str(), "AGE")==0)
            age_ = boost::get<long>(value);
        else
            RP_FAIL("Error: attempt to retrieve non-existent Property: '" + name + "'");
    }

}


text:
.. _features:

Features
========

Open Virtual Network (OVN) offers the following virtual network
services:

* Layer-2 (switching)

  Native implementation. Replaces the conventional Open vSwitch (OVS)
  agent.

* Layer-3 (routing)

  Native implementation that supports distributed routing.  Replaces the
  conventional Neutron L3 agent. This includes transparent L3HA :doc::`routing`
  support, based on BFD monitorization integrated in core OVN.

* DHCP

  Native distributed implementation.  Replaces the conventional Neutron DHCP
  agent.  Note that the native implementation does not yet support DNS
  features.

* DPDK

  OVN and the OVN mechanism driver may be used with OVS using either the Linux
  kernel datapath or the DPDK datapath.

* Trunk driver

  Uses OVN's functionality of parent port and port tagging to support trunk
  service plugin. One has to enable the 'trunk' service plugin in neutron
  configuration files to use this feature.

* VLAN tenant networks

  The OVN driver does support VLAN tenant networks when used
  with OVN version 2.11 (or higher).

* DNS

  Native implementation. Since the version 2.8 OVN contains a built-in
  DNS implementation.

* Port Forwarding

  The OVN driver supports port forwarding as an extension of floating
  IPs. Enable the 'port_forwarding' service plugin in neutron configuration
  files to use this feature.

* Packet Logging

  Packet logging service is designed as a Neutron plug-in that captures network
  packets for relevant resources when the registered events occur. OVN supports
  this feature based on security groups.

* Segments

  Allows for Network segments ranges to be used with OVN. Requires OVN
  version 20.06 or higher.

.. TODO What about tenant networks?

* Routed provider networks

  Allows for multiple localnet ports to be attached to a single Logical
  Switch entry. This work also assumes that only a single localnet
  port (of the same Logical Switch) is actually mapped to a given
  hypervisor. Requires OVN version 20.06 or higher.

The following Neutron API extensions are supported with OVN:

+----------------------------------+---------------------------------+
| Extension Name                   | Extension Alias                 |
+==================================+=================================+
| Allowed Address Pairs            | allowed-address-pairs           |
+----------------------------------+---------------------------------+
| Auto Allocated Topology Services | auto-allocated-topology         |
+----------------------------------+---------------------------------+
| Availability Zone                | availability_zone               |
+----------------------------------+---------------------------------+
| Default Subnetpools              | default-subnetpools             |
+----------------------------------+---------------------------------+
| DNS Integration                  | dns-integration                 |
+----------------------------------+---------------------------------+
| DNS domain for ports             | dns-domain-ports                |
+----------------------------------+---------------------------------+
| DNS domain names with keywords   | dns-integration-domain-keywords |
+----------------------------------+---------------------------------+
| Subnet DNS publish fixed IP      | subnet-dns-publish-fixed-ip     |
+----------------------------------+---------------------------------+
| Multi Provider Network           | multi-provider                  |
+----------------------------------+---------------------------------+
| Network IP Availability          | network-ip-availability         |
+----------------------------------+---------------------------------+
| Network Segment                  | segment                         |
+----------------------------------+---------------------------------+
| Neutron external network         | external-net                    |
+----------------------------------+---------------------------------+
| Neutron Extra DHCP opts          | extra_dhcp_opt                  |
+----------------------------------+---------------------------------+
| Neutron Extra Route              | extraroute                      |
+----------------------------------+---------------------------------+
| Neutron L3 external gateway      | ext-gw-mode                     |
+----------------------------------+---------------------------------+
| Neutron L3 Router                | router                          |
+----------------------------------+---------------------------------+
| Network MTU                      | net-mtu                         |
+----------------------------------+---------------------------------+
| Packet Logging                   | logging                         |
+----------------------------------+---------------------------------+
| Port Binding                     | binding                         |
+----------------------------------+---------------------------------+
| Port Bindings Extended           | binding-extended                |
+----------------------------------+---------------------------------+
| Port Forwarding                  | port_forwarding                 |
+----------------------------------+---------------------------------+
| Port MAC address Regenerate      | port-mac-address-regenerate     |
+----------------------------------+---------------------------------+
| Port Security                    | port-security                   |
+----------------------------------+---------------------------------+
| Provider Network                 | provider                        |
+----------------------------------+---------------------------------+
| Quality of Service               | qos                             |
+----------------------------------+---------------------------------+
| Quota management support         | quotas                          |
+----------------------------------+---------------------------------+
| RBAC Policies                    | rbac-policies                   |
+----------------------------------+---------------------------------+
| Resource revision numbers        | standard-attr-revisions         |
+----------------------------------+---------------------------------+
| security-group                   | security-group                  |
+----------------------------------+---------------------------------+
| standard-attr-description        | standard-attr-description       |
+----------------------------------+---------------------------------+
| Subnet Allocation                | subnet_allocation               |
+----------------------------------+---------------------------------+
| Subnet service types             | subnet-service-types            |
+----------------------------------+---------------------------------+
| Tag support                      | standard-attr-tag               |
+----------------------------------+---------------------------------+
| Time Stamp Fields                | standard-attr-timestamp         |
+----------------------------------+---------------------------------+