text:
// ========================================================================
// Copyright 2008-2009 NEXCOM Systems
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================

package org.cipango.diameter.base;

import static org.cipango.diameter.Factory.newAnswer;
import static org.cipango.diameter.Factory.newCommand;
import static org.cipango.diameter.Factory.newRequest;
import static org.cipango.diameter.Factory.newResultCode;
import static org.cipango.diameter.Factory.newType;

import java.io.IOException;
import java.lang.reflect.Array;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.net.ntp.TimeStamp;
import org.cipango.diameter.AVP;
import org.cipango.diameter.AVPList;
import org.cipango.diameter.DataFormat;
import org.cipango.diameter.DiameterCommand;
import org.cipango.diameter.ResultCode;
import org.cipango.diameter.Type;
import org.cipango.diameter.io.Codecs;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.Utf8StringBuffer;

/**
 * Defines all data formats, commands and AVPs specified in Diameter Base.
 *
 * @see RFC 3588
 */
public abstract class Common
{
	public static final int IETF_VENDOR_ID = 0;

	// ======================== Data formats ========================

	/**
	 * The Data field is specified as a sequence of AVPs i.e diameter messages or grouped AVPs
	 */
	public static DataFormat<AVPList> __grouped = new DataFormat<AVPList>("Grouped")
	{
		public AVPList decode(Buffer buffer) throws IOException
		{
			AVPList avps = new AVPList();
			while (buffer.hasContent())
			{
				AVP<?> avp = Codecs.__avp.decode(buffer);
				avps.add(avp);
			}
			return avps;
		}

		public Buffer encode(Buffer buffer, AVPList avps) throws IOException
		{
			for (AVP<?> avp : avps)
			{
				buffer = Codecs.__avp.encode(buffer, avp);
			}
			return buffer;
		}
	};

	/**
	 * The data contains arbitrary data of variable length
	 */
	public static final DataFormat<byte[]> __octetString = new DataFormat<byte[]>("OctetString")
	{
		public byte[] decode(Buffer buffer) throws IOException
		{
			return buffer.asArray();
		}

		public Buffer encode(Buffer buffer, byte[] value) throws IOException
		{
			buffer = ensureSpace(buffer, value.length);
			buffer.put(value);
			return buffer;
		}
	};

	/**
	 * The UTF8String format is derived from the OctetString AVP Base Format.
     * This is a human readable string represented using the
     * ISO/IEC IS 10646-1 character set, encoded as an OctetString using
     * the UTF-8 [UFT8] transformation format described in RFC 2279.
	 */
	public static final DataFormat<String> __utf8String = new DataFormat<String>("utf8String")
	{
		public String decode(Buffer buffer) throws IOException
		{
			byte[] bytes = buffer.array();
			if (bytes != null)
				return StringUtil.toUTF8String(bytes, buffer.getIndex(), buffer.length());

			Utf8StringBuffer b = new Utf8StringBuffer(buffer.length());
			for (int i = buffer.getIndex(), c=0; c < buffer.length(); i++,c++)
                b.append(buffer.peek(i));
            return b.toString();
		}

		public Buffer encode(Buffer buffer, String value) throws IOException
		{
			byte[] bytes = value.getBytes(StringUtil.__UTF8);
			buffer = ensureSpace(buffer, bytes.length);
			buffer.put(bytes);
			return buffer;
		}
	};

	public static final DataFormat<InetAddress> __address = new DataFormat<InetAddress>("address")
	{
		public static final int IPV4 = 1;
		public static final int IPV6 = 2;

		public InetAddress decode(Buffer buffer) throws IOException
		{
			int type = (buffer.get() & 0xff) << 8 | (buffer.get() & 0xff);
			byte[] b;
			if (type == IPV4)
				b = new byte[4];
			else if (type == IPV6)
				b = new byte[16];
			else
				throw new IOException("Unknown address type: " + type);
			buffer.get(b, 0, b.length);

			return InetAddress.getByAddress(b);
		}

		public Buffer encode(Buffer buffer, InetAddress address) throws IOException
		{
			int type = address instanceof Inet4Address ? IPV4 : IPV6;
			buffer = ensureSpace(buffer, 2 + (type == IPV4 ? 4 : 16));
			buffer.put((byte) 0); buffer.put((byte) type);

			buffer.put(address.getAddress());
			return buffer;
		}
	};

	public static final DataFormat<Date> __date = new DataFormat<Date>("time")
	{
		public Date decode(Buffer buffer) throws IOException
		{
			long seconds = 0;

			for (int i = 0; i < 4; i++)
			{
				seconds |= (buffer.get() & 0xFF) << ((3 - i) * 8);
			}
			return new Date(TimeStamp.getTime(seconds << 32));
		}

		public Buffer encode(Buffer buffer, Date date) throws IOException
		{
			buffer = ensureSpace(buffer, 4);
			byte[] data = new byte[4];
			long nptDate = TimeStamp.getNtpTime(date.getTime()).ntpValue();

			for(int i = 0, shift = 56; i < 4; i++, shift -= 8)
			{
				data[i] = (byte)(0xFF & (nptDate >> shift));
			}
			buffer.put(data);
			return buffer;
		}
	};

	public static final DataFormat<Integer> __unsigned32 = new DataFormat<Integer>("unsigned32")
	{
		public Integer decode(Buffer buffer) throws IOException
		{
			return getInt(buffer);
		}

		public Buffer encode(Buffer buffer, Integer value) throws IOException
		{
			buffer = ensureSpace(buffer, 4);
			return putInt(buffer, value);
		}
	};

	public static class EnumDataFormat<E extends Enum<E>> extends DataFormat<E>
	{
		private E[] enums;
		private int _offset;

		@SuppressWarnings("unchecked")
		public EnumDataFormat(Class<E> clazz)
		{
			super("Enumerated " + clazz.getSimpleName());
			EnumSet<E> values = EnumSet.allOf(clazz);
			//System.out.println(values);
			enums = (E[]) Array.newInstance(clazz, values.size());
			values.toArray(enums);
		}

		public EnumDataFormat(Class<E> clazz, int offset)
		{
			this(clazz);
			_offset = offset;
		}

		public E decode(Buffer buffer) throws IOException
		{
			int i = __unsigned32.decode(buffer);
			return enums[i-_offset];
		}

		public Buffer encode(Buffer buffer, E value) throws IOException
		{
			return __unsigned32.encode(buffer, value.ordinal() + _offset);
		}
	}

	public static interface CustomEnumValues
	{
		int getValue();
	}

	public static class CustomEnumDataFormat<E extends Enum<E> & CustomEnumValues> extends DataFormat<E>
	{
		private Map<Integer, E> enums = new HashMap<Integer, E>();

		public CustomEnumDataFormat(Class<E> clazz)
		{
			super("Enumerated " + clazz.getSimpleName());
			EnumSet<E> values = EnumSet.allOf(clazz);

			for (E e : values)
			{
				enums.put(e.getValue(), e);
			}
		}

		public E decode(Buffer buffer) throws IOException
		{
			int i = Common.__unsigned32.decode(buffer);
			return enums.get(i);
		}

		public Buffer encode(Buffer buffer, E value) throws IOException
		{
			return Common.__unsigned32.encode(buffer, value.getValue());
		}
	}

	public static Type<String> newUTF8StringType(String name, int code)
	{
		return newType(name, code, __utf8String);
	}

	public static Type<AVPList> newGroupedType(String name, int code)
	{
		return newType(name, code, __grouped);
	}

	public static Type<Integer> newUnsigned32Type(String name, int code)
	{
		return newType(name, code, __unsigned32);
	}

	public static Type<InetAddress> newAddressType(String name, int code)
	{
		return newType(name, code, __address);
	}

	public static Type<Date> newDateType(String name, int code)
	{
		return newType(name, code, __date);
	}

	public static Type<byte[]> newOctetStringType(String name, int code)
	{
		return newType(name, code, __octetString);
	}

	public static <T extends Enum<T>> Type<T> newEnumType(String name,
			int code, Class<T> clazz)
	{
		return newEnumType(name, IETF_VENDOR_ID, code, clazz);
	}

	public static <T extends Enum<T>> Type<T> newEnumType(String name,
			int vendorId, int code, Class<T> clazz)
	{
		return newType(name, vendorId, code, new EnumDataFormat<T>(clazz));
	}

	// ======================== AVP Types ========================

	public static final int
		USER_NAME_ORDINAL = 1,
		AUTH_APPLICATION_ID_ORDINAL = 258,
		AUTH_SESSION_STATE_ORDINAL = 277,
		ACCT_APPLICATION_ID_ORDINAL = 259,
		SESSION_ID_ORDINAL = 263,
		DESTINATION_HOST_ORDINAL = 293,
		DESTINATION_REALM_ORDINAL = 283,
		DISCONNECT_CAUSE_ORDINAL = 273,
		ORIGIN_HOST_ORDINAL = 264,
		ORIGIN_REALM_ORDINAL = 296,
		ORIGIN_STATE_ID_ORDINAL= 278,
		FIRMWARE_REVISION_ORDINAL = 267,
		HOST_IP_ADDRESS_ORDINAL = 257,
		RESULT_CODE_ORDINAL = 268,
		SUPPORTED_VENDOR_ID_ORDINAL = 265,
		VENDOR_ID_ORDINAL = 266,
		VENDOR_SPECIFIC_APPLICATION_ID_ORDINAL = 260,
		PRODUCT_NAME_ORDINAL = 269,
		FAILED_AVP_ORDINAL = 279,
		REDIRECT_HOST_ORDINAL = 292,
		EXPERIMENTAL_RESULT_ORDINAL = 297,
		EXPERIMENTAL_RESULT_CODE_ORDINAL = 298;

	public static enum AuthSessionState
	{
		/**
		 * STATE_MAINTAINED 0.
		 *
 This value is used to specify that session state is
		 * being maintained, and the access device MUST issue a session termination
		 * message when service to the user is terminated. This is the default
		 * value.
		 */
		STATE_MAINTAINED,

		/**
		 * NO_STATE_MAINTAINED 1
		 *
This value is used to specify that no session
		 * termination messages will be sent by the access device upon expiration of
		 * the Authorization-Lifetime.
		 */
		NO_STATE_MAINTAINED
	}

	/**
	 * The Auth-Session-State AVP (AVP Code 277) is of type Enumerated and
	 * specifies whether state is maintained for a particular session. The
	 * client MAY include this AVP in requests as a hint to the server, but the
	 * value in the server's answer message is binding.
	 *
	 * @see AuthSessionState
	 */
	public static final Type<AuthSessionState> AUTH_SESSION_STATE = newEnumType(
			"Auth-Session-State", AUTH_SESSION_STATE_ORDINAL, AuthSessionState.class);

	/**
	 * The Auth-Application-Id AVP (AVP Code 258) is of type Unsigned32 and
     * is used in order to advertise support of the Authentication and
     * Authorization portion of an application (see Section 2.4).  The
     * Auth-Application-Id MUST also be present in all Authentication and/or
     * Authorization messages that are defined in a separate Diameter
     * specification and have an Application ID assigned.
     */
	public static final Type<Integer> AUTH_APPLICATION_ID = newUnsigned32Type(
			"Auth-Application-Id", AUTH_APPLICATION_ID_ORDINAL);

	/**
	 * The Acct-Application-Id AVP (AVP Code 259) is of type Unsigned32 and
     * is used in order to advertise support of the Accounting portion of an
     * application (see Section 2.4).  The Acct-Application-Id MUST also be
     * present in all Accounting messages.  Exactly one of the Auth-
     * Application-Id and Acct-Application-Id AVPs MAY be present.
	 */
	public static final Type<Integer> ACCT_APPLICATION_ID = newUnsigned32Type(
			"Acct-Application-Id", ACCT_APPLICATION_ID_ORDINAL);

	/**
	 * The Origin-Host AVP (AVP Code 264) is of type DiameterIdentity, and MUST
	 * be present in all Diameter messages. This AVP identifies the endpoint
	 * that originated the Diameter message. Relay agents MUST NOT modify this
	 * AVP. The value of the Origin-Host AVP is guaranteed to be unique within a
	 * single host. Note that the Origin-Host AVP may resolve to more than one
	 * address as the Diameter peer may support more than one address.
	 */
	public static final Type<String> ORIGIN_HOST = newUTF8StringType("Origin-Host", ORIGIN_HOST_ORDINAL);

	/**
	 * The Origin-Realm AVP (AVP Code 296) is of type DiameterIdentity. This AVP
	 * contains the Realm of the originator of any Diameter message and MUST be
	 * present in all messages.
	 */
	public static final Type<String> ORIGIN_REALM = newUTF8StringType("Origin-Realm", ORIGIN_REALM_ORDINAL);

	/**
	 * The Destination-Realm AVP (AVP Code 283) is of type DiameterIdentity, and
	 * contains the realm the message is to be routed to. The Destination-Realm
	 * AVP MUST NOT be present in Answer messages. Diameter Clients insert the
	 * realm portion of the User-Name AVP. Diameter servers initiating a request
	 * message use the value of the Origin-Realm AVP from a previous message
	 * received from the intended target host (unless it is known a priori).
	 * When present, the Destination-Realm AVP is used to perform message
	 * routing decisions.
	 *

	 * Request messages whose ABNF does not list the Destination-Realm AVP as a
	 * mandatory AVP are inherently non-routable messages.
	 *

	 * This AVP SHOULD be placed as close to the Diameter header as possible.
	 */
	public static final Type<String> DESTINATION_REALM = newUTF8StringType(
			"Destination-Realm", DESTINATION_REALM_ORDINAL);

	/**
	 * The Destination-Host AVP (AVP Code 293) is of type DiameterIdentity. This
	 * AVP MUST be present in all unsolicited agent initiated messages, MAY be
	 * present in request messages, and MUST NOT be present in Answer messages.
	 *

	 * The absence of the Destination-Host AVP will cause a message to be sent
	 * to any Diameter server supporting the application within the realm
	 * specified in Destination-Realm AVP.
	 *

	 * This AVP SHOULD be placed as close to the Diameter header as possible.
	 */
	public static final Type<String> DESTINATION_HOST = newUTF8StringType(
			"Destination-Host", DESTINATION_HOST_ORDINAL);

	/**
	 * The Session-Id AVP (AVP Code 263) is of type UTF8String and is used to
	 * identify a specific session (see Section 8). All messages pertaining to a
	 * specific session MUST include only one Session-Id AVP and the same value
	 * MUST be used throughout the life of a session. When present, the
	 * Session-Id SHOULD appear immediately following the Diameter Header (see
	 * Section 3).
	 *

	 * The Session-Id MUST be globally and eternally unique, as it is meant to
	 * uniquely identify a user session without reference to any other
	 * information, and may be needed to correlate historical authentication
	 * information with accounting information. The Session-Id includes a
	 * mandatory portion and an implementation-defined portion; a recommended
	 * format for the implementation-defined portion is outlined below.
	 *

	 * The Session-Id MUST begin with the sender's identity encoded in the
	 * DiameterIdentity type (see Section 4.4). The remainder of the Session-Id
	 * is delimited by a ";" character, and MAY be any sequence that the client
	 * can guarantee to be eternally unique; however, the following format is
	 * recommended, (square brackets [] indicate an optional element):
	 *

	 *
	 *

	 * {@code <DiameterIdentity><high 32 bits>;<low 32 bits>[;<optional value>] }
	 *

	 *

	 * <high 32 bits> and <low 32 bits> are decimal representations of the high
	 * and low 32 bits of a monotonically increasing 64-bit value. The 64-bit
	 * value is rendered in two part to simplify formatting by 32-bit
	 * processors. At startup, the high 32 bits of the 64-bit value MAY be
	 * initialized to the time, and the low 32 bits MAY be initialized to zero.
	 * This will for practical purposes eliminate the possibility of overlapping
	 * Session-Ids after a reboot, assuming the reboot process takes longer than
	 * a second. Alternatively, an implementation MAY keep track of the
	 * increasing value in non-volatile memory.
	 *

	 * <optional value> is implementation specific but may include a modem's
	 * device Id, a layer 2 address, timestamp, etc.
	 *

	 * Example, in which there is no optional value:
	 * accesspoint7.acme.com;1876543210;523
	 *

	 * Example, in which there is an optional value:
	 * accesspoint7.acme.com;1876543210;523;mobile@200.1.1.88
	 *

	 * The Session-Id is created by the Diameter application initiating the
	 * session, which in most cases is done by the client. Note that a
	 * Session-Id MAY be used for both the authorization and accounting commands
	 * of a given application.
	 */
	public static final Type<String> SESSION_ID = newUTF8StringType("Session-Id", SESSION_ID_ORDINAL);

	/**
	 * The User-Name AVP (AVP Code 1) [RADIUS] is of type UTF8String, which
	 * contains the User-Name, in a format consistent with the NAI specification
	 * [NAI].
	 */
	public static final Type<String> USER_NAME = newUTF8StringType("User-Name", USER_NAME_ORDINAL);

	/**
	 * The Vendor-Specific-Application-Id AVP (AVP Code 260) is of type Grouped
	 * and is used to advertise support of a vendor-specific Diameter
	 * Application. Exactly one of the Auth-Application-Id and
	 * Acct-Application-Id AVPs MAY be present.
	 *
	 * This AVP MUST also be present as the first AVP in all experimental
	 * commands defined in the vendor-specific application.
	 *
	 * This AVP SHOULD be placed as close to the Diameter header as possible.
	 *
	 *

	 * {@code
	 * <Vendor-Specific-Application-Id> ::= < AVP Header: 260 >
	 * 		1* [ Vendor-Id ]
	 * 		0*1{ Auth-Application-Id }
	 * 		0*1{ Acct-Application-Id }
	 * }
	 *

	 */
	public static final Type<AVPList> VENDOR_SPECIFIC_APPLICATION_ID = newGroupedType(
			"Vendor-Specific-Application-Id", VENDOR_SPECIFIC_APPLICATION_ID_ORDINAL);

	/**
	 * The Vendor-Id AVP (AVP Code 266) is of type Unsigned32 and contains the
	 * IANA "SMI Network Management Private Enterprise Codes" [ASSIGNNO] value
	 * assigned to the vendor of the Diameter application. In combination with
	 * the Supported-Vendor-Id AVP (Section 5.3.6), this MAY be used in order to
	 * know which vendor specific attributes may be sent to the peer. It is also
	 * envisioned that the combination of the Vendor-Id, Product-Name (Section
	 * 5.3.7) and the Firmware-Revision (Section 5.3.4) AVPs MAY provide very
	 * useful debugging information.
	 *
	 * A Vendor-Id value of zero in the CER or CEA messages is reserved and
	 * indicates that this field is ignored.
	 */
	public static final Type<Integer> VENDOR_ID = newUnsigned32Type("Vendor-Id", VENDOR_ID_ORDINAL);

	/**
	 * The Product-Name AVP (AVP Code 269) is of type UTF8String, and contains
	 * the vendor assigned name for the product. The Product-Name AVP SHOULD
	 * remain constant across firmware revisions for the same product.
	 */
	public static final Type<String> PRODUCT_NAME = newUTF8StringType("Product-Name", PRODUCT_NAME_ORDINAL);

	/**
	 * The Host-IP-Address AVP (AVP Code 257) is of type Address and is used to
	 * inform a Diameter peer of the sender's IP address. All source addresses
	 * that a Diameter node expects to use with SCTP [SCTP] MUST be advertised
	 * in the CER and CEA messages by including a Host-IP- Address AVP for each
	 * address. This AVP MUST ONLY be used in the CER and CEA messages.
	 */
	public static final Type<InetAddress> HOST_IP_ADDRESS = newAddressType("Host-IP-Address", HOST_IP_ADDRESS_ORDINAL);

	public static enum DisconnectCause
	{
		/** 0 A scheduled reboot is imminent. */
		REBOOTING,

		/**
		 * 1 The peer's internal resources are constrained, and it has
	     * determined that the transport connection needs to be closed.
	     */
		BUSY,

		/**
		 * 2 The peer has determined that it does not see a need for the
	     * transport connection to exist, since it does not expect any
	     * messages to be exchanged in the near future.
		 */
		DO_NOT_WANT_TO_TALK_TO_YOU
	}

	/**
	 * The Disconnect-Cause AVP (AVP Code 273) is of type Enumerated.  A
   	 * Diameter node MUST include this AVP in the Disconnect-Peer-Request
   	 * message to inform the peer of the reason for its intention to
   	 * shutdown the transport connection.  The following values are
   	 * supported:
   	 *
   	 * @see DisconnectCause
	 */
	public static final Type<DisconnectCause> DISCONNECT_CAUSE = newEnumType("Disconnect-Clause",
			DISCONNECT_CAUSE_ORDINAL, DisconnectCause.class);

	/**
	 * The Result-Code AVP (AVP Code 268) is of type Unsigned32 and
     * indicates whether a particular request was completed successfully or
     * whether an error occurred.  All Diameter answer messages defined in
     * IETF applications MUST include one Result-Code AVP.  A non-successful
     * Result-Code AVP (one containing a non 2xxx value other than
     * DIAMETER_REDIRECT_INDICATION) MUST include the Error-Reporting-Host
     * AVP if the host setting the Result-Code AVP is different from the
     * identity encoded in the Origin-Host AVP.
	 */
	public static final Type<Integer> RESULT_CODE = newUnsigned32Type("Result-Code", RESULT_CODE_ORDINAL);

	/**
	 * The Experimental-Result AVP (AVP Code 297) is of type Grouped, and
	 * indicates whether a particular vendor-specific request was completed
	 * successfully or whether an error occurred.  Its Data field has the
	 * following ABNF grammar:
	 *
	 * AVP Format
     *

	 *    Experimental-Result ::= < AVP Header: 297 >
	 *                               { Vendor-Id }
	 *                               { Experimental-Result-Code }
	 *

     *
	 * The Vendor-Id AVP (see Section 5.3.3) in this grouped AVP identifies
	 * the vendor responsible for the assignment of the result code which
	 * follows.  All Diameter answer messages defined in vendor-specific
	 * applications MUST include either one Result-Code AVP or one
	 * Experimental-Result AVP.
	 */
	public static final Type<AVPList> EXPERIMENTAL_RESULT = newGroupedType(
			"Experimental-Result", EXPERIMENTAL_RESULT_ORDINAL);

	/**
	 * The Experimental-Result-Code AVP (AVP Code 298) is of type Unsigned32
     * and contains a vendor-assigned value representing the result of
     * processing the request.
     *

     * It is recommended that vendor-specific result codes follow the same
     * conventions given for the Result-Code AVP regarding the different
     * types of result codes and the handling of errors (for non 2xxx
     * values).
	 */
	public static final Type<Integer> EXPERIMENTAL_RESULT_CODE = newUnsigned32Type(
			"Experimental-Result-Code", EXPERIMENTAL_RESULT_CODE_ORDINAL);

	/**
	 * The Origin-State-Id AVP (AVP Code 278), of type Unsigned32, is a
     * monotonically increasing value that is advanced whenever a Diameter
     * entity restarts with loss of previous state, for example upon reboot.
     * Origin-State-Id MAY be included in any Diameter message, including
     * CER.
     *
     * A Diameter entity issuing this AVP MUST create a higher value for
     * this AVP each time its state is reset.  A Diameter entity MAY set
     * Origin-State-Id to the time of startup, or it MAY use an incrementing
     * counter retained in non-volatile memory across restarts.
     *
     * The Origin-State-Id, if present, MUST reflect the state of the entity
     * indicated by Origin-Host.  If a proxy modifies Origin-Host, it MUST
     * either remove Origin-State-Id or modify it appropriately as well.
     *
     * Typically, Origin-State-Id is used by an access device that always
     * starts up with no active sessions; that is, any session active prior
     * to restart will have been lost.  By including Origin-State-Id in a
     * message, it allows other Diameter entities to infer that sessions
     * associated with a lower Origin-State-Id are no longer active.  If an
     * access device does not intend for such inferences to be made, it MUST
     * either not include Origin-State-Id in any message, or set its value
     * to 0.
	 */
	public static Type<Integer> ORIGIN_STATE_ID = newUnsigned32Type("Origin-State-Id", ORIGIN_STATE_ID_ORDINAL);

	/**
	 * The Firmware-Revision AVP (AVP Code 267) is of type Unsigned32 and is
     * used to inform a Diameter peer of the firmware revision of the
     * issuing device.
     * For devices that do not have a firmware revision (general purpose
     * computers running Diameter software modules, for instance), the
     * revision of the Diameter software module may be reported instead.
	 */
	public static final Type<Integer> FIRMWARE_REVISION = newUnsigned32Type("Firmware-Revision", FIRMWARE_REVISION_ORDINAL);

	/**
	 * The Failed-AVP AVP (AVP Code 279) is of type Grouped and provides
     * debugging information in cases where a request is rejected or not
     * fully processed due to erroneous information in a specific AVP.  The
     * value of the Result-Code AVP will provide information on the reason
     * for the Failed-AVP AVP.
     *
     * The possible reasons for this AVP are the presence of an improperly
     * constructed AVP, an unsupported or unrecognized AVP, an invalid AVP
     * value, the omission of a required AVP, the presence of an explicitly
     * excluded AVP (see tables in Section 10), or the presence of two or
     * more occurrences of an AVP which is restricted to 0, 1, or 0-1
     * occurrences.
   	 *
     * A Diameter message MAY contain one Failed-AVP AVP, containing the
     * entire AVP that could not be processed successfully.  If the failure
     * reason is omission of a required AVP, an AVP with the missing AVP
     * code, the missing vendor id, and a zero filled payload of the minimum
     * required length for the omitted AVP will be added.
     *
     * <Failed-AVP> ::= < AVP Header: 279 >
     *               1* {AVP}
	 */
	public static final Type<AVPList> FAILED_AVP = newGroupedType("Failed-AVP", FAILED_AVP_ORDINAL);

	// Radius for digest authentication (RFC 4590)
	public static final int
		DIGEST_REALM_ORDINAL = 104,
		DIGEST_QOP_ORDINAL = 110,
		DIGEST_ALGORITHM_ORDINAL = 111,
		DIGEST_HA1_ORDINAL = 121;

	/**
	 * Description: This attribute describes a protection space component of the
	 * RADIUS server. HTTP-style protocols differ in their definition of the
	 * protection space. See [RFC2617], Section 1.2, for details. It MUST only
	 * be used in Access-Request and Access-Challenge packets.
	 *
	 * Type: 104 for Digest-Realm
	 *
	 * Length: >=3
	 *
	 * Text: In Access-Requests, the RADIUS client takes the value of the realm
	 * directive (realm-value according to [RFC2617]) without surrounding quotes
	 * from the HTTP-style request it wants to authenticate. In Access-Challenge
	 * packets, the RADIUS server puts the expected realm value into this
	 * attribute.
	 */
	public static final Type<String> DIGEST_REALM = newUTF8StringType("Digest-Realm", DIGEST_REALM_ORDINAL);

	/**
	 * Description: This attribute holds the Quality of Protection parameter that
	 * influences the HTTP Digest calculation. This attribute MUST only be used
	 * in Access-Request and Access-Challenge packets. A RADIUS client SHOULD
	 * insert one of the Digest-Qop attributes it has received in a previous
	 * Access-Challenge packet. RADIUS servers SHOULD insert at least one
	 * Digest-Qop attribute in an Access-Challenge packet. Digest-Qop is
	 * optional in order to preserve backward compatibility with a minimal
	 * implementation of [RFC2069].
	 *
	 * Text: In Access-Requests, the RADIUS client takes the value of the qop
	 * directive (qop-value as described in [RFC2617]) from the HTTP-style
	 * request it wants to authenticate. In Access-Challenge packets, the RADIUS
	 * server puts a desired qop-value into this attribute. If the RADIUS server
	 * supports more than one "quality of protection" value, it puts each
	 * qop-value into a separate Digest-Qop attribute.
	 */
	public static final Type<String> DIGEST_QOP = newUTF8StringType("Digest-Qop", DIGEST_QOP_ORDINAL);

	/**
	 * Description This attribute holds the algorithm parameter that influences
	 * the HTTP Digest calculation. It MUST only be used in Access-Request and
	 * Access-Challenge packets. If this attribute is missing, MD5 is assumed.
	 *
	 * Text In Access-Requests, the RADIUS client takes the value of the
	 * algorithm directive (as described in [RFC2617], section 3.2.1) from the
	 * HTTP-style request it wants to authenticate. In Access-Challenge packets,
	 * the RADIUS server SHOULD put the desired algorithm into this attribute.
	 */
	public static final Type<String> DIGEST_ALGORITHM = newUTF8StringType("Digest-Algorithm", DIGEST_ALGORITHM_ORDINAL);

	/**
	 * Description This attribute is used to allow the generation of an
	 * Authentication-Info header, even if the HTTP-style response's body is
	 * required for the calculation of the rspauth value. It SHOULD be used in
	 * Access-Accept packets if the required quality of protection ('qop') is
	 * 'auth-int'.
	 *
	 * This attribute MUST NOT be sent if the qop parameter was not specified or
	 * has a value of 'auth' (in this case, use Digest-Response-Auth instead).
	 *
	 * The Digest-HA1 attribute MUST only be sent by the RADIUS server or
	 * processed by the RADIUS client if at least one of the following
	 * conditions is true:
	 *
	 * + The Digest-Algorithm attribute's value is 'MD5-sess' or
	 * 'AKAv1-MD5-sess'.
	 *
	 * + IPsec is configured to protect traffic between RADIUS client and RADIUS
	 * server with IPsec (see Section 8).
	 *
	 * This attribute MUST only be used in Access-Accept packets.
	 *
	 * Text This attribute contains the hexadecimal representation of H(A1) as
	 * described in [RFC2617], sections 3.1.3, 3.2.1, and 3.2.2.2.
	 */
	public static final Type<String> DIGEST_HA1 = newUTF8StringType("Digest-HA1", DIGEST_HA1_ORDINAL);

	// ======================== Commands ========================

	public static final int
		CER_ORDINAL = 257,
		CEA_ORDINAL = 257,
		DWR_ORDINAL = 280,
		DWA_ORDINAL = 280,
		DPR_ORDINAL = 282,
		DPA_ORDINAL = 282;

	/**
	 * The Capabilities-Exchange-Request (CER), indicated by the Command-
     * Code set to 257 and the Command Flags' 'R' bit set, is sent to
     * exchange local capabilities.  Upon detection of a transport failure,
     * this message MUST NOT be sent to an alternate peer.
     *
     * When Diameter is run over SCTP [SCTP], which allows for connections
     * to span multiple interfaces and multiple IP addresses, the
     * Capabilities-Exchange-Request message MUST contain one Host-IP-
     * Address AVP for each potential IP address that MAY be locally used
     * when transmitting Diameter messages.
     *

	 * {@code
	 *  <CER> ::= < Diameter Header: 257, REQ >
     *           { Origin-Host }
     *           { Origin-Realm }
     *        1* { Host-IP-Address }
     *           { Vendor-Id }
     *           { Product-Name }
     *           [ Origin-State-Id ]
     *         * [ Supported-Vendor-Id ]
     *         * [ Auth-Application-Id ]
     *         * [ Inband-Security-Id ]
     *         * [ Acct-Application-Id ]
     *         * [ Vendor-Specific-Application-Id ]
     *           [ Firmware-Revision ]
     *         * [ AVP ]
     *  }
     *

	 */
	public static final DiameterCommand CER = newCommand(true, CER_ORDINAL, "Capabilities-Exchange-Request", false);

	/**
	 *  The Capabilities-Exchange-Answer (CEA), indicated by the Command-Code
     * set to 257 and the Command Flags' 'R' bit cleared, is sent in
     * response to a CER message.
     *
     * When Diameter is run over SCTP [SCTP], which allows connections to
     * span multiple interfaces, hence, multiple IP addresses, the
     * Capabilities-Exchange-Answer message MUST contain one Host-IP-Address
     * AVP for each potential IP address that MAY be locally used when
     * transmitting Diameter messages.
     *
     * Message Format
     *

     * {@code
     *  <CEA> ::= < Diameter Header: 257 >
     *          { Result-Code }
     *          { Origin-Host }
     *          { Origin-Realm }
     *       1* { Host-IP-Address }
     *          { Vendor-Id }
     *          { Product-Name }
     *          [ Origin-State-Id ]
     *          [ Error-Message ]
     *        * [ Failed-AVP ]
     *        * [ Supported-Vendor-Id ]
     *        * [ Auth-Application-Id ]
     *        * [ Inband-Security-Id ]
     *        * [ Acct-Application-Id ]
     *        * [ Vendor-Specific-Application-Id ]
     *          [ Firmware-Revision ]
     *        * [ AVP ]
     *  }
     *

	 */
	public static final DiameterCommand CEA = newAnswer(CEA_ORDINAL, "Capabilities-Exchange-Answer");

	/**
	 *
 {@code
	 * 	<DWR>  ::= < Diameter Header: 280, REQ >
     * 		{ Origin-Host }
     * 		{ Origin-Realm }
     * 		[ Origin-State-Id ]
     * }

     *
     * @see Common#ORIGIN_HOST
     * @see Common#ORIGIN_REALM
     * @see Common#ORIGIN_STATE_ID
     */
	public static final DiameterCommand DWR = newRequest(DWR_ORDINAL, "Device-Watchdog-Request");

	/**
	 *
 {@code
	 * <DWA>  ::= < Diameter Header: 280 >
     *           { Result-Code }
     *           { Origin-Host }
     *           { Origin-Realm }
     *           [ Error-Message ]
     *         * [ Failed-AVP ]
     *           [ Original-State-Id ]
     * }

	 */
	public static final DiameterCommand DWA = newAnswer(DWA_ORDINAL, "Device-Watchdog-Answer");

	/**
	 * The Disconnect-Peer-Request (DPR), indicated by the Command-Code set
   	 * to 282 and the Command Flags' 'R' bit set, is sent to a peer to
   	 * inform its intentions to shutdown the transport connection.  Upon
   	 * detection of a transport failure, this message MUST NOT be sent to an
   	 * alternate peer.
	 *
   	 *
 {@code
     * <DPR> ::= < Diameter Header: 282, REQ >
     *            { Origin-Host }
     *            { Origin-Realm }
     *            { Disconnect-Cause }
	 * }

	 */
	public static final DiameterCommand DPR = newRequest(DPR_ORDINAL, "Disconnect-Peer-Request");

	/**
	 * Upon receipt of this message, the transport connection is shutdown.
	 *
	 *
 {@code
     * <DPA>  ::= < Diameter Header: 282 >
     *            { Result-Code }
     *            { Origin-Host }
     *            { Origin-Realm }
     *            [ Error-Message ]
     *          * [ Failed-AVP ]
     * }

	 */
	public static final DiameterCommand DPA = newAnswer(DPA_ORDINAL, "Disconnect-Peer-Answer");

	/**
	 * The Supported-Vendor-Id AVP (AVP Code 265) is of type Unsigned32 and
     * contains the IANA "SMI Network Management Private Enterprise Codes"
     * [ASSIGNNO] value assigned to a vendor other than the device vendor.
     * This is used in the CER and CEA messages in order to inform the peer
     * that the sender supports (a subset of) the vendor-specific AVPs
     * defined by the vendor identified in this AVP.
	 */
	public static final Type<Integer> SUPPORTED_VENDOR_ID = newUnsigned32Type("Supported-Vendor-Id", SUPPORTED_VENDOR_ID_ORDINAL);

	/**
	 * One or more of instances of this AVP MUST be present if the answer
     * message's 'E' bit is set and the Result-Code AVP is set to
     * DIAMETER_REDIRECT_INDICATION.
     *
     * Upon receiving the above, the receiving Diameter node SHOULD forward
     * the request directly to one of the hosts identified in these AVPs.
     * The server contained in the selected Redirect-Host AVP SHOULD be used
     * for all messages pertaining to this session.
	 */
	public static final Type<String> REDIRECT_HOST = newUTF8StringType("Redirect-Host", REDIRECT_HOST_ORDINAL);

	// ======================== Result codes ========================

	public static final int
		DIAMETER_SUCCESS_ORDINAL = 2001,
		DIAMETER_LIMITED_SUCCESS_ORDINAL = 2002,

		DIAMETER_COMMAND_UNSUPPORTED_ORDINAL = 3001,
		DIAMETER_UNABLE_TO_DELIVER_ORDINAL = 3002,
		DIAMETER_REALM_NOT_SERVED_ORDINAL = 3003,
		DIAMETER_TOO_BUSY_ORDINAL = 3004,
		DIAMETER_LOOP_DETECTED_ORDINAL = 3005,
		DIAMETER_REDIRECT_INDICATION_ORDINAL = 3006,
		DIAMETER_APPLICATION_UNSUPPORTED_ORDINAL = 3007,
		DIAMETER_INVALID_HDR_BITS_ORDINAL = 3008,
		DIAMETER_INVALID_AVP_BITS_ORDINAL = 3009,
		DIAMETER_UNKNOWN_PEER_ORDINAL = 3010,

		DIAMETER_AUTHENTICATION_REJECTED_ORDINAL = 4001,
		DIAMETER_OUT_OF_SPACE_ORDINAL = 4002,
		ELECTION_LOST_ORDINAL = 4003,

		DIAMETER_AVP_UNSUPPORTED_ORDINAL = 5001,
		DIAMETER_UNKNOWN_SESSION_ID_ORDINAL = 5002,
		DIAMETER_AUTHORIZATION_REJECTED_ORDINAL = 5003,
		DIAMETER_INVALID_AVP_VALUE_ORDINAL = 5004,
		DIAMETER_MISSING_AVP_ORDINAL = 5005,
		DIAMETER_RESOURCES_EXCEEDED_ORDINAL = 5006,
		DIAMETER_CONTRADICTING_AVPS_ORDINAL = 5007,
		DIAMETER_AVP_NOT_ALLOWED_ORDINAL = 5008,
		DIAMETER_AVP_OCCURS_TOO_MANY_TIMES_ORDINAL = 5009,
		DIAMETER_NO_COMMON_APPLICATION_ORDINAL = 5010,
		DIAMETER_UNSUPPORTED_VERSION_ORDINAL = 5011,
		DIAMETER_UNABLE_TO_COMPLY_ORDINAL = 5012,
		DIAMETER_INVALID_BIT_IN_HEADER_ORDINAL = 5013,
		DIAMETER_INVALID_AVP_LENGTH_ORDINAL = 5014,
		DIAMETER_INVALID_MESSAGE_LENGTH_ORDINAL = 5015,
		DIAMETER_INVALID_AVP_BIT_COMBO_ORDINAL = 5016,
		DIAMETER_NO_COMMON_SECURITY_ORDINAL = 5017;

	/**
	 * The Request was successfully completed
	 */
	public static final ResultCode DIAMETER_SUCCESS = newResultCode(
			DIAMETER_SUCCESS_ORDINAL, "DIAMETER_SUCCESS");

	/**
	 * When returned, the request was successfully completed, but
     * additional processing is required by the application in order to
     * provide service to the user.
	 */
	public static final ResultCode DIAMETER_LIMITED_SUCCESS = newResultCode(
			DIAMETER_LIMITED_SUCCESS_ORDINAL, "DIAMETER_LIMITED_SUCCESS");

	// Protocol Errors
	/**
	 * The Request contained a Command-Code that the receiver did not
     * recognize or support.  This MUST be used when a Diameter node
     * receives an experimental command that it does not understand.
	 */
	public static final ResultCode DIAMETER_COMMAND_UNSUPPORTED = newResultCode(
			DIAMETER_COMMAND_UNSUPPORTED_ORDINAL, "DIAMETER_COMMAND_UNSUPPORTED");

	/**
	 * This error is given when Diameter can not deliver the message to the
	 * destination, either because no host within the realm supporting the
	 * required application was available to process the request, or because
	 * Destination-Host AVP was given without the associated Destination-Realm
	 * AVP.
	 */
	public static final ResultCode DIAMETER_UNABLE_TO_DELIVER = newResultCode(
			DIAMETER_UNABLE_TO_DELIVER_ORDINAL, "DIAMETER_UNABLE_TO_DELIVER");

	/**
	 * The intended realm of the request is not recognized.
	 */
	public static final ResultCode DIAMETER_REALM_NOT_SERVED = newResultCode(
			DIAMETER_REALM_NOT_SERVED_ORDINAL, "DIAMETER_REALM_NOT_SERVED");

	/**
	 * When returned, a Diameter node SHOULD attempt to send the message to an
	 * alternate peer. This error MUST only be used when a specific server is
	 * requested, and it cannot provide the requested service.
	 */
	public static final ResultCode DIAMETER_TOO_BUSY = newResultCode(
			DIAMETER_TOO_BUSY_ORDINAL, "DIAMETER_TOO_BUSY");

	/**
	 * An agent detected a loop while trying to get the message to the intended
	 * recipient. The message MAY be sent to an alternate peer, if one is
	 * available, but the peer reporting the error has identified a
	 * configuration problem.
	 */
	public static final ResultCode DIAMETER_LOOP_DETECTED = newResultCode(
			DIAMETER_LOOP_DETECTED_ORDINAL, "DIAMETER_LOOP_DETECTED");

	/**
	 * A redirect agent has determined that the request could not be satisfied
	 * locally and the initiator of the request should direct the request
	 * directly to the server, whose contact information has been added to the
	 * response. When set, the Redirect-Host AVP MUST be present.
	 */
	public static final ResultCode DIAMETER_REDIRECT_INDICATION = newResultCode(
			DIAMETER_REDIRECT_INDICATION_ORDINAL, "DIAMETER_REDIRECT_INDICATION");

	/**
	 * A request was sent for an application that is not supported.
	 */
	public static final ResultCode DIAMETER_APPLICATION_UNSUPPORTED = newResultCode(
			DIAMETER_APPLICATION_UNSUPPORTED_ORDINAL, "DIAMETER_APPLICATION_UNSUPPORTED");

	/**
	 * A request was received whose bits in the Diameter header were either set
	 * to an invalid combination, or to a value that is inconsistent with the
	 * command code's definition.
	 */
	public static final ResultCode DIAMETER_INVALID_HDR_BITS = newResultCode(
			DIAMETER_INVALID_HDR_BITS_ORDINAL, "DIAMETER_INVALID_HDR_BITS");

	/**
	 * A request was received that included an AVP whose flag bits are set to an
	 * unrecognized value, or that is inconsistent with the AVP's definition.
	 */
	public static final ResultCode DIAMETER_INVALID_AVP_BITS = newResultCode(
			DIAMETER_INVALID_AVP_BITS_ORDINAL, "DIAMETER_INVALID_AVP_BITS");

	/**
	 * A CER was received from an unknown peer.
	 */
	public static final ResultCode DIAMETER_UNKNOWN_PEER = newResultCode(
			DIAMETER_UNKNOWN_PEER_ORDINAL, "DIAMETER_UNKNOWN_PEER");

	//  Transient Failures

	/**
	 * The authentication process for the user failed, most likely due to an
	 * invalid password used by the user. Further attempts MUST only be tried
	 * after prompting the user for a new password.
	 */
	public static final ResultCode DIAMETER_AUTHENTICATION_REJECTED = newResultCode(
			DIAMETER_AUTHENTICATION_REJECTED_ORDINAL, "DIAMETER_AUTHENTICATION_REJECTED");

	/**
	 * A Diameter node received the accounting request but was unable to commit
	 * it to stable storage due to a temporary lack of space.
	 */
	public static final ResultCode DIAMETER_OUT_OF_SPACE = newResultCode(
			DIAMETER_OUT_OF_SPACE_ORDINAL, "DIAMETER_OUT_OF_SPACE");

	/**
	 * The peer has determined that it has lost the election process and has
	 * therefore disconnected the transport connection.
	 */
	public static final ResultCode ELECTION_LOST = newResultCode(
			ELECTION_LOST_ORDINAL, "ELECTION_LOST");

	// Permanent Failures

	/**
     * The peer received a message that contained an AVP that is not
     * recognized or supported and was marked with the Mandatory bit.  A
     * Diameter message with this error MUST contain one or more Failed-
     * AVP AVP containing the AVPs that caused the failure.
	 */
	public static final ResultCode DIAMETER_AVP_UNSUPPORTED = newResultCode(
			DIAMETER_AVP_UNSUPPORTED_ORDINAL, "DIAMETER_AVP_UNSUPPORTED");

	/**
	 * The request contained an unknown Session-Id.
	 */
	public static final ResultCode DIAMETER_UNKNOWN_SESSION_ID = newResultCode(
			DIAMETER_UNKNOWN_SESSION_ID_ORDINAL, "DIAMETER_UNKNOWN_SESSION_ID");

	/**
     * The request contained an AVP with an invalid value in its data
     * portion.  A Diameter message indicating this error MUST include
     * the offending AVPs within a Failed-AVP AVP.
	 */
	public static final ResultCode DIAMETER_INVALID_AVP_VALUE = newResultCode(
			DIAMETER_INVALID_AVP_VALUE_ORDINAL, "DIAMETER_INVALID_AVP_VALUE");

	/**
	 * A request was received for which the user could not be authorized.
     * This error could occur if the service requested is not permitted
     * to the user.
	 */
	public static final ResultCode DIAMETER_AUTHORIZATION_REJECTED = newResultCode(
			DIAMETER_AUTHORIZATION_REJECTED_ORDINAL, "DIAMETER_AUTHORIZATION_REJECTED");

	/**
	 * The request did not contain an AVP that is required by the Command Code
	 * definition. If this value is sent in the Result-Code AVP, a Failed-AVP
	 * AVP SHOULD be included in the message. The Failed-AVP AVP MUST contain an
	 * example of the missing AVP complete with the Vendor-Id if applicable. The
	 * value field of the missing AVP should be of correct minimum length and
	 * contain zeroes.
	 */
	public static final ResultCode DIAMETER_MISSING_AVP = newResultCode(
			DIAMETER_MISSING_AVP_ORDINAL, "DIAMETER_MISSING_AVP");

	/**
	 * A request was received that cannot be authorized because the user has
	 * already expended allowed resources. An example of this error condition is
	 * a user that is restricted to one dial-up PPP port, attempts to establish
	 * a second PPP connection.
	 */
	public static final ResultCode DIAMETER_RESOURCES_EXCEEDED = newResultCode(
			DIAMETER_RESOURCES_EXCEEDED_ORDINAL, "DIAMETER_RESOURCES_EXCEEDED");

	/**
	 * The Home Diameter server has detected AVPs in the request that
	 * contradicted each other, and is not willing to provide service to the
	 * user. One or more Failed-AVP AVPs MUST be present, containing the AVPs
	 * that contradicted each other.
	 */
	public static final ResultCode DIAMETER_CONTRADICTING_AVPS = newResultCode(
			DIAMETER_CONTRADICTING_AVPS_ORDINAL, "DIAMETER_CONTRADICTING_AVPS");

	/**
	 * A message was received with an AVP that MUST NOT be present. The
	 * Failed-AVP AVP MUST be included and contain a copy of the offending AVP.
	 */
	public static final ResultCode DIAMETER_AVP_NOT_ALLOWED = newResultCode(
			DIAMETER_AVP_NOT_ALLOWED_ORDINAL, "DIAMETER_AVP_NOT_ALLOWED");

	/**
	 * A message was received that included an AVP that appeared more often than
	 * permitted in the message definition. The Failed-AVP AVP MUST be included
	 * and contain a copy of the first instance of the offending AVP that
	 * exceeded the maximum number of occurrences
	 */
	public static final ResultCode DIAMETER_AVP_OCCURS_TOO_MANY_TIMES = newResultCode(
			DIAMETER_AVP_OCCURS_TOO_MANY_TIMES_ORDINAL, "DIAMETER_AVP_OCCURS_TOO_MANY_TIMES");

	/**
	 * This error is returned when a CER message is received, and there are no
	 * common applications supported between the peers.
	 */
	public static final ResultCode DIAMETER_NO_COMMON_APPLICATION = newResultCode(
			DIAMETER_NO_COMMON_APPLICATION_ORDINAL, "DIAMETER_NO_COMMON_APPLICATION");

	/**
	 * This error is returned when a request was received, whose version number
	 * is unsupported.
	 */
	public static final ResultCode DIAMETER_UNSUPPORTED_VERSION = newResultCode(
			DIAMETER_UNSUPPORTED_VERSION_ORDINAL, "DIAMETER_UNSUPPORTED_VERSION");

	/**
	 * This error is returned when a request is rejected for unspecified
	 * reasons.
	 */
	public static final ResultCode DIAMETER_UNABLE_TO_COMPLY = newResultCode(
			DIAMETER_UNABLE_TO_COMPLY_ORDINAL, "DIAMETER_UNABLE_TO_COMPLY");

	/**
	 * This error is returned when an unrecognized bit in the Diameter header is
	 * set to one (1).
	 */
	public static final ResultCode DIAMETER_INVALID_BIT_IN_HEADER = newResultCode(
			DIAMETER_INVALID_BIT_IN_HEADER_ORDINAL, "DIAMETER_INVALID_BIT_IN_HEADER");

	/**
	 * The request contained an AVP with an invalid length. A Diameter message
	 * indicating this error MUST include the offending AVPs within a Failed-AVP
	 * AVP.
	 */
	public static final ResultCode DIAMETER_INVALID_AVP_LENGTH = newResultCode(
			DIAMETER_INVALID_AVP_LENGTH_ORDINAL, "DIAMETER_INVALID_AVP_LENGTH");

	/**
	 * This error is returned when a request is received with an invalid message
	 * length.
	 */
	public static final ResultCode DIAMETER_INVALID_MESSAGE_LENGTH = newResultCode(
			DIAMETER_INVALID_MESSAGE_LENGTH_ORDINAL, "DIAMETER_INVALID_MESSAGE_LENGTH");

	/**
	 * The request contained an AVP with which is not allowed to have the given
	 * value in the AVP Flags field. A Diameter message indicating this error
	 * MUST include the offending AVPs within a Failed-AVP AVP.
	 */
	public static final ResultCode DIAMETER_INVALID_AVP_BIT_COMBO = newResultCode(
			DIAMETER_INVALID_AVP_BIT_COMBO_ORDINAL, "DIAMETER_INVALID_AVP_BIT_COMBO");

	/**
	 * This error is returned when a CER message is received, and there are no
	 * common security mechanisms supported between the peers. A
	 * Capabilities-Exchange-Answer (CEA) MUST be returned with the Result-Code
	 * AVP set to DIAMETER_NO_COMMON_SECURITY.
	 */
	public static final ResultCode DIAMETER_NO_COMMON_SECURITY = newResultCode(
			DIAMETER_NO_COMMON_SECURITY_ORDINAL, "DIAMETER_NO_COMMON_SECURITY");
}


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

namespace NGnono.FMNote.Datas.Models
{
    public partial class ResourceStageEntity : NGnono.Framework.Models.BaseEntity
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ExtName { get; set; }
        public Nullable<int> Width { get; set; }
        public Nullable<int> Height { get; set; }
        public Nullable<int> ContentSize { get; set; }
        public string Size { get; set; }
        public Nullable<int> SortOrder { get; set; }
        public Nullable<int> InUser { get; set; }
        public string ItemCode { get; set; }
        public Nullable<System.DateTime> InDate { get; set; }
        public int Status { get; set; }
        public Nullable<int> UploadGroupId { get; set; }

        #region Overrides of BaseEntity

        /// <summary>
        /// KeyMemberId
        /// </summary>
        public override object EntityId
        {
                get { return new Dictionary<string, object> (2){
                {"Id",Id}, {"Status",Status}
                };}

        }

        #endregion

    }
}

redpajama_set_name: RedPajamaGithub


text:
 <footer>
 footer
 </footer>

 </div>

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.0.min.js"><\/script>')</script>
        <script src="js/build/script.min.js"></script>
        <!-- Google Analytics -->
        <script>
          (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
          (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
          })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

          ga('create', 'UA-48897223-1', 'integralcode.co.uk');
          ga('send', 'pageview');

        </script>
    </body>
</html>


text:
<?php

class Google_Service_Spanner_Session extends Google_Model
{
  public $approximateLastUseTime;
  public $createTime;
  public $labels;
  public $name;

  public function setApproximateLastUseTime($approximateLastUseTime)
  {
    $this->approximateLastUseTime = $approximateLastUseTime;
  }
  public function getApproximateLastUseTime()
  {
    return $this->approximateLastUseTime;
  }
  public function setCreateTime($createTime)
  {
    $this->createTime = $createTime;
  }
  public function getCreateTime()
  {
    return $this->createTime;
  }
  public function setLabels($labels)
  {
    $this->labels = $labels;
  }
  public function getLabels()
  {
    return $this->labels;
  }
  public function setName($name)
  {
    $this->name = $name;
  }
  public function getName()
  {
    return $this->name;
  }
}


text:
namespace mojo {
namespace edk {
namespace {

// NOTE(vtl): There's currently not much to test for in
// |SharedBufferDispatcher::ValidateCreateOptions()|, but the tests should be
// expanded if/when options are added, so I've kept the general form of the
// tests from data_pipe_unittest.cc.

const uint32_t kSizeOfCreateOptions = sizeof(MojoCreateSharedBufferOptions);

// Does a cursory sanity check of |validated_options|. Calls
// |ValidateCreateOptions()| on already-validated options. The validated options
// should be valid, and the revalidated copy should be the same.
void RevalidateCreateOptions(
    const MojoCreateSharedBufferOptions& validated_options) {
  EXPECT_EQ(kSizeOfCreateOptions, validated_options.struct_size);
  // Nothing to check for flags.

  MojoCreateSharedBufferOptions revalidated_options = {};
  EXPECT_EQ(MOJO_RESULT_OK,
            SharedBufferDispatcher::ValidateCreateOptions(
                &validated_options, &revalidated_options));
  EXPECT_EQ(validated_options.struct_size, revalidated_options.struct_size);
  EXPECT_EQ(validated_options.flags, revalidated_options.flags);
}

class SharedBufferDispatcherTest : public testing::Test {
 public:
  SharedBufferDispatcherTest() {}
  ~SharedBufferDispatcherTest() override {}

 private:
  DISALLOW_COPY_AND_ASSIGN(SharedBufferDispatcherTest);
};

// Tests valid inputs to |ValidateCreateOptions()|.
TEST_F(SharedBufferDispatcherTest, ValidateCreateOptionsValid) {
  // Default options.
  {
    MojoCreateSharedBufferOptions validated_options = {};
    EXPECT_EQ(MOJO_RESULT_OK, SharedBufferDispatcher::ValidateCreateOptions(
                                  nullptr, &validated_options));
    RevalidateCreateOptions(validated_options);
  }

  // Different flags.
  MojoCreateSharedBufferOptionsFlags flags_values[] = {
      MOJO_CREATE_SHARED_BUFFER_OPTIONS_FLAG_NONE};
  for (size_t i = 0; i < arraysize(flags_values); i++) {
    const MojoCreateSharedBufferOptionsFlags flags = flags_values[i];

    // Different capacities (size 1).
    for (uint32_t capacity = 1; capacity <= 100 * 1000 * 1000; capacity *= 10) {
      MojoCreateSharedBufferOptions options = {
          kSizeOfCreateOptions,  // |struct_size|.
          flags                  // |flags|.
      };
      MojoCreateSharedBufferOptions validated_options = {};
      EXPECT_EQ(MOJO_RESULT_OK,
                SharedBufferDispatcher::ValidateCreateOptions(
                    &options, &validated_options))
          << capacity;
      RevalidateCreateOptions(validated_options);
      EXPECT_EQ(options.flags, validated_options.flags);
    }
  }
}

TEST_F(SharedBufferDispatcherTest, ValidateCreateOptionsInvalid) {
  // Invalid |struct_size|.
  {
    MojoCreateSharedBufferOptions options = {
        1,                                           // |struct_size|.
        MOJO_CREATE_SHARED_BUFFER_OPTIONS_FLAG_NONE  // |flags|.
    };
    MojoCreateSharedBufferOptions unused;
    EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
              SharedBufferDispatcher::ValidateCreateOptions(
                  &options, &unused));
  }

  // Unknown |flags|.
  {
    MojoCreateSharedBufferOptions options = {
        kSizeOfCreateOptions,  // |struct_size|.
        ~0u                    // |flags|.
    };
    MojoCreateSharedBufferOptions unused;
    EXPECT_EQ(MOJO_RESULT_UNIMPLEMENTED,
              SharedBufferDispatcher::ValidateCreateOptions(
                  &options, &unused));
  }
}

TEST_F(SharedBufferDispatcherTest, CreateAndMapBuffer) {
  scoped_refptr<SharedBufferDispatcher> dispatcher;
  EXPECT_EQ(MOJO_RESULT_OK, SharedBufferDispatcher::Create(
                                SharedBufferDispatcher::kDefaultCreateOptions,
                                nullptr, 100, &dispatcher));
  ASSERT_TRUE(dispatcher);
  EXPECT_EQ(Dispatcher::Type::SHARED_BUFFER, dispatcher->GetType());

  // Make a couple of mappings.
  scoped_ptr<PlatformSharedBufferMapping> mapping1;
  EXPECT_EQ(MOJO_RESULT_OK, dispatcher->MapBuffer(
                                0, 100, MOJO_MAP_BUFFER_FLAG_NONE, &mapping1));
  ASSERT_TRUE(mapping1);
  ASSERT_TRUE(mapping1->GetBase());
  EXPECT_EQ(100u, mapping1->GetLength());
  // Write something.
  static_cast<char*>(mapping1->GetBase())[50] = 'x';

  scoped_ptr<PlatformSharedBufferMapping> mapping2;
  EXPECT_EQ(MOJO_RESULT_OK, dispatcher->MapBuffer(
                                50, 50, MOJO_MAP_BUFFER_FLAG_NONE, &mapping2));
  ASSERT_TRUE(mapping2);
  ASSERT_TRUE(mapping2->GetBase());
  EXPECT_EQ(50u, mapping2->GetLength());
  EXPECT_EQ('x', static_cast<char*>(mapping2->GetBase())[0]);

  EXPECT_EQ(MOJO_RESULT_OK, dispatcher->Close());

  // Check that we can still read/write to mappings after the dispatcher has
  // gone away.
  static_cast<char*>(mapping2->GetBase())[1] = 'y';
  EXPECT_EQ('y', static_cast<char*>(mapping1->GetBase())[51]);
}

TEST_F(SharedBufferDispatcherTest, CreateAndMapBufferFromPlatformBuffer) {
  scoped_refptr<PlatformSharedBuffer> platform_shared_buffer =
      PlatformSharedBuffer::Create(100);
  ASSERT_TRUE(platform_shared_buffer);
  scoped_refptr<SharedBufferDispatcher> dispatcher;
  EXPECT_EQ(MOJO_RESULT_OK,
            SharedBufferDispatcher::CreateFromPlatformSharedBuffer(
                platform_shared_buffer, &dispatcher));
  ASSERT_TRUE(dispatcher);
  EXPECT_EQ(Dispatcher::Type::SHARED_BUFFER, dispatcher->GetType());

  // Make a couple of mappings.
  scoped_ptr<PlatformSharedBufferMapping> mapping1;
  EXPECT_EQ(MOJO_RESULT_OK, dispatcher->MapBuffer(
                                0, 100, MOJO_MAP_BUFFER_FLAG_NONE, &mapping1));
  ASSERT_TRUE(mapping1);
  ASSERT_TRUE(mapping1->GetBase());
  EXPECT_EQ(100u, mapping1->GetLength());
  // Write something.
  static_cast<char*>(mapping1->GetBase())[50] = 'x';

  scoped_ptr<PlatformSharedBufferMapping> mapping2;
  EXPECT_EQ(MOJO_RESULT_OK, dispatcher->MapBuffer(
                                50, 50, MOJO_MAP_BUFFER_FLAG_NONE, &mapping2));
  ASSERT_TRUE(mapping2);
  ASSERT_TRUE(mapping2->GetBase());
  EXPECT_EQ(50u, mapping2->GetLength());
  EXPECT_EQ('x', static_cast<char*>(mapping2->GetBase())[0]);

  EXPECT_EQ(MOJO_RESULT_OK, dispatcher->Close());

  // Check that we can still read/write to mappings after the dispatcher has
  // gone away.
  static_cast<char*>(mapping2->GetBase())[1] = 'y';
  EXPECT_EQ('y', static_cast<char*>(mapping1->GetBase())[51]);
}

TEST_F(SharedBufferDispatcherTest, DuplicateBufferHandle) {
  scoped_refptr<SharedBufferDispatcher> dispatcher1;
  EXPECT_EQ(MOJO_RESULT_OK, SharedBufferDispatcher::Create(
                                SharedBufferDispatcher::kDefaultCreateOptions,
                                nullptr, 100, &dispatcher1));

  // Map and write something.
  scoped_ptr<PlatformSharedBufferMapping> mapping;
  EXPECT_EQ(MOJO_RESULT_OK, dispatcher1->MapBuffer(
                                0, 100, MOJO_MAP_BUFFER_FLAG_NONE, &mapping));
  static_cast<char*>(mapping->GetBase())[0] = 'x';
  mapping.reset();

  // Duplicate |dispatcher1| and then close it.
  scoped_refptr<Dispatcher> dispatcher2;
  EXPECT_EQ(MOJO_RESULT_OK, dispatcher1->DuplicateBufferHandle(
                                nullptr, &dispatcher2));
  ASSERT_TRUE(dispatcher2);
  EXPECT_EQ(Dispatcher::Type::SHARED_BUFFER, dispatcher2->GetType());

  EXPECT_EQ(MOJO_RESULT_OK, dispatcher1->Close());

  // Map |dispatcher2| and read something.
  EXPECT_EQ(MOJO_RESULT_OK, dispatcher2->MapBuffer(
                                0, 100, MOJO_MAP_BUFFER_FLAG_NONE, &mapping));
  EXPECT_EQ('x', static_cast<char*>(mapping->GetBase())[0]);

  EXPECT_EQ(MOJO_RESULT_OK, dispatcher2->Close());
}

TEST_F(SharedBufferDispatcherTest, DuplicateBufferHandleOptionsValid) {
  scoped_refptr<SharedBufferDispatcher> dispatcher1;
  EXPECT_EQ(MOJO_RESULT_OK, SharedBufferDispatcher::Create(
                                SharedBufferDispatcher::kDefaultCreateOptions,
                                nullptr, 100, &dispatcher1));

  MojoDuplicateBufferHandleOptions options[] = {
      {sizeof(MojoDuplicateBufferHandleOptions),
       MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE},
      {sizeof(MojoDuplicateBufferHandleOptions),
       MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_READ_ONLY},
      {sizeof(MojoDuplicateBufferHandleOptionsFlags), ~0u}};
  for (size_t i = 0; i < arraysize(options); i++) {
    scoped_refptr<Dispatcher> dispatcher2;
    EXPECT_EQ(MOJO_RESULT_OK, dispatcher1->DuplicateBufferHandle(
                                  &options[i], &dispatcher2));
    ASSERT_TRUE(dispatcher2);
    EXPECT_EQ(Dispatcher::Type::SHARED_BUFFER, dispatcher2->GetType());
    {
      scoped_ptr<PlatformSharedBufferMapping> mapping;
      EXPECT_EQ(MOJO_RESULT_OK, dispatcher2->MapBuffer(0, 100, 0, &mapping));
    }
    EXPECT_EQ(MOJO_RESULT_OK, dispatcher2->Close());
  }

  EXPECT_EQ(MOJO_RESULT_OK, dispatcher1->Close());
}

TEST_F(SharedBufferDispatcherTest, DuplicateBufferHandleOptionsInvalid) {
  scoped_refptr<SharedBufferDispatcher> dispatcher1;
  EXPECT_EQ(MOJO_RESULT_OK, SharedBufferDispatcher::Create(
                                SharedBufferDispatcher::kDefaultCreateOptions,
                                nullptr, 100, &dispatcher1));

  // Invalid |struct_size|.
  {
    MojoDuplicateBufferHandleOptions options = {
        1u, MOJO_DUPLICATE_BUFFER_HANDLE_OPTIONS_FLAG_NONE};
    scoped_refptr<Dispatcher> dispatcher2;
    EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
              dispatcher1->DuplicateBufferHandle(&options, &dispatcher2));
    EXPECT_FALSE(dispatcher2);
  }

  // Unknown |flags|.
  {
    MojoDuplicateBufferHandleOptions options = {
        sizeof(MojoDuplicateBufferHandleOptions), ~0u};
    scoped_refptr<Dispatcher> dispatcher2;
    EXPECT_EQ(MOJO_RESULT_UNIMPLEMENTED,
              dispatcher1->DuplicateBufferHandle(&options, &dispatcher2));
    EXPECT_FALSE(dispatcher2);
  }

  EXPECT_EQ(MOJO_RESULT_OK, dispatcher1->Close());
}

TEST_F(SharedBufferDispatcherTest, CreateInvalidNumBytes) {
  // Size too big.
  scoped_refptr<SharedBufferDispatcher> dispatcher;
  EXPECT_EQ(MOJO_RESULT_RESOURCE_EXHAUSTED,
            SharedBufferDispatcher::Create(
                SharedBufferDispatcher::kDefaultCreateOptions, nullptr,
                std::numeric_limits<uint64_t>::max(), &dispatcher));
  EXPECT_FALSE(dispatcher);

  // Zero size.
  EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
            SharedBufferDispatcher::Create(
                SharedBufferDispatcher::kDefaultCreateOptions, nullptr, 0,
                &dispatcher));
  EXPECT_FALSE(dispatcher);
}

TEST_F(SharedBufferDispatcherTest, MapBufferInvalidArguments) {
  scoped_refptr<SharedBufferDispatcher> dispatcher;
  EXPECT_EQ(MOJO_RESULT_OK, SharedBufferDispatcher::Create(
                                SharedBufferDispatcher::kDefaultCreateOptions,
                                nullptr, 100, &dispatcher));

  scoped_ptr<PlatformSharedBufferMapping> mapping;
  EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
            dispatcher->MapBuffer(0, 101, MOJO_MAP_BUFFER_FLAG_NONE, &mapping));
  EXPECT_FALSE(mapping);

  EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
            dispatcher->MapBuffer(1, 100, MOJO_MAP_BUFFER_FLAG_NONE, &mapping));
  EXPECT_FALSE(mapping);

  EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT,
            dispatcher->MapBuffer(0, 0, MOJO_MAP_BUFFER_FLAG_NONE, &mapping));
  EXPECT_FALSE(mapping);

  EXPECT_EQ(MOJO_RESULT_OK, dispatcher->Close());
}

}  // namespace
}  // namespace edk
}  // namespace mojo


text:
import json

import numpy as np
import tables
import os
import pandas as pd

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtWidgets import QApplication, QMessageBox
from tierpsy.gui.SWTrackerViewer_ui import Ui_SWTrackerViewer
from tierpsy.gui.TrackerViewerAux import TrackerViewerAuxGUI
from tierpsy.analysis.int_ske_orient.correctHeadTailIntensity import createBlocks, _fuseOverlapingGroups

class EggWriter():
    def __init__(self):
        self.fname = os.path.expanduser(os.path.join('~', 'Desktop', 'egg_events_raw.txt'))

    def add(self, vfilename, frame_number):
        if vfilename is not None:
            base_name = os.path.splitext(os.path.basename(vfilename))[0]
            line = '\n{}\t{}'.format(base_name, frame_number)
            with open(self.fname, 'a+') as fid:
                fid.write(line)

    def tag_bad(self):
        with open(self.fname, 'a+') as fid:
            fid.write('X')

    def export(self):
        if not os.path.exists(self.fname):
            return

        tab = pd.read_table(self.fname, header=None)
        tab.columns = ['base_name', 'frame_number']
        tab_g = tab.groupby('base_name')

        fexport= os.path.expanduser(os.path.join('~', 'Desktop', 'egg_events.tsv'))
        with open(fexport, 'w') as fid:
            for base_name, dat in tab_g:
                frame_numbers = []
                for f in dat['frame_number'].values:
                    try:
                        frame_numbers.append(int(f))
                    except:
                        pass
                if frame_numbers:
                    frame_numbers = sorted(set(frame_numbers))
                    line = '\t'.join([base_name] + list(map(str, frame_numbers))) + '\n'
                    fid.write(line)

class SWTrackerViewer_GUI(TrackerViewerAuxGUI):

    def __init__(self, ui='', mask_file=''):
        if not ui:
            super().__init__(Ui_SWTrackerViewer())
        else:
            super().__init__(ui)
        self.setWindowTitle("Single Worm Viewer")

        self.skel_block = []
        self.skel_block_n = 0
        self.is_stage_move = []
        self.is_feat_file = False

        self.ui.spinBox_skelBlock.valueChanged.connect(self.changeSkelBlock)
        self.ui.checkBox_showLabel.stateChanged.connect(self.updateImage)

        if mask_file:
            self.vfilename = mask_file
            self.updateVideoFile()

        self.egg_writer = EggWriter()

    def updateVideoFile(self, vfilename):
        super().updateVideoFile(vfilename, possible_ext = ['_skeletons.hdf5', '_features.hdf5'])
        self.updateImage()

    # change frame number using the keys
    def keyPressEvent(self, event):
        # go the previous block
        if event.key() == Qt.Key_BracketLeft:
            self.ui.spinBox_skelBlock.setValue(self.skel_block_n - 1)

        # go to the next block
        elif event.key() == Qt.Key_BracketRight:
            self.ui.spinBox_skelBlock.setValue(self.skel_block_n + 1)

        elif event.key() == Qt.Key_Semicolon:
            if self.ui.checkBox_showLabel.isChecked():
                self.ui.checkBox_showLabel.setChecked(0)
            else:
                self.ui.checkBox_showLabel.setChecked(1)
        elif event.key() == Qt.Key_E:
            self.egg_writer.add(self.vfilename, self.frame_number)
        elif event.key() == Qt.Key_X:
            self.egg_writer.tag_bad()
        super().keyPressEvent(event)

    def updateSkelFile(self, skel_file, dflt_skel_size = 10):
        super().updateSkelFile(skel_file)

        self.ui.spinBox_skelBlock.setMaximum(max(len(self.skel_block) - 1, 0))
        self.ui.spinBox_skelBlock.setMinimum(0)

        if self.skel_block_n != 0:
            self.skel_block_n = 0
            self.ui.spinBox_skelBlock.setValue(0)
        else:
            self.changeSkelBlock(0)

        self.skel_block = []
        self.is_stage_move = []
        self.is_feat_file = False

        VALID_ERRORS = (IOError, KeyError, tables.exceptions.HDF5ExtError, tables.exceptions.NoSuchNodeError)
        #try to read the information from the features file if possible
        if not self.trajectories_data is None:
            try:
                # I am reading an skeleton file, so there is information about the intensity blocks
                with tables.File(self.skeletons_file, 'r') as fid:
                    #only used for skeletons, and to test the head/tail orientation. I leave it but probably should be removed for in the future
                    prov_str = fid.get_node('/provenance_tracking/INT_SKE_ORIENT').read()
                    func_arg_str = json.loads(
                        prov_str.decode("utf-8"))['func_arguments']
                    gap_size = json.loads(func_arg_str)['gap_size']

                    good = (self.trajectories_data['int_map_id'] > 0).values
                    has_skel_group = createBlocks(good, min_block_size=0)
                    if len(has_skel_group) > 0:
                        self.skel_block = _fuseOverlapingGroups(
                            has_skel_group, gap_size=gap_size)

            except VALID_ERRORS:
                self.skel_block = []

        else:
            try:
                if self.stage_position_pix is None:
                    try:
                        self.stage_position_pix = self.video_reader.fid.get_node('/stage_position_pix')[:]
                    except:
                        n_frames = len(self.video_reader)
                        self.stage_position_pix = np.full((n_frames,2), np.nan)

                timestamp = self.video_reader.fid.get_node('/timestamp/raw')[:]
                with pd.HDFStore(self.skeletons_file, 'r') as ske_file_id:
                    #this could be better so I do not have to load everything into memory, but this is faster
                    self.trajectories_data = ske_file_id['/features_timeseries']

                    if self.trajectories_data['worm_index'].unique().size !=1:
                        QMessageBox.critical(
                        self,
                        '',
                        "There is more than one worm index. This file does not seem to have been analyzed with the WT2 option.",
                        QMessageBox.Ok
                        )

                        raise KeyError()

                    good = self.trajectories_data['timestamp'].isin(timestamp)
                    self.trajectories_data = self.trajectories_data[good]
                    self.trajectories_data.sort_values(by='timestamp', inplace=True)

                    if np.any(self.trajectories_data['timestamp'] < 0) or np.any(self.trajectories_data['timestamp'].isnull()):
                        QMessageBox.critical(
                        self,
                        '',
                        'There are invalid values in the timestamp. I cannot get the stage movement information.',
                        QMessageBox.Ok)
                        raise KeyError()

                    first_frame = np.where(timestamp==self.trajectories_data['timestamp'].min())[0][0]
                    last_frame = np.where(timestamp==self.trajectories_data['timestamp'].max())[0][0]

                    self.trajectories_data['frame_number'] = np.arange(first_frame, last_frame+1, dtype=np.int)
                    self.trajectories_data['skeleton_id'] = self.trajectories_data.index

                    self.traj_time_grouped = self.trajectories_data.groupby('frame_number')

                self.is_feat_file = True

            except VALID_ERRORS:
                self.trajectories_data = None
                self.traj_time_grouped = None
                self.is_feat_file = False

            if self.stage_position_pix is not None:
                self.is_stage_move = np.isnan(self.stage_position_pix[:, 0])
        self.updateImage()

    def drawSkelSingleWorm(self):
        frame_data = self.getFrameData(self.frame_number)
        if frame_data is None:
            return

        row_data = frame_data.squeeze()

        #for this viewer there must be only one particle per frame
        if len(row_data) == 0:
            return

        isDrawSkel = self.ui.checkBox_showLabel.isChecked()
        skel_id = int(row_data['skeleton_id'])

        if isDrawSkel and skel_id >= 0:
            self.frame_qimg = self.drawSkelResult(self.frame_img, self.frame_qimg, row_data, isDrawSkel)

        return self.frame_qimg

    def updateImage(self):
        self.readCurrentFrame()
        self.drawSkelSingleWorm()

        #draw stage movement if necessary
        if len(self.is_stage_move) > 0 and self.is_stage_move[self.frame_number]:
            self.frame_qimg = self._drawRect(self.frame_qimg)

        self.mainImage.setPixmap(self.frame_qimg)

    def _drawRect(self, qimg):
        painter = QPainter()
        painter.begin(qimg)
        pen = QPen()
        pen_width = 3
        pen.setWidth(pen_width)
        pen.setColor(Qt.red)
        painter.setPen(pen)

        dw = qimg.width() - pen_width
        dh = qimg.height() - pen_width
        painter.drawRect(
            1,
            1,
            dw,
            dh)
        painter.end()
        return qimg

    def changeSkelBlock(self, val):

        self.skel_block_n = val

        if len(self.skel_block) > 0:
            self.ui.label_skelBlock.setText(
                'Block limits: %i-%i' %
                (self.skel_block[
                    self.skel_block_n]))
            # move to the frame where the block starts
            self.ui.spinBox_frame.setValue(
                self.skel_block[self.skel_block_n][0])
        else:
            self.ui.label_skelBlock.setText('')

    def closeEvent(self, event):
        self.egg_writer.export()
        super().closeEvent(event)

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    ui = SWTrackerViewer_GUI()
    ui.show()
    sys.exit(app.exec_())


text:
import { Emitter } from './factory.js';
import { isArray, isObject } from './types.js';
import { get, set, extend, reconstruct } from './proto.js';
import Symbolic from './symbolic.js';
/**
 * @typedef ChangeSet
 * @property {String} property The path to the changed property.
 * @property {*} oldValue The old value for the property.
 * @property {*} newValue The new value for the property.
 * @property {Array} added A list of added items to an array.
 * @property {Array} remove A list of remove items from an array.
 */
/**
 * Observable Symbol.
 * @type {Symbolic}
 * @private
 */
const OBSERVABLE_SYM = Symbolic('observable');
/**
 * Array prototype shortcut.
 * @type {Object}
 * @private
 */
const ARRAY_PROTO = Array.prototype;
/**
 * Object.prototype.hasOwnProperty shortcut.
 * @type {Function}
 * @private
 */
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
 * Micro Proxy polyfill.
 * @private
 */
const ProxyHelper = typeof Proxy !== 'undefined' ? Proxy : class {
    constructor(data, handler) {
        const res = reconstruct(get(data));
        Object.keys(data)
            .filter((key) => Object.getOwnPropertyDescriptor(data, key).configurable)
            .forEach((key) => {
                this.define(res, data, key, handler);
            });
        if (isArray(data)) {
            let lastLength = data.length;
            res.on('change', () => {
                if (data.length !== lastLength) {
                    Object.keys(data).forEach((key) => {
                        if (key !== OBSERVABLE_SYM) {
                            this.define(res, data, key, handler);
                        }
                    });
                    lastLength = data.length;
                }
            });
        }
        res[OBSERVABLE_SYM] = data[OBSERVABLE_SYM];
        return res;
    }
    define(res, data, property, handler) {
        const desc = {
            configurable: true,
            enumerable: ('enumerable' in handler) ? handler.enumerable : !Symbolic.isSymbolic(property),
        };
        if (handler.get) {
            desc.get = () => handler.get(data, property);
        }
        if (handler.set) {
            desc.set = (val) => handler.set(data, property, val);
        }
        Object.defineProperty(res, property, desc);
    }
};
/**
 * Trigger object changes.
 * @private
 *
 * @param {Object|Array} scope The updated object.
 * @param {ChangeSet} changeset The changes descriptor.
 */
function triggerChanges(scope, changeset) {
    return scope[OBSERVABLE_SYM].trigger('change', changeset);
}
/**
 * Wrap Array prototype methods for changes triggering.
 * @type {Object}
 * @private
 */
const ARRAY_PROTO_WRAP = {
    push(...items) {
        const length = this.length;
        items = items.map((item, index) =>
            subobserve(this, length + index, item)
        );
        const res = ARRAY_PROTO.push.call(this, ...items);
        triggerChanges(this, {
            property: length,
            added: items,
            removed: [],
        });
        return res;
    },
    unshift(item) {
        const res = ARRAY_PROTO.unshift.call(this, item);
        subobserve(this, 0, item);
        triggerChanges(this, {
            property: 0,
            added: [item],
            removed: [],
        });
        return res;
    },
    pop() {
        const res = ARRAY_PROTO.pop.call(this);
        triggerChanges(this, {
            property: this.length,
            added: [],
            removed: [res],
        });
        return res;
    },
    shift() {
        const res = ARRAY_PROTO.shift.call(this);
        triggerChanges(this, {
            property: 0,
            added: [],
            removed: [res],
        });
        return res;
    },
    splice(index, count, ...items) {
        items = items.map((item, index) =>
            subobserve(this, this.length + index, item)
        );
        const res = ARRAY_PROTO.splice.call(this, index, count, ...items);
        triggerChanges(this, {
            property: index,
            added: items,
            removed: [res],
        });
        return res;
    },
};
/**
 * Subobserve objects.
 * @private
 *
 * @param {Object|Array} target The root object.
 * @param {String} name The root object property name
 * @param {Object|Array} value The sub object to observe.
 * @return {Observable} The Observable instance for the sub object.
 */
function subobserve(target, name, value) {
    if (isObject(value) || isArray(value)) {
        value = new Observable(value);
        value.on('change', (changeset) => {
            name = isArray(target) ? target.indexOf(value) : name;
            const changes = {
                property: `${name}.${changeset.property}`,
            };
            if (hasOwnProperty.call(changeset, 'value')) {
                changes.oldValue = changeset.oldValue;
                changes.value = changeset.value;
            } else if (hasOwnProperty.call(changeset, 'added')) {
                changes.added = changeset.added;
                changes.removed = changeset.removed;
            }
            triggerChanges(target, changes);
        });
    }
    return value;
}
/**
 * ES6 Proxy handler.
 * @type {Object}
 * @private
 */
const handler = {
    getPrototypeOf(target) {
        if (isArray(target)) {
            return target.constructor.prototype;
        }
        return Reflect.getPrototypeOf(target);
    },
    get: (target, name) => target[name],
    set: (target, name, value) => {
        if (Symbolic.isSymbolic(name)) {
            return target[name] = value;
        }
        const oldValue = target[name];
        if (target[name] !== value) {
            value = subobserve(target, name, value);
            target[name] = value;
            triggerChanges(target, {
                property: name,
                oldValue,
                value,
            });
        }
        return true;
    },
};
/**
 * Create an Observable object for a set of data or an array.
 *
 * @param {Object|Array} data The object to observe.
 * @return {Proxy} The observed object proxy.
 */
export default class Observable {
    constructor(data) {
        if (typeof data !== 'object') {
            throw new Error('Cannot observe this value.');
        }
        const emitter = data[OBSERVABLE_SYM] || new Emitter();

        if (emitter.proxy) {
            return emitter.proxy;
        }
        const proto = {
            on: { value: emitter.on.bind(emitter) },
            off: { value: emitter.off.bind(emitter) },
            trigger: { value: emitter.trigger.bind(emitter) },
        };
        if (isArray(data)) {
            proto.push = { get: () => ARRAY_PROTO_WRAP.push.bind(data) };
            proto.unshift = { get: () => ARRAY_PROTO_WRAP.unshift.bind(data) };
            proto.pop = { get: () => ARRAY_PROTO_WRAP.pop.bind(data) };
            proto.shift = { get: () => ARRAY_PROTO_WRAP.shift.bind(data) };
            proto.splice = { get: () => ARRAY_PROTO_WRAP.splice.bind(data) };
        }
        data[OBSERVABLE_SYM] = emitter;
        set(data, extend(get(data), proto));
        emitter.proxy = new ProxyHelper(data, handler);
        Object.keys(data).forEach((key) => {
            if (key !== OBSERVABLE_SYM) {
                data[key] = subobserve(data, key, data[key]);
            }
        });
        return emitter.proxy;
    }
    /**
     * Re-observe an array or an object after adding a property.
     *
     * You should invoke this static method only after adding a new property
     * to an object, and only if you wish to support browsers that do not have
     * native Proxy object. This is required because it is impossible to
     * intercept new properties added to an existing object from the polyfill.
     *
     * ## Example
     *
     * ```js
     * const myObservable = new Observable({ foo: 'foo' });
     *
     * // This is not enough to trigger changes in older browsers!
     * myObservable.bar = 'bar';
     *
     * // So, you should invoke this immediately after:
     * Observable.reobserve(myObservable);
     * ```
     *
     * @param {Object|Array} data Data to be re-observed.
     * @return {void}
     */
    static reobserve(data) {
        if (typeof Proxy !== 'undefined') {
            // Native proxy support. We're good.
            return;
        }
        // Ensure `data` is an observable.
        new Observable(data);
        Object.keys(data).forEach((key) => {
            const descriptor = Object.getOwnPropertyDescriptor(data, key);
            if (key !== OBSERVABLE_SYM && descriptor && descriptor.configurable && ('value' in descriptor)) {
                // Key has been added and is not yet observed. Big Brother is on its way.
                data[key] = subobserve(data, key, data[key]);
                triggerChanges(data, {
                    property: key,
                    oldValue: undefined,
                    value: data[key],
                });
            }
        });
    }
}


text:
<?php

namespace App\Services;

use League\Flysystem\Filesystem;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Cached\CachedAdapter;
use League\Flysystem\Cached\Storage\Memory as CacheStore;

class ResourceResolver
{

    protected $builtFS = [];
    protected $resourceNamespaceConfig = [];

    public function __construct($resourceNamespaceConfig)
    {
        $this->resourceNamespaceConfig=$resourceNamespaceConfig;
    }

    public function resolve($namespace,$path){
        if(!isset($this->resourceNamespaceConfig[$namespace])){
            return false;
        }
        if(!isset($this->builtFS[$namespace])){
            $this->buildFS($namespace);
        }
        if($this->builtFS[$namespace]->has($path)){
            return [
                "content"=>$this->builtFS[$namespace]->read($path),
                "mimeType"=>$this->builtFS[$namespace]->getMimeType($path),
                "size"=>$this->builtFS[$namespace]->getSize($path)
            ];
        }
        if(!isset($this->resourceNamespaceConfig[$namespace]['fallbackNamespace'])){
            return false;
        } else {
            return $this->resolve($this->resourceNamespaceConfig[$namespace]['fallbackNamespace'],$path);
        }
    }

    public function buildFS($namespace){
        $rootPath=$this->resourceNamespaceConfig[$namespace]["path"];
        $localAdapter = new Local($rootPath);
        $cacheStore = new CacheStore();
        $adapter = new CachedAdapter($localAdapter, $cacheStore);
        $this->builtFS[$namespace] = new Filesystem($adapter);
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />

    <meta name="viewport" content="width=device-width,user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />

    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>KeymanWeb Samples</title>

KeymanWeb Samples

Test unminified Keymanweb

Test fully compiled Keymanweb

Full multilingual (compiled) Keymanweb

Return to main index.


text:
package org.arabidopsis.interval;

/** An implementation of an interval tree, following the explanation.
 * from CLR.
 */

import java.util.WeakHashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import org.apache.log4j.Logger;

public class IntervalTree {
    private StatisticUpdate updater;
    private RbTree tree;

    private Map intervals;
    private Map max;
    private Map min;

    private Logger logger;

    public IntervalTree() {
	this.updater = new IntervalTreeStatisticUpdate();
	this.tree = new RbTree(this.updater);

	this.logger = Logger.getLogger(this.getClass());

	this.intervals = new WeakHashMap();
	this.intervals.put(RbNode.NIL, null);

	this.max = new WeakHashMap();
	this.max.put(RbNode.NIL, new Integer(Integer.MIN_VALUE));
	this.min = new WeakHashMap();
	this.min.put(RbNode.NIL, new Integer(Integer.MAX_VALUE));
    }

    public void insert(Interval interval) {
	RbNode node = new RbNode(interval.getLow());
	this.intervals.put(node, interval);
	this.tree.insert(node);
    }

    public int size() {
	return this.tree.size();
    }

    // Returns the first matching interval that we can find.
    public Interval search(Interval interval) {

	RbNode node = tree.root();
	if (node.isNull())
	    return null;

	while ( (! node.isNull()) &&
		(! getInterval(node).overlaps(interval))) {
	    if (canOverlapOnLeftSide(interval, node)) {
		node = node.left;
	    } else if (canOverlapOnRightSide(interval, node)) {
		node = node.right;
	    } else {
		return null;
	    }
	}

	// Defensive coding.  node can be the NIL node, but it must
	// not be itself the null object.
	assert node != null;
	return getInterval(node);
    }

    private boolean canOverlapOnLeftSide(Interval interval,
					 RbNode node) {
	return (! node.left.isNull()) &&
	    getMax(node.left) >= interval.getLow();
    }

    private boolean canOverlapOnRightSide(Interval interval,
					 RbNode node) {
	return (! node.right.isNull()) &&
	    getMin(node.right) <= interval.getHigh();
    }

    // Returns all matches as a list of Intervals
    public List searchAll(Interval interval) {
	logger.debug("Starting search for " + interval);

	if (tree.root().isNull()) {
	    return new ArrayList();
	}
	return this._searchAll(interval, tree.root());
    }

    private List _searchAll(Interval interval, RbNode node) {
	assert (! node.isNull());

	logger.debug("Looking at " + getInterval(node));

	List results = new ArrayList();
	if (getInterval(node).overlaps(interval)) {
	    results.add(getInterval(node));
	    logger.debug("match");
	} else {
	    logger.debug("mismatch");
	}

	if (canOverlapOnLeftSide(interval, node)) {
	    results.addAll(_searchAll(interval, node.left));
	}

	if (canOverlapOnRightSide(interval, node)) {
	    results.addAll(_searchAll(interval, node.right));
	}

	return results;
    }

    public Interval getInterval(RbNode node) {
	assert (node != null);
	assert (! node.isNull());

	assert (this.intervals.containsKey(node));

	return (Interval) this.intervals.get(node);
    }

    public int getMax(RbNode node) {
	assert (node != null);
	assert (this.intervals.containsKey(node));

	return ((Integer) this.max.get(node)).intValue();
    }

    private void setMax(RbNode node, int value) {
	this.max.put(node, new Integer(value));
    }

    public int getMin(RbNode node) {
	assert (node != null);
	assert (this.intervals.containsKey(node));

	return ((Integer) this.min.get(node)).intValue();
    }

    private void setMin(RbNode node, int value) {
	this.min.put(node, new Integer(value));
    }

    private class IntervalTreeStatisticUpdate
	implements StatisticUpdate {
	public void update(RbNode node) {
	    setMax(node, max(max(getMax(node.left),
				 getMax(node.right)),
			     getInterval(node).getHigh()));

	    setMin(node, min(min(getMin(node.left),
				 getMin(node.right)),
			     getInterval(node).getLow()));
	}

	private int max(int x, int y) {
	    if (x > y) { return x; }
	    return y;
	}

	private int min(int x, int y) {
	    if (x < y) { return x; }
	    return y;
	}

    }

    /**
     *
     * Test case code: check to see that the data structure follows
     * the right constraints of interval trees:
     *
     *     o.  They're valid red-black trees
     *     o.  getMax(node) is the maximum of any interval rooted at that node..
     *
     * This code is expensive, and only meant to be used for
     * assertions and testing.
     */
    public boolean isValid() {
	return (this.tree.isValid() &&
		hasCorrectMaxFields(this.tree.root) &&
		hasCorrectMinFields(this.tree.root));
    }

    private boolean hasCorrectMaxFields(RbNode node) {
	if (node.isNull())
	    return true;
	return (getRealMax(node) == getMax(node) &&
		hasCorrectMaxFields(node.left) &&
		hasCorrectMaxFields(node.right));
    }

    private boolean hasCorrectMinFields(RbNode node) {
	if (node.isNull())
	    return true;
	return (getRealMin(node) == getMin(node) &&
		hasCorrectMinFields(node.left) &&
		hasCorrectMinFields(node.right));
    }

    private int getRealMax(RbNode node) {
	if (node.isNull())
	    return Integer.MIN_VALUE;
	int leftMax = getRealMax(node.left);
	int rightMax = getRealMax(node.right);
	int nodeHigh = getInterval(node).getHigh();

	int max1 = (leftMax > rightMax ? leftMax : rightMax);
	return (max1 > nodeHigh ? max1 : nodeHigh);
    }

    private int getRealMin(RbNode node) {
	if (node.isNull())
	    return Integer.MAX_VALUE;

	int leftMin = getRealMin(node.left);
	int rightMin = getRealMin(node.right);
	int nodeLow = getInterval(node).getLow();

	int min1 = (leftMin < rightMin ? leftMin : rightMin);
	return (min1 < nodeLow ? min1 : nodeLow);
    }

}


text:
'use strict';
module.exports.profileUploadFileFilter = function (req, file, cb) {
    if (file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/gif') {
        return cb(new Error('Only image files are allowed!'), false);
    }
    cb(null, true);
};


text:
'use strict';

module.exports = {
  isRegExp: require('./is-reg-exp'),
  validRegExp: require('./valid-reg-exp')
};


text:
package stroom.statistics.impl.sql.client.gin;

import stroom.statistics.impl.sql.client.StatisticsPlugin;
import stroom.statistics.impl.sql.client.presenter.StatisticsDataSourcePresenter;
import stroom.statistics.impl.sql.client.presenter.StatisticsDataSourceSettingsPresenter;
import stroom.statistics.impl.sql.client.presenter.StatisticsFieldEditPresenter;

import com.google.gwt.inject.client.AsyncProvider;

public interface StatisticsGinjector {

    // Statistics Data Source
    AsyncProvider<StatisticsPlugin> getStatisticPlugin();

    AsyncProvider<StatisticsDataSourcePresenter> getStatisticsDataSourcePresenter();

    AsyncProvider<StatisticsDataSourceSettingsPresenter> getStatisticsDataSourceSettingsPresenter();

    AsyncProvider<StatisticsFieldEditPresenter> getStatisticFieldEditPresenter();

}


text: <!DOCTYPE html>


text:
#ifndef __RCAR_DU_DRV_H__
#define __RCAR_DU_DRV_H__

#include <linux/kernel.h>
#include <linux/wait.h>

#include "rcar_du_crtc.h"
#include "rcar_du_group.h"

struct clk;
struct device;
struct drm_device;
struct drm_fbdev_cma;
struct rcar_du_device;
struct rcar_du_lvdsenc;

#define RCAR_DU_FEATURE_CRTC_IRQ_CLOCK	(1 << 0)	/* Per-CRTC IRQ and clock */
#define RCAR_DU_FEATURE_EXT_CTRL_REGS	(1 << 1)	/* Has extended control registers */

#define RCAR_DU_QUIRK_ALIGN_128B	(1 << 0)	/* Align pitches to 128 bytes */
#define RCAR_DU_QUIRK_LVDS_LANES	(1 << 1)	/* LVDS lanes 1 and 3 inverted */

/*
 * struct rcar_du_output_routing - Output routing specification
 * @possible_crtcs: bitmask of possible CRTCs for the output
 * @encoder_type: DRM type of the internal encoder associated with the output
 * @port: device tree port number corresponding to this output route
 *
 * The DU has 5 possible outputs (DPAD0/1, LVDS0/1, TCON). Output routing data
 * specify the valid SoC outputs, which CRTCs can drive the output, and the type
 * of in-SoC encoder for the output.
 */
struct rcar_du_output_routing {
	unsigned int possible_crtcs;
	unsigned int encoder_type;
	unsigned int port;
};

/*
 * struct rcar_du_device_info - DU model-specific information
 * @features: device features (RCAR_DU_FEATURE_*)
 * @quirks: device quirks (RCAR_DU_QUIRK_*)
 * @num_crtcs: total number of CRTCs
 * @routes: array of CRTC to output routes, indexed by output (RCAR_DU_OUTPUT_*)
 * @num_lvds: number of internal LVDS encoders
 */
struct rcar_du_device_info {
	unsigned int features;
	unsigned int quirks;
	unsigned int num_crtcs;
	struct rcar_du_output_routing routes[RCAR_DU_OUTPUT_MAX];
	unsigned int num_lvds;
};

#define RCAR_DU_MAX_CRTCS		3
#define RCAR_DU_MAX_GROUPS		DIV_ROUND_UP(RCAR_DU_MAX_CRTCS, 2)
#define RCAR_DU_MAX_LVDS		2

struct rcar_du_device {
	struct device *dev;
	const struct rcar_du_device_info *info;

	void __iomem *mmio;

	struct drm_device *ddev;
	struct drm_fbdev_cma *fbdev;

	struct rcar_du_crtc crtcs[RCAR_DU_MAX_CRTCS];
	unsigned int num_crtcs;

	struct rcar_du_group groups[RCAR_DU_MAX_GROUPS];

	struct {
		struct drm_property *alpha;
		struct drm_property *colorkey;
		struct drm_property *zpos;
	} props;

	unsigned int dpad0_source;
	struct rcar_du_lvdsenc *lvds[RCAR_DU_MAX_LVDS];

	struct {
		wait_queue_head_t wait;
		u32 pending;
	} commit;
};

static inline bool rcar_du_has(struct rcar_du_device *rcdu,
			       unsigned int feature)
{
	return rcdu->info->features & feature;
}

static inline bool rcar_du_needs(struct rcar_du_device *rcdu,
				 unsigned int quirk)
{
	return rcdu->info->quirks & quirk;
}

static inline u32 rcar_du_read(struct rcar_du_device *rcdu, u32 reg)
{
	return ioread32(rcdu->mmio + reg);
}

static inline void rcar_du_write(struct rcar_du_device *rcdu, u32 reg, u32 data)
{
	iowrite32(data, rcdu->mmio + reg);
}

#endif /* __RCAR_DU_DRV_H__ */


text:
tests:
	# symfony-skeleton
	./symfony skeleton 3.4
	./symfony skeleton 4.3
	./symfony skeleton 4.4
	#./symfony skeleton 5.0

	# website-skeleton
	./symfony website-skeleton 3.4
	./symfony website-skeleton 4.3
	./symfony website-skeleton 4.4
	#./symfony website-skeleton 5.0

	# symfony-framework
	#./symfony framework-standard-edition  3.4

	# specific
	cd ukenpachi && composer install --no-interaction