text:
package com.logica.smpp;

/**
 * This class contains all constant data values used in the SMPP
 * protocol ver 3.4 and in the library as well as some global variable
 * defaults.
 *
 * @author Logica Mobile Networks SMPP Open Source Team
 * @version 1.3, 16 Nov 2001
 */

/*
  13-07-01 ticp@logica.com default queue timeout QUEUE_TIMEOUT increased
                           from 50 msec to 10 sec
  21-09-01 ticp@logica.com added constants for registered delivery
  28-09-01 ticp@logica.com DEFAULT_IO_BUF_SIZE moved to the TCPIPConnection
                           class and renamed to DFLT_IO_BUF_SIZE
  10-10-01 ticp@logica.com max address lengths fixed according smpp spec
  16-11-01 ticp@logica.com added multibyte encoding support
*/
public class Data
{
    public static final int SM_CONNID_LEN        = 16;
    public static final int SM_MSG_LEN           = 254;
    public static final int SM_SYSID_LEN         = 16;
    public static final int SM_MSGID_LEN         = 64;
    public static final int SM_PASS_LEN          = 9;
    public static final int SM_DATE_LEN          = 17;
    public static final int SM_SRVTYPE_LEN       = 6;
    public static final int SM_SYSTYPE_LEN       = 13;
    public static final int SM_ADDR_LEN          = 21;
    public static final int SM_DATA_ADDR_LEN     = 65;
    public static final int SM_ADDR_RANGE_LEN    = 41;
    public static final int SM_TYPE_LEN          = 13;
    public static final int SM_DL_NAME_LEN       = 21;
    public static final int SM_PARAM_NAME_LEN    = 10;
    public static final int SM_PARAM_VALUE_LEN   = 10;
    public static final int SM_MAX_CNT_DEST_ADDR = 254;

    public static final int CONNECTION_CLOSED   = 0;
    public static final int CONNECTION_OPENED   = 1;

    public static final int SM_ACK              = 1;
    public static final int SM_NO_ACK           = 0;
    public static final int SM_RESPONSE_ACK     = 0;
    public static final int SM_RESPONSE_TNACK   = 1;
    public static final int SM_RESPONSE_PNACK   = 2;

    //SMPP Command Set
    public static final int GENERIC_NACK            = 0x80000000;
    public static final int BIND_RECEIVER           = 0x00000001;
    public static final int BIND_RECEIVER_RESP      = 0x80000001;
    public static final int BIND_TRANSMITTER        = 0x00000002;
    public static final int BIND_TRANSMITTER_RESP   = 0x80000002;
    public static final int QUERY_SM                = 0x00000003;
    public static final int QUERY_SM_RESP           = 0x80000003;
    public static final int SUBMIT_SM               = 0x00000004;
    public static final int SUBMIT_SM_RESP          = 0x80000004;
    public static final int DELIVER_SM              = 0x00000005;
    public static final int DELIVER_SM_RESP         = 0x80000005;
    public static final int UNBIND                  = 0x00000006;
    public static final int UNBIND_RESP             = 0x80000006;
    public static final int REPLACE_SM              = 0x00000007;
    public static final int REPLACE_SM_RESP         = 0x80000007;
    public static final int CANCEL_SM               = 0x00000008;
    public static final int CANCEL_SM_RESP          = 0x80000008;
    public static final int BIND_TRANSCEIVER        = 0x00000009;
    public static final int BIND_TRANSCEIVER_RESP   = 0x80000009;
    public static final int OUTBIND                 = 0x0000000B;
    public static final int ENQUIRE_LINK            = 0x00000015;
    public static final int ENQUIRE_LINK_RESP       = 0x80000015;
    public static final int SUBMIT_MULTI            = 0x00000021;
    public static final int SUBMIT_MULTI_RESP       = 0x80000021;
    public static final int ALERT_NOTIFICATION      = 0x00000102;
    public static final int DATA_SM                 = 0x00000103;
    public static final int DATA_SM_RESP            = 0x80000103;

    //Command_Status Error Codes
    public static final int ESME_ROK                = 0x00000000;
    public static final int ESME_RINVMSGLEN         = 0x00000001;
    public static final int ESME_RINVCMDLEN         = 0x00000002;
    public static final int ESME_RINVCMDID          = 0x00000003;
    public static final int ESME_RINVBNDSTS         = 0x00000004;
    public static final int ESME_RALYBND            = 0x00000005;
    public static final int ESME_RINVPRTFLG         = 0x00000006;
    public static final int ESME_RINVREGDLVFLG      = 0x00000007;
    public static final int ESME_RSYSERR            = 0x00000008;
    public static final int ESME_RINVSRCADR         = 0x0000000A;
    public static final int ESME_RINVDSTADR         = 0x0000000B;
    public static final int ESME_RINVMSGID          = 0x0000000C;
    public static final int ESME_RBINDFAIL          = 0x0000000D;
    public static final int ESME_RINVPASWD          = 0x0000000E;
    public static final int ESME_RINVSYSID          = 0x0000000F;
    public static final int ESME_RCANCELFAIL        = 0x00000011;
    public static final int ESME_RREPLACEFAIL       = 0x00000013;
    public static final int ESME_RMSGQFUL           = 0x00000014;
    public static final int ESME_RINVSERTYP         = 0x00000015;

    public static final int ESME_RADDCUSTFAIL       = 0x00000019;  // Failed to Add Customer
    public static final int ESME_RDELCUSTFAIL       = 0x0000001A;  // Failed to delete Customer
    public static final int ESME_RMODCUSTFAIL       = 0x0000001B;  // Failed to modify customer
    public static final int ESME_RENQCUSTFAIL       = 0x0000001C;  // Failed to Enquire Customer
    public static final int ESME_RINVCUSTID         = 0x0000001D;  // Invalid Customer ID
    public static final int ESME_RINVCUSTNAME       = 0x0000001F;  // Invalid Customer Name
    public static final int ESME_RINVCUSTADR        = 0x00000021;  // Invalid Customer Address
    public static final int ESME_RINVADR            = 0x00000022;  // Invalid Address
    public static final int ESME_RCUSTEXIST         = 0x00000023;  // Customer Exists
    public static final int ESME_RCUSTNOTEXIST      = 0x00000024;  // Customer does not exist
    public static final int ESME_RADDDLFAIL         = 0x00000026;  // Failed to Add DL
    public static final int ESME_RMODDLFAIL         = 0x00000027;  // Failed to modify DL
    public static final int ESME_RDELDLFAIL         = 0x00000028;  // Failed to Delete DL
    public static final int ESME_RVIEWDLFAIL        = 0x00000029;  // Failed to View DL
    public static final int ESME_RLISTDLSFAIL       = 0x00000030;  // Failed to list DLs
    public static final int ESME_RPARAMRETFAIL      = 0x00000031;  // Param Retrieve Failed
    public static final int ESME_RINVPARAM          = 0x00000032;  // Invalid Param

    public static final int ESME_RINVNUMDESTS       = 0x00000033;
    public static final int ESME_RINVDLNAME         = 0x00000034;

    public static final int ESME_RINVDLMEMBDESC     = 0x00000035;  // Invalid DL Member Description
    public static final int ESME_RINVDLMEMBTYP      = 0x00000038;  // Invalid DL Member Type
    public static final int ESME_RINVDLMODOPT       = 0x00000039;  // Invalid DL Modify Option

    public static final int ESME_RINVDESTFLAG       = 0x00000040;
    public static final int ESME_RINVSUBREP         = 0x00000042;
    public static final int ESME_RINVESMCLASS       = 0x00000043;
    public static final int ESME_RCNTSUBDL          = 0x00000044;
    public static final int ESME_RSUBMITFAIL        = 0x00000045;
    public static final int ESME_RINVSRCTON         = 0x00000048;
    public static final int ESME_RINVSRCNPI         = 0x00000049;
    public static final int ESME_RINVDSTTON         = 0x00000050;
    public static final int ESME_RINVDSTNPI         = 0x00000051;
    public static final int ESME_RINVSYSTYP         = 0x00000053;
    public static final int ESME_RINVREPFLAG        = 0x00000054;
    public static final int ESME_RINVNUMMSGS        = 0x00000055;
    public static final int ESME_RTHROTTLED         = 0x00000058;

    public static final int ESME_RPROVNOTALLWD      = 0x00000059;  // Provisioning Not Allowed

    public static final int ESME_RINVSCHED          = 0x00000061;
    public static final int ESME_RINVEXPIRY         = 0x00000062;
    public static final int ESME_RINVDFTMSGID       = 0x00000063;
    public static final int ESME_RX_T_APPN          = 0x00000064;
    public static final int ESME_RX_P_APPN          = 0x00000065;
    public static final int ESME_RX_R_APPN          = 0x00000066;
    public static final int ESME_RQUERYFAIL         = 0x00000067;

    public static final int ESME_RINVPGCUSTID       = 0x00000080;  // Paging Customer ID Invalid No such subscriber
    public static final int ESME_RINVPGCUSTIDLEN    = 0x00000081;  // Paging Customer ID length Invalid
    public static final int ESME_RINVCITYLEN        = 0x00000082;  // City Length Invalid
    public static final int ESME_RINVSTATELEN       = 0x00000083;  // State Length Invalid
    public static final int ESME_RINVZIPPREFIXLEN   = 0x00000084;  // Zip Prefix Length Invalid
    public static final int ESME_RINVZIPPOSTFIXLEN  = 0x00000085;  // Zip Postfix Length Invalid
    public static final int ESME_RINVMINLEN         = 0x00000086;  // MIN Length Invalid
    public static final int ESME_RINVMIN            = 0x00000087;  // MIN Invalid (i.e. No such MIN)
    public static final int ESME_RINVPINLEN         = 0x00000088;  // PIN Length Invalid
    public static final int ESME_RINVTERMCODELEN    = 0x00000089;  // Terminal Code Length Invalid
    public static final int ESME_RINVCHANNELLEN     = 0x0000008A;  // Channel Length Invalid
    public static final int ESME_RINVCOVREGIONLEN   = 0x0000008B;  // Coverage Region Length Invalid
    public static final int ESME_RINVCAPCODELEN     = 0x0000008C;  // Cap Code Length Invalid
    public static final int ESME_RINVMDTLEN         = 0x0000008D;  // Message delivery time Length Invalid
    public static final int ESME_RINVPRIORMSGLEN    = 0x0000008E;  // Priority Message Length Invalid
    public static final int ESME_RINVPERMSGLEN      = 0x0000008F;  // Periodic Messages Length Invalid
    public static final int ESME_RINVPGALERTLEN     = 0x00000090;  // Paging Alerts Length Invalid
    public static final int ESME_RINVSMUSERLEN      = 0x00000091;  // Short Message User Group Length Invalid
    public static final int ESME_RINVRTDBLEN        = 0x00000092;  // Real Time Data broadcasts Length Invalid
    public static final int ESME_RINVREGDELLEN      = 0x00000093;  // Registered Delivery Lenght Invalid
    public static final int ESME_RINVMSGDISTLEN     = 0x00000094;  // Message Distribution Lenght Invalid
    public static final int ESME_RINVPRIORMSG       = 0x00000095;  // Priority Message Length Invalid
    public static final int ESME_RINVMDT            = 0x00000096;  // Message delivery time Invalid
    public static final int ESME_RINVPERMSG         = 0x00000097;  // Periodic Messages Invalid
    public static final int ESME_RINVMSGDIST        = 0x00000098;  // Message Distribution Invalid
    public static final int ESME_RINVPGALERT        = 0x00000099;  // Paging Alerts Invalid
    public static final int ESME_RINVSMUSER         = 0x0000009A;  // Short Message User Group Invalid
    public static final int ESME_RINVRTDB           = 0x0000009B;  // Real Time Data broadcasts Invalid
    public static final int ESME_RINVREGDEL         = 0x0000009C;  // Registered Delivery Invalid
    public static final int ESME_RINVOPTPARSTREAM   = 0x0000009D;  // KIF IW Field out of data
    public static final int ESME_ROPTPARNOTALLWD    = 0x0000009E;  // Optional Parameter not allowed
    public static final int ESME_RINVOPTPARLEN      = 0x0000009F;  // Invalid Optional Parameter Length

    public static final int ESME_RMISSINGOPTPARAM   = 0x000000C3;
    public static final int ESME_RINVOPTPARAMVAL    = 0x000000C4;
    public static final int ESME_RDELIVERYFAILURE   = 0x000000FE;
    public static final int ESME_RUNKNOWNERR        = 0x000000FF;

    public static final int ESME_LAST_ERROR         = 0x0000012C;  // the value of the last error code

    //Interface_Version
    public static final byte SMPP_V33               = (byte)0x00-0x33;
    public static final byte SMPP_V34               = (byte)0x34;

    //Address_TON
    public static final byte GSM_TON_UNKNOWN        = (byte)0x00;
    public static final byte GSM_TON_INTERNATIONAL  = (byte)0x01;
    public static final byte GSM_TON_NATIONAL       = (byte)0x02;
    public static final byte GSM_TON_NETWORK        = (byte)0x03;
    public static final byte GSM_TON_SUBSCRIBER     = (byte)0x04;
    public static final byte GSM_TON_ALPHANUMERIC   = (byte)0x05;
    public static final byte GSM_TON_ABBREVIATED    = (byte)0x06;
    public static final byte GSM_TON_RESERVED_EXTN  = 0x07;

    //Address_NPI
    public static final byte GSM_NPI_UNKNOWN        = (byte)0x00;
    public static final byte GSM_NPI_E164           = (byte)0x01;
    public static final byte GSM_NPI_ISDN           = GSM_NPI_E164;
    public static final byte GSM_NPI_X121           = (byte)0x03;
    public static final byte GSM_NPI_TELEX          = (byte)0x04;
    public static final byte GSM_NPI_LAND_MOBILE    = (byte)0x06;
    public static final byte GSM_NPI_NATIONAL       = (byte)0x08;
    public static final byte GSM_NPI_PRIVATE        = (byte)0x09;
    public static final byte GSM_NPI_ERMES          = (byte)0x0A;
    public static final byte GSM_NPI_INTERNET       = (byte)0x0E;
    public static final byte GSM_NPI_WAP_CLIENT_ID  = (byte)0x12;
    public static final byte GSM_NPI_RESERVED_EXTN  = 0x0F;

    //Service_Type
    public static final String SERVICE_NULL         = "";
    public static final String SERVICE_CMT          = "CMT";
    public static final String SERVICE_CPT          = "CPT";
    public static final String SERVICE_VMN          = "VMN";
    public static final String SERVICE_VMA          = "VMA";
    public static final String SERVICE_WAP          = "WAP";
    public static final String SERVICE_USSD         = "USSD";

    public static final byte SMPP_PROTOCOL          = (byte)1;
    public static final byte SMPPP_PROTOCOL         = (byte)2;
    public static final byte SM_SERVICE_MOBILE_TERMINATED   = (byte)0;
    public static final byte SM_SERVICE_MOBILE_ORIGINATED   = (byte)1;
    public static final byte SM_SERVICE_MOBILE_TRANSCEIVER  = (byte)2;

    // State of message at SMSC
    public static final int SM_STATE_EN_ROUTE       = 1;  // default state for messages in transit
    public static final int SM_STATE_DELIVERED      = 2;  // message is delivered
    public static final int SM_STATE_EXPIRED        = 3;  // validity period expired
    public static final int SM_STATE_DELETED        = 4;  // message has been deleted
    public static final int SM_STATE_UNDELIVERABLE  = 5;  // undeliverable
    public static final int SM_STATE_ACCEPTED       = 6;  // message is in accepted state
    public static final int SM_STATE_INVALID        = 7;  // message is in invalid state
    public static final int SM_STATE_REJECTED       = 8;  // message is in rejected state

    //******************
    // ESMClass Defines
    //******************

    // Messaging Mode
    public static final int SM_ESM_DEFAULT          = 0x00;  //Default SMSC Mode or Message Type
    public static final int SM_DATAGRAM_MODE        = 0x01;  // Use one-shot express mode
    public static final int SM_FORWARD_MODE         = 0x02;  // Do not use
    public static final int SM_STORE_FORWARD_MODE   = 0x03;  // Use store & forward

    // Send/Receive TDMA & CDMA Message Type
    public static final int SM_SMSC_DLV_RCPT_TYPE       = 0x04;  // Recv Msg contains SMSC delivery receipt
    public static final int SM_ESME_DLV_ACK_TYPE        = 0x08;  // Send/Recv Msg contains ESME delivery acknowledgement
    public static final int SM_ESME_MAN_USER_ACK_TYPE   = 0x10;  // Send/Recv Msg contains manual/user acknowledgment
    public static final int SM_CONV_ABORT_TYPE          = 0x18;  // Recv Msg contains conversation abort (Korean CDMA)
    public static final int SM_INTMD_DLV_NOTIFY_TYPE    = 0x20;  // Recv Msg contains intermediate notification

    // GSM Network features
    public static final int SM_NONE_GSM             = 0x00;  // No specific features selected
    public static final int SM_UDH_GSM              = 0x40;  // User Data Header indicator set
    public static final int SM_REPLY_PATH_GSM       = 0x80;  // Reply path set
    public static final int SM_UDH_REPLY_PATH_GSM   = 0xC0;  // Both UDH & Reply path

    // Optional Parameter Tags, Min and Max Lengths
    // Following are the 2 byte tag and min/max lengths for
    // supported optional parameter (declann)

    public static final short OPT_PAR_MSG_WAIT        = 2;

    // Privacy Indicator
    public static final short OPT_PAR_PRIV_IND        = 0x0201;

    // Source Subaddress
    public static final short OPT_PAR_SRC_SUBADDR         = 0x0202;
    public static final int   OPT_PAR_SRC_SUBADDR_MIN     = 2;
    public static final int   OPT_PAR_SRC_SUBADDR_MAX     = 23;

    // Destination Subaddress
    public static final short OPT_PAR_DEST_SUBADDR        = 0x0203;
    public static final int   OPT_PAR_DEST_SUBADDR_MIN    = 2;
    public static final int   OPT_PAR_DEST_SUBADDR_MAX    = 23;

    // User Message Reference
    public static final short OPT_PAR_USER_MSG_REF        = 0x0204;

    // User Response Code
    public static final short OPT_PAR_USER_RESP_CODE      = 0x0205;

    // Language Indicator
    public static final short OPT_PAR_LANG_IND            = 0x020D;

    // Source Port
    public static final short OPT_PAR_SRC_PORT            = 0x020A;

    // Destination Port
    public static final short OPT_PAR_DST_PORT            = 0x020B;

    // Concat Msg Ref Num
    public static final short OPT_PAR_SAR_MSG_REF_NUM     = 0x020C;

    // Concat Total Segments
    public static final short OPT_PAR_SAR_TOT_SEG         = 0x020E;

    // Concat Segment Seqnums
    public static final short OPT_PAR_SAR_SEG_SNUM        = 0x020F;

    // SC Interface Version
    public static final short OPT_PAR_SC_IF_VER           = 0x0210;

    // Display Time
    public static final short OPT_PAR_DISPLAY_TIME        = 0x1201;

    // Validity Information
    public static final short OPT_PAR_MS_VALIDITY         = 0x1204;

    // DPF Result
    public static final short OPT_PAR_DPF_RES             = 0x0420;

    // Set DPF
    public static final short OPT_PAR_SET_DPF             = 0x0421;

    // MS Availability Status
    public static final short OPT_PAR_MS_AVAIL_STAT       = 0x0422;

    // Network Error Code
    public static final short OPT_PAR_NW_ERR_CODE         = 0x0423;
    public static final int OPT_PAR_NW_ERR_CODE_MIN     = 3;
    public static final int OPT_PAR_NW_ERR_CODE_MAX     = 3;

    // Extended Short Message has no size limit

    // Delivery Failure Reason
    public static final short OPT_PAR_DEL_FAIL_RSN        = 0x0425;

    // More Messages to Follow
    public static final short OPT_PAR_MORE_MSGS           = 0x0426;

    // Message State
    public static final short OPT_PAR_MSG_STATE           = 0x0427;

    // Callback Number
    public static final short OPT_PAR_CALLBACK_NUM        = 0x0381;
    public static final int OPT_PAR_CALLBACK_NUM_MIN    = 4;
    public static final int OPT_PAR_CALLBACK_NUM_MAX    = 19;

    // Callback Number Presentation  Indicator
    public static final short OPT_PAR_CALLBACK_NUM_PRES_IND       = 0x0302;

    // Callback Number Alphanumeric Tag
    public static final short OPT_PAR_CALLBACK_NUM_ATAG           = 0x0303;
    public static final int OPT_PAR_CALLBACK_NUM_ATAG_MIN       = 1;
    public static final int OPT_PAR_CALLBACK_NUM_ATAG_MAX       = 65;

    // Number of messages in Mailbox
    public static final short OPT_PAR_NUM_MSGS            = 0x0304;

    // SMS Received Alert
    public static final short OPT_PAR_SMS_SIGNAL          = 0x1203;

    // Message Delivery Alert
    public static final short OPT_PAR_ALERT_ON_MSG_DELIVERY       = 0x130C;

    // ITS Reply Type
    public static final short OPT_PAR_ITS_REPLY_TYPE      = 0x1380;

    // ITS Session Info
    public static final short OPT_PAR_ITS_SESSION_INFO            = 0x1383;

    // USSD Service Op
    public static final short OPT_PAR_USSD_SER_OP         = 0x0501;

    // Priority
    public static final int SM_NOPRIORITY               = 0;
    public static final int SM_PRIORITY                 = 1;

    // Registered delivery
    //   SMSC Delivery Receipt (bits 1 & 0)
    public static final byte SM_SMSC_RECEIPT_MASK            = 0x03;
    public static final byte SM_SMSC_RECEIPT_NOT_REQUESTED   = 0x00;
    public static final byte SM_SMSC_RECEIPT_REQUESTED       = 0x01;
    public static final byte SM_SMSC_RECEIPT_ON_FAILURE      = 0x02;
    //   SME originated acknowledgement (bits 3 & 2)
    public static final byte SM_SME_ACK_MASK               = 0x0c;
    public static final byte SM_SME_ACK_NOT_REQUESTED      = 0x00;
    public static final byte SM_SME_ACK_DELIVERY_REQUESTED = 0x04;
    public static final byte SM_SME_ACK_MANUAL_REQUESTED   = 0x08;
    public static final byte SM_SME_ACK_BOTH_REQUESTED     = 0x0c;
    //   Intermediate notification (bit 5)
    public static final byte SM_NOTIF_MASK                 = 0x010;
    public static final byte SM_NOTIF_NOT_REQUESTED        = 0x000;
    public static final byte SM_NOTIF_REQUESTED            = 0x010;

    // Replace if Present flag
    public static final int SM_NOREPLACE                = 0;
    public static final int SM_REPLACE                  = 1;

    // Destination flag
    public static final int SM_DEST_SME_ADDRESS         = 1;
    public static final int SM_DEST_DL_NAME             = 2;

    // Higher Layer Message Type
    public static final int SM_LAYER_WDP                = 0;
    public static final int SM_LAYER_WCMP               = 1;

    // Operation Class
    public static final int SM_OPCLASS_DATAGRAM         = 0;
    public static final int SM_OPCLASS_TRANSACTION      = 3;

    // Originating MSC Address
    public static final short OPT_PAR_ORIG_MSC_ADDR       = (short)0x8081;
    public static final int OPT_PAR_ORIG_MSC_ADDR_MIN   = 1;
    public static final int OPT_PAR_ORIG_MSC_ADDR_MAX   = 24;

    // Destination MSC Address
    public static final short OPT_PAR_DEST_MSC_ADDR       = (short)0x8082;
    public static final int OPT_PAR_DEST_MSC_ADDR_MIN   = 1;
    public static final int OPT_PAR_DEST_MSC_ADDR_MAX   = 24;

    // Unused Tag
    public static final int OPT_PAR_UNUSED              = 0xffff;

    // Destination Address Subunit
    public static final short OPT_PAR_DST_ADDR_SUBUNIT        = 0x0005;

    // Destination Network Type
    public static final short OPT_PAR_DST_NW_TYPE         = 0x0006;

    // Destination Bearer Type
    public static final short OPT_PAR_DST_BEAR_TYPE       = 0x0007;

    // Destination Telematics ID
    public static final short OPT_PAR_DST_TELE_ID         = 0x0008;

    // Source Address Subunit
    public static final short OPT_PAR_SRC_ADDR_SUBUNIT    = 0x000D;

    // Source Network Type
    public static final short OPT_PAR_SRC_NW_TYPE         = 0x000E;

    // Source Bearer Type
    public static final short OPT_PAR_SRC_BEAR_TYPE       = 0x000F;

    // Source Telematics ID
    public static final short OPT_PAR_SRC_TELE_ID         = 0x0010;

    // QOS Time to Live
    public static final short OPT_PAR_QOS_TIME_TO_LIVE        = 0x0017;
    public static final int OPT_PAR_QOS_TIME_TO_LIVE_MIN    = 1;
    public static final int OPT_PAR_QOS_TIME_TO_LIVE_MAX    = 4;

    // Payload Type
    public static final short OPT_PAR_PAYLOAD_TYPE        = 0x0019;

    // Additional Status Info Text
    public static final short OPT_PAR_ADD_STAT_INFO       = 0x001D;
    public static final int OPT_PAR_ADD_STAT_INFO_MIN   = 1;
    public static final int OPT_PAR_ADD_STAT_INFO_MAX   = 256;

    // Receipted Message ID
    public static final short OPT_PAR_RECP_MSG_ID         = 0x001E;
    public static final int OPT_PAR_RECP_MSG_ID_MIN     = 1;
    public static final int OPT_PAR_RECP_MSG_ID_MAX     = 65;

    // Message Payload
    public static final short OPT_PAR_MSG_PAYLOAD         = 0x0424;
    public static final int OPT_PAR_MSG_PAYLOAD_MIN     = 1;
    public static final int OPT_PAR_MSG_PAYLOAD_MAX     = 1500;

    // list of character encodings
    // see http://java.sun.com/j2se/1.3/docs/guide/intl/encoding.doc.html
    // from rt.jar

    // American Standard Code for Information Interchange
    public static final String ENC_ASCII = "ASCII";
    // Windows Latin-1
    public static final String ENC_CP1252 = "Cp1252";
    // ISO 8859-1, Latin alphabet No. 1
    public static final String ENC_ISO8859_1 = "ISO8859_1";
    // Sixteen-bit Unicode Transformation Format, big-endian byte order
    // with byte-order mark
    public static final String ENC_UTF16_BEM = "UnicodeBig";
    // Sixteen-bit Unicode Transformation Format, big-endian byte order
    public static final String ENC_UTF16_BE = "UnicodeBigUnmarked";
    // Sixteen-bit Unicode Transformation Format, little-endian byte order
    // with byte-order mark
    public static final String ENC_UTF16_LEM = "UnicodeLittle";
    // Sixteen-bit Unicode Transformation Format, little-endian byte order
    public static final String ENC_UTF16_LE = "UnicodeLittleUnmarked";
    // Eight-bit Unicode Transformation Format
    public static final String ENC_UTF8 = "UTF8";
    // Sixteen-bit Unicode Transformation Format, byte order specified by
    // a mandatory initial byte-order mark
    public static final String ENC_UTF16 = "UTF-16";

    /**
     * @deprecated As of version 1.3 of the library there are defined
     * new encoding constants for base set of encoding supported by Java Runtime.
     * The <code>CHAR_ENC</code> is replaced by <code>ENC_ASCII</code>
     * and redefined in this respect.
     */
    public static final String CHAR_ENC         = ENC_ASCII;

    public static final String DFLT_MSGID               = "";
    public static final String DFLT_MSG                 = "";
    public static final String DFLT_SRVTYPE             = "";
    public static final String DFLT_SYSID               = "";
    public static final String DFLT_PASS                = "";
    public static final String DFLT_SYSTYPE             = "";
    public static final String DFLT_ADDR_RANGE          = "";
    public static final String DFLT_DATE                = "";
    public static final String DFLT_ADDR                = "";
    public static final byte   DFLT_MSG_STATE           = 0;
    public static final byte   DFLT_ERR                 = 0;
    public static final String DFLT_SCHEDULE            = "";
    public static final String DFLT_VALIDITY            = "";
    public static final byte   DFLT_REG_DELIVERY        =
        SM_SMSC_RECEIPT_NOT_REQUESTED | SM_SME_ACK_NOT_REQUESTED | SM_NOTIF_NOT_REQUESTED;
    public static final byte   DFLT_DFLTMSGID           = 0;
    public static final byte   DFLT_MSG_LEN             = 0;
    public static final byte   DFLT_ESM_CLASS           = 0;
    public static final byte   DFLT_DATA_CODING         = 0;
    public static final byte   DFLT_PROTOCOLID          = 0;
    public static final byte   DFLT_PRIORITY_FLAG       = 0;
    public static final byte   DFTL_REPLACE_IFP         = 0;
    public static final String DFLT_DL_NAME             = "";
    public static final byte   DFLT_GSM_TON             = GSM_TON_UNKNOWN;
    public static final byte   DFLT_GSM_NPI             = GSM_NPI_UNKNOWN;
    public static final byte   DFLT_DEST_FLAG           = 0; // not set
    public static final int    MAX_PDU_LEN              = 5000;

    public static final int PDU_HEADER_SIZE  = 16; // 4 integers
    public static final int TLV_HEADER_SIZE  = 4;  // 2 shorts: tag & length

    // all times in milliseconds
    public static final long RECEIVER_TIMEOUT           = 60000;
    public static final long CONNECTION_RECEIVE_TIMEOUT = 10000;
    public static final long COMMS_TIMEOUT              = 60000;
    public static final long QUEUE_TIMEOUT              = 10000;
    public static final long ACCEPT_TIMEOUT             = 5000;

    public static final long RECEIVE_BLOCKING           = -1;

    public static final int MAX_VALUE_PORT              = 99999;
    public static final int MIN_VALUE_PORT              = 100;
    public static final int MIN_LENGTH_ADDRESS          = 7;

    static private byte defaultTon = Data.DFLT_GSM_TON;
    static private byte defaultNpi = Data.DFLT_GSM_NPI;

    static final public synchronized void setDefaultTon(byte dfltTon) {
        defaultTon = dfltTon;
    }
    static final public synchronized void setDefaultNpi(byte dfltNpi) {
        defaultNpi = dfltNpi;
    }

    static final public synchronized byte getDefaultTon() { return defaultTon; }
    static final public synchronized byte getDefaultNpi() { return defaultNpi; }

    static final public long getCurrentTime() {
        return System.currentTimeMillis();
        // return Calendar.getInstance().getTime().getTime();
    }

}


text:
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
from math import *
from datetime import *
from copy import copy
import sys
import argparse

# Commands
CMD_DID_DRAW = "D"
CMD_SYNC_CLIENT_CONNECT = "S"
CMD_ASYNC_CLIENT_CONNECT = "A"
CMD_BROADCAST = "T"
CMD_PAUSE = "P"
CMD_RESET = "R"
CMD_GO = "G"

# Parse the command line arguments
parser = argparse.ArgumentParser(description='Most Pixels Ever Server, conforms to protocol version 2.0')
parser.add_argument('--screens', dest='screens', default=-1, help='The number of clients. The server won\'t start the draw loop until all of the clients are connected.')
parser.add_argument('--port', dest='port_num', default=9002, help='The port number that the clients connect to.')
parser.add_argument('--framerate', dest='framerate', default=60, help='The target framerate.')
args = parser.parse_args()

portnum = int(args.port_num)
screens_required = int(args.screens)
framerate = int(args.framerate)
microseconds_per_frame = (1.0 / framerate) * 1000000
framecount = 0
screens_drawn = 0
is_paused = False
last_frame_time = datetime.now()

class BroadcastMessage:

    def __init__(self, body, from_client_id, to_client_ids = []):
        self.body = body
        self.from_client_id = from_client_id
        self.to_client_ids = to_client_ids

class MPEServer(Protocol):

    client_id = -1
    client_name = ""

    def connectionMade(self):
        print("Client connected. Total Clients: %i" % (len(MPEServer.clients) + 1))

    def connectionLost(self, reason):
        print("Client disconnected")
        if MPEServer.clients[self.client_id]:
            del MPEServer.clients[self.client_id]
        if self.client_id in MPEServer.rendering_client_ids:
            MPEServer.rendering_client_ids.remove(self.client_id)
        if self.client_id in MPEServer.receiving_client_ids:
            MPEServer.receiving_client_ids.remove(self.client_id)
        # It's possible that isNextFrameReady is true after the client disconnects
        # if they were the last client to render and hadn't informed the server.
        if MPEServer.isNextFrameReady():
            MPEServer.sendNextFrame()

    def dataReceived(self, data):
        global screens_drawn
        global framecount
        # Parse data as utf-8, not byte string
        data = data.decode("utf_8")
        # There may be more than 1 message in the mix
        messages = data.split("\n")
        for message in messages:
            if len(message) < 1:
                return

            tokens = message.split("|")
            token_count = len(tokens)
            cmd = tokens[0]

            if cmd == CMD_DID_DRAW:
                # Format
                # D|client_id|last_frame_rendered
                if token_count != 3:
                    print("ERROR: Incorrect param count for CMD %s. " % cmd, data, tokens)
                client = int(tokens[1])
                frame_id = int(tokens[2])
                if frame_id >= framecount:
                    screens_drawn += 1
                    if MPEServer.isNextFrameReady():
                        # all of the frames are drawn, send out the next frames
                        MPEServer.sendNextFrame()

            elif (cmd == CMD_SYNC_CLIENT_CONNECT) or (cmd == CMD_ASYNC_CLIENT_CONNECT):
                # Formats
                # "S|client_id|client_name"
                # "A|client_id|client_name|should_receive_broadcasts"
                if token_count < 3 or token_count > 4:
                    print("ERROR: Incorrect param count for CMD %s. " % cmd, data, tokens)
                self.client_id = int(tokens[1])
                self.client_name = tokens[2]
                MPEServer.clients[self.client_id] = self

                client_receives_messages = True
                if cmd == CMD_SYNC_CLIENT_CONNECT:
                    MPEServer.rendering_client_ids.append(self.client_id)
                elif cmd == CMD_ASYNC_CLIENT_CONNECT:
                    client_receives_messages = tokens[3].lower() == 'true'

                if client_receives_messages:
                    print("New client will receive data")
                    MPEServer.receiving_client_ids.append(self.client_id)

                MPEServer.handleClientAdd(self.client_id)

            elif cmd == CMD_BROADCAST:
                # Formats:
                # "T|message message message"
                # "T|message message message|toID_1,toID_2,toID_3"
                if token_count < 2 or token_count > 3:
                    print("ERROR: Incorrect param count for CMD %s. " % cmd, data, tokens)
                to_client_ids = []
                if token_count == 2:
                    to_client_ids = MPEServer.receiving_client_ids
                elif token_count == 3:
                    to_client_ids = tokens[2].split(",")
                    to_client_ids = [int(client_id) for client_id in to_client_ids]

                MPEServer.broadcastMessage(tokens[1], self.client_id, to_client_ids)

            elif cmd == CMD_PAUSE:
                # Format:
                # P
                if token_count > 1:
                    print("ERROR: Incorrect param count for CMD %s. " % cmd, data, tokens)
                MPEServer.togglePause()

            elif cmd == CMD_RESET:
                # Format:
                # R
                if token_count > 1:
                    print("ERROR: Incorrect param count for CMD %s. " % cmd, data, tokens)
                MPEServer.reset()

            else:
                print("Unknown message: " + message)

        # print("Received message: ", data, "FROM", self.client_id)

    def sendMessage(self, message):
        # Must use byte string, not unicode string
        message = message + "\n"
        self.transport.write(message.encode('utf_8'))

    @staticmethod
    def reset():
        global framecount
        global is_paused
        framecount = 0
        screens_drawn = 0
        MPEServer.message_queue = []
        MPEServer.sendReset()
        if is_paused:
            print("INFO: Reset was called when server is paused.")
        MPEServer.sendNextFrame()

    @staticmethod
    def sendReset():
        for n in MPEServer.receiving_client_ids:
            MPEServer.clients[n].sendMessage(CMD_RESET)

    @staticmethod
    def togglePause():
        global is_paused
        is_paused = not is_paused
        if MPEServer.isNextFrameReady():
            MPEServer.sendNextFrame()

    @staticmethod
    def handleClientAdd(client_id):
        global framecount
        global screens_required
        print("Added client %i (%s)" % (client_id, MPEServer.clients[client_id].client_name))
        num_sync_clients = len(MPEServer.rendering_client_ids)
        if screens_required == -1 or num_sync_clients == screens_required:
            # NOTE: We don't reset when an async client connects
            if client_id in MPEServer.rendering_client_ids:
                MPEServer.reset()
        elif num_sync_clients < screens_required:
            print("Waiting for %i more clients." % (screens_required - num_sync_clients))
        elif num_sync_clients > screens_required:
            print("ERROR: More than MAX clients have connected.")

    @staticmethod
    def isNextFrameReady():
        global screens_drawn
        global screens_required
        global is_paused
        num_sync_clients = len(MPEServer.rendering_client_ids)
        return screens_drawn >= num_sync_clients and not is_paused and num_sync_clients >= screens_required

    @staticmethod
    def sendNextFrame():
        global last_frame_time
        global screens_drawn
        global framecount
        global is_paused
        global framerate
        global microseconds_per_frame

        if is_paused:
            return

        # Slow down if we've exceeded the target FPS
        delta = datetime.now() - last_frame_time
        while delta.seconds < 1 and delta.microseconds < microseconds_per_frame:
            delta = datetime.now() - last_frame_time

        screens_drawn = 0
        framecount += 1
        send_message = CMD_GO + "|%i" % framecount
        # Copy the clients so in case one disconnects during the loop
        clients = copy(MPEServer.clients)
        for client_id in clients:
            c = clients[client_id]
            if client_id in MPEServer.receiving_client_ids:
                client_messages = []
                for m in MPEServer.message_queue:
                    if len(m.to_client_ids) == 0 or client_id in m.to_client_ids:
                        client_messages.append(str(m.from_client_id) + "," + m.body)

                if len(client_messages) > 0:
                    c.sendMessage(send_message + "|" + "|".join(client_messages))
                else:
                    c.sendMessage(send_message)

        MPEServer.message_queue = []
        last_frame_time = datetime.now()

    @staticmethod
    def broadcastMessage(message, from_client_id, to_client_ids):
        #print("Broadcasting message: " + message + " to client IDs: ", to_client_ids)
        m = BroadcastMessage(message, from_client_id, to_client_ids)
        MPEServer.message_queue.append(m)
        # NOTE: If only async clients are connected, send this message now.
        # Otherwise the message wont be sent until the next render frame
        # comes across.
        if len(MPEServer.rendering_client_ids) == 0:
            MPEServer.sendNextFrame()

# Start the server
factory = Factory()
factory.protocol = MPEServer

MPEServer.clients = {}
MPEServer.rendering_client_ids = []
MPEServer.receiving_client_ids = []
MPEServer.message_queue = []

reactor.listenTCP(portnum, factory)
print("MPE Server started on port %i" % portnum)
print("Running at max %i FPS" % framerate)
if screens_required > 0:
    print("Waiting for %i clients." % screens_required)
reactor.run()

redpajama_set_name: RedPajamaGithub


text:
package tables

import (
	"bytes"
	"fmt"
	"io"
	"reflect"
	"sort"
	"text/tabwriter"

	"k8s.io/klog/v2"

	"k8s.io/kops/util/pkg/reflectutils"
)

// Table renders tables to stdout
type Table struct {
	columns map[string]*TableColumn
}

type TableColumn struct {
	Name   string
	Getter reflect.Value
}

func (c *TableColumn) getFromValue(v reflect.Value) string {
	var args []reflect.Value
	args = append(args, v)
	fvs := c.Getter.Call(args)
	fv := fvs[0]

	return reflectutils.ValueAsString(fv)
}

// AddColumn registers an available column for formatting
func (t *Table) AddColumn(name string, getter interface{}) {
	getterVal := reflect.ValueOf(getter)

	column := &TableColumn{
		Name:   name,
		Getter: getterVal,
	}
	if t.columns == nil {
		t.columns = make(map[string]*TableColumn)
	}
	t.columns[name] = column
}

type funcSorter struct {
	len  int
	less func(int, int) bool
	swap func(int, int)
}

func (f *funcSorter) Len() int {
	return f.len
}

func (f *funcSorter) Less(i, j int) bool {
	return f.less(i, j)
}

func (f *funcSorter) Swap(i, j int) {
	f.swap(i, j)
}

func SortByFunction(len int, swap func(int, int), less func(int, int) bool) {
	sort.Sort(&funcSorter{len, less, swap})
}

func (t *Table) findColumns(columnNames ...string) ([]*TableColumn, error) {
	columns := make([]*TableColumn, len(columnNames))
	for i, columnName := range columnNames {
		c := t.columns[columnName]
		if c == nil {
			return nil, fmt.Errorf("column not found: %v", columnName)
		}
		columns[i] = c
	}
	return columns, nil
}

// Render writes the items in a table, to out
func (t *Table) Render(items interface{}, out io.Writer, columnNames ...string) error {
	itemsValue := reflect.ValueOf(items)
	if itemsValue.Kind() != reflect.Slice {
		klog.Fatal("unexpected kind for items: ", itemsValue.Kind())
	}

	columns, err := t.findColumns(columnNames...)
	if err != nil {
		return err
	}

	n := itemsValue.Len()

	rows := make([][]string, n)
	for i := 0; i < n; i++ {
		row := make([]string, len(columns))
		item := itemsValue.Index(i)
		for j, column := range columns {
			row[j] = column.getFromValue(item)
		}
		rows[i] = row
	}

	SortByFunction(n, func(i, j int) {
		row := rows[i]
		rows[i] = rows[j]
		rows[j] = row
	}, func(i, j int) bool {
		l := rows[i]
		r := rows[j]

		for k := 0; k < len(columns); k++ {
			lV := l[k]
			rV := r[k]

			if lV != rV {
				return lV < rV
			}
		}
		return false
	})

	var b bytes.Buffer
	w := new(tabwriter.Writer)

	// Format in tab-separated columns with a tab stop of 8.
	w.Init(out, 0, 8, 1, '\t', tabwriter.StripEscape)

	writeHeader := true
	if writeHeader {
		for i, c := range columns {
			if i != 0 {
				b.WriteByte('\t')
			}
			b.WriteByte(tabwriter.Escape)
			b.WriteString(c.Name)
			b.WriteByte(tabwriter.Escape)
		}
		b.WriteByte('\n')

		_, err := w.Write(b.Bytes())
		if err != nil {
			return fmt.Errorf("error writing to output: %v", err)
		}
		b.Reset()
	}

	for _, row := range rows {
		for i, col := range row {
			if i != 0 {
				b.WriteByte('\t')
			}

			b.WriteByte(tabwriter.Escape)
			b.WriteString(col)
			b.WriteByte(tabwriter.Escape)
		}
		b.WriteByte('\n')

		_, err := w.Write(b.Bytes())
		if err != nil {
			return fmt.Errorf("error writing to output: %v", err)
		}
		b.Reset()
	}
	w.Flush()

	return nil
}


text:
package org.lastaflute.web.path;

import org.dbflute.optional.OptionalThing;
import org.dbflute.util.DfTypeUtil;

/**
 * @author jflute
 * @since 0.9.5 (2017/04/15 Saturday at rainbow bird rendezvous)
 */
public class ApplicationExceptionOption {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    protected OptionalThing<AppExInfoSuppressor> appExInfoSuppressor = OptionalThing.empty();

    // ===================================================================================
    //                                                                              Facade
    //                                                                              ======
    // -----------------------------------------------------
    //                                       Info Suppressor
    //                                       ---------------
    public ApplicationExceptionOption suppressInfo(AppExInfoSuppressor causeLambda) {
        if (causeLambda == null) {
            throw new IllegalArgumentException("The argument 'causeLambda' should not be null.");
        }
        this.appExInfoSuppressor = OptionalThing.of(causeLambda);
        return this;
    }

    @FunctionalInterface
    public static interface AppExInfoSuppressor {

        boolean isSuppress(RuntimeException cause);
    }

    // ===================================================================================
    //                                                                      Basic Override
    //                                                                      ==============
    @Override
    public String toString() {
        final String title = DfTypeUtil.toClassTitle(this);
        return title + ":{" + appExInfoSuppressor + "}";
    }

    // ===================================================================================
    //                                                                            Accessor
    //                                                                            ========
    // -----------------------------------------------------
    //                                       Info Suppressor
    //                                       ---------------
    public OptionalThing<AppExInfoSuppressor> getAppExInfoSuppressor() { // not null
        return appExInfoSuppressor;
    }
}


text:
- in fact, put ALL the code of debug in arucocontext
- expose debug info in arucocontext
- expose all the hardcoded parameters from AR.Detect in the debug.html
  - init gui in debug.html

# Fix pose estimation
- epnp as way to fix pose estimation issue
- https://infoscience.epfl.ch/record/160138/files/top.pdf?version=1
- standalone cpp implementation - https://github.com/artivis/epnp/blob/master/src/main.cpp

# Performances
- jsaruco use a kernel size of 2 in adaptative thresholding
  - could i reduce the resolution of the source image and use a kernel size of 1 ?
  - it would produce more fps. what the difference would be ? create errors ?
- jsaruco - adaptiveThreshold is doing it on ALL bytes - so all channel ??? check if it is correct
  - it use blackwhite image - it only needs 1 channel - 8 bits is already a lot to store blackwhite
  - this mean 4 times more work than needed
  - NOTES: unclear this is true - grayscale is packing it all in 1 channel. check it out ?
- in posit1: image difference is computed by a manathan distance. not a euclidian distance... how come ?
  - this seems to intrduce an error without need (sqrt is nothing in js)
  - ```imageDifference += Math.abs(sopImagePoints[i].x - oldSopImagePoints[i].x);```
  - ```imageDifference += Math.abs(sopImagePoints[i].y - oldSopImagePoints[i].y);```

# How to include it in AR.js
- see how to include it in ar.js
  - so basically a context and a controls
  - the source can remain the same without trouble
- how to handle all the options between the various backend

- how to handle the development ?
  - do you copy the files ?
  - do i modify the master files

- seems to have only a few modifications
  -


text:
package edu.psu.citeseerx.exec.protocol;

import java.util.*;

public class ComponentTask implements Runnable {

    protected final Task baseTask;
    protected final TaskScript parent;

    public ComponentTask(Task task, TaskScript parent) {
        this.baseTask = task;
        this.parent = parent;
    }

    //private Protocol protocol;

    public void setProtocol(Protocol protocol) {
        //this.protocol = protocol;
        baseTask.setProtocol(protocol);
    }

    private final Vector<ComponentTask> requiredDependencyList =
        new Vector<ComponentTask>();

    private final Vector<ComponentTask> optionalDependencyList =
        new Vector<ComponentTask>();

    public void addDependency(ComponentTask task, boolean optional) {
        task.addListener(this);
        if (optional) {
            if (!optionalDependencyList.contains(task)) {
                optionalDependencyList.add(task);
            }
        } else {
            System.out.println("adding required");
            if (!requiredDependencyList.contains(task)) {
                requiredDependencyList.add(task);
            }
        }
        System.out.println("added depency for component "+baseTask.name+
                ": "+task.baseTask.name);
        System.out.println(baseTask.name+" DEPSIZE: "+requiredDependencyList.size());

    }  //- addDependency

    private final Vector<Object> listeners =
        new Vector<Object>();

    public void addListener(Object listener) {
        if (!listeners.contains(listener))
            listeners.add(listener);
    }

    private void notifyCompleted() {
        System.out.println("notify completed");
        synchronized(listeners) {
            for (Iterator<Object> it = listeners.iterator();
                    it.hasNext(); ) {
                System.out.println("notifying");
                Object lock = it.next();
                synchronized(lock) {
                    lock.notifyAll();
                }
            }
        }

    }  //- notifyCompleted

    /*
    private void notifyFailed() {
        synchronized(listeners) {
            for (Iterator<ComponentTaskListener> it = listeners.iterator();
                    it.hasNext(); ) {
                it.next().taskFailed(this);
            }
        }

    }  //- notifyFailed
    */

    private boolean taskComplete = false;

    public boolean isComplete() {
        return taskComplete;
    }

    private boolean taskError = false;

    public boolean completedOK() {
        return taskError;
    }

    //public final Object notificationLock = new Object();

    public void run() {
        System.out.println(baseTask.name+" CP1");
        synchronized(this) {
            System.out.println(baseTask.name+" CP2");
            while(dependenciesNotMet()) {
                System.out.println(baseTask.name+": waiting for results");
                try {
                    wait();
                } catch (InterruptedException e) {}
                System.out.println(baseTask.name+": got results");
            }
        }
        System.out.println(baseTask.name+" CP3");

        boolean dependenciesOK = true;
        synchronized(requiredDependencyList) {
            for (Iterator<ComponentTask> it =
                requiredDependencyList.iterator(); it.hasNext(); ) {
                if (!it.next().completedOK()) {
                    dependenciesOK = false;
                    break;
                }
            }
        }
        System.out.println(baseTask.name+" CP4");

        if (dependenciesOK) {
            if (!baseTask.execute()) {
                taskError = false;
            } else {
                taskError = true;
            }
        }

        System.out.println(baseTask.name+" deps ok? " + dependenciesOK);

        taskComplete = true;
        notifyCompleted();

    }  //- run

    private boolean dependenciesNotMet() {
        System.out.println(baseTask.name+" CP1.1");
        System.out.println(baseTask.name+" DEPSIZE: "+requiredDependencyList.size());

        synchronized(requiredDependencyList) {
            for (Iterator<ComponentTask> it = requiredDependencyList.iterator();
                    it.hasNext(); ) {
                ComponentTask task = it.next();
                System.out.println(baseTask.name+" DEPSTATUS: "+task.baseTask.name+" "+task.isComplete());
                if (!task.isComplete()) {
                    return true;
                }
            }
        }
        System.out.println(baseTask.name+" CP1.2");

        synchronized(optionalDependencyList) {
            for (Iterator<ComponentTask> it = optionalDependencyList.iterator();
                    it.hasNext(); ) {
                if (!it.next().isComplete()) {
                    return true;
                }
            }
        }
        System.out.println(baseTask.name+" CP1.3");

        return false;

    }  //- dependenciesNotMet

    public ComponentTask newInstance(TaskScript parent) {
        return new ComponentTask(baseTask.newInstance(), parent);
    }

    public void reset() {
        taskComplete = false;
    }

    /*
    public void taskCompleted(ComponentTask task) {
        //dependencyList.remove(task);
    }

    public void taskFailed(ComponentTask task) {
        taskComplete = true;
        notifyFailed();
    }
    */

}  //- class ComponentTask


text:
import logging

logger = logging.getLogger('nppm')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('[%(levelname)s]: %(message)s'))
logger.addHandler(handler)

module.exports = logger


text:
package com.zkjd.ehua.system.visit.dao;

import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.zkjd.ehua.system.visit.entity.VisitLog;

/**
 * 访问日志DAO接口
 * @author yangsong
 * @version 2017-03-14
 */
@MyBatisDao
public interface VisitLogDao extends CrudDao<VisitLog> {

}


text:
#include <pumex/Surface.h>
#include <tbb/tbb.h>
#include <pumex/Viewer.h>
#include <pumex/Window.h>
#include <pumex/PhysicalDevice.h>
#include <pumex/RenderPass.h>
#include <pumex/RenderVisitors.h>
#include <pumex/FrameBuffer.h>
#include <pumex/RenderGraphExecution.h>
#include <pumex/MemoryImage.h>
#include <pumex/utils/Log.h>
#include <pumex/TimeStatistics.h>

using namespace pumex;

SurfaceTraits::SurfaceTraits(const ResourceDefinition& sdef, uint32_t sic, VkColorSpaceKHR sics, VkPresentModeKHR spm, VkSurfaceTransformFlagBitsKHR pt, VkCompositeAlphaFlagBitsKHR ca)
  : swapChainDefinition{ sdef }, minSwapChainImageCount{ sic }, swapChainImageColorSpace{ sics }, swapchainPresentMode{ spm }, preTransform{ pt }, compositeAlpha{ ca }
{
}

const std::unordered_map<std::string, VkPresentModeKHR> Surface::nameToPresentationModes
{
  { "immediate",    VK_PRESENT_MODE_IMMEDIATE_KHR },
  { "mailbox",      VK_PRESENT_MODE_MAILBOX_KHR },
  { "fifo",         VK_PRESENT_MODE_FIFO_KHR },
  { "fifo_relaxed", VK_PRESENT_MODE_FIFO_RELAXED_KHR }
};

const std::map<VkPresentModeKHR, std::string> Surface::presentationModeNames
{
  { VK_PRESENT_MODE_IMMEDIATE_KHR,    "immediate" },
  { VK_PRESENT_MODE_MAILBOX_KHR,      "mailbox" },
  { VK_PRESENT_MODE_FIFO_KHR,         "fifo" },
  { VK_PRESENT_MODE_FIFO_RELAXED_KHR, "fifo_relaxed" }
};

const std::map<VkPresentModeKHR, std::vector<VkPresentModeKHR>> Surface::replacementModes
{
  { VK_PRESENT_MODE_IMMEDIATE_KHR,{ VK_PRESENT_MODE_MAILBOX_KHR , VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR } },
  { VK_PRESENT_MODE_MAILBOX_KHR,{ VK_PRESENT_MODE_IMMEDIATE_KHR , VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR } },
  { VK_PRESENT_MODE_FIFO_KHR,{ VK_PRESENT_MODE_FIFO_RELAXED_KHR , VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR } },
  { VK_PRESENT_MODE_FIFO_RELAXED_KHR,{ VK_PRESENT_MODE_FIFO_KHR , VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR } }
};

Surface::Surface(std::shared_ptr<Device> d, std::shared_ptr<Window> w, VkSurfaceKHR s, const SurfaceTraits& st)
  : device{ d }, window{ w }, surface{ s }, surfaceTraits{ st }
{
  timeStatistics      = std::make_unique<TimeStatistics>(32);
  timeStatistics->registerGroup(TSS_GROUP_BASIC,             L"Surface operations");
  timeStatistics->registerGroup(TSS_GROUP_EVENTS,            L"Surface events");
  timeStatistics->registerGroup(TSS_GROUP_SECONDARY_BUFFERS, L"Secondary buffers");

  timeStatistics->registerChannel(TSS_CHANNEL_BEGINFRAME,                   TSS_GROUP_BASIC,             L"beginFrame",                   glm::vec4(0.4f, 0.4f, 0.4f, 0.5f));
  timeStatistics->registerChannel(TSS_CHANNEL_EVENTSURFACERENDERSTART,      TSS_GROUP_EVENTS,            L"eventSurfaceRenderStart",      glm::vec4(0.8f, 0.8f, 0.1f, 0.5f));
  timeStatistics->registerChannel(TSS_CHANNEL_VALIDATERENDERGRAPH,          TSS_GROUP_BASIC,             L"validateRenderGraphs",         glm::vec4(0.1f, 0.1f, 0.1f, 0.5f));
  timeStatistics->registerChannel(TSS_CHANNEL_VALIDATESECONDARYNODES,       TSS_GROUP_SECONDARY_BUFFERS, L"validateSecondaryNodes",       glm::vec4(0.0f, 0.0f, 0.0f, 0.5f));
  timeStatistics->registerChannel(TSS_CHANNEL_VALIDATESECONDARYDESCRIPTORS, TSS_GROUP_SECONDARY_BUFFERS, L"validateSecondaryDescriptors", glm::vec4(1.0f, 1.0f, 0.0f, 0.5f));
  timeStatistics->registerChannel(TSS_CHANNEL_BUILDSECONDARYCOMMANDBUFFERS, TSS_GROUP_SECONDARY_BUFFERS, L"buildSecondaryCommandBuffers", glm::vec4(1.0f, 0.0f, 0.0f, 0.5f));
  timeStatistics->registerChannel(TSS_CHANNEL_DRAW,                         TSS_GROUP_BASIC,             L"draw",                         glm::vec4(0.9f, 0.9f, 0.9f, 0.5f));
  timeStatistics->registerChannel(TSS_CHANNEL_ENDFRAME,                     TSS_GROUP_BASIC,             L"endFrame",                     glm::vec4(0.1f, 0.1f, 0.1f, 0.5f));
  timeStatistics->registerChannel(TSS_CHANNEL_EVENTSURFACERENDERFINISH,     TSS_GROUP_EVENTS,            L"eventSurfaceRenderFinish",     glm::vec4(0.8f, 0.8f, 0.1f, 0.5f));

  timeStatistics->setFlags(TSS_STAT_BASIC | TSS_STAT_BUFFERS | TSS_STAT_EVENTS);
}

Surface::~Surface()
{
  cleanup();
}

// called before realization - collects queue traits for all render graphs
void Surface::collectQueueTraits()
{
  auto v = viewer.lock();
  for (auto& rgData : renderGraphData)
  {
    auto currentSize = queueTraits.size();
    std::string& rgName = std::get<0>(rgData);
    auto qTraits = v->getRenderGraphQueueTraits(rgName);
    auto qit = renderGraphQueueIndices.insert({ rgName, std::vector<uint32_t>() }).first;
    for (uint32_t i=0; i<qTraits.size(); ++i)
    {
      switch(qTraits[i].assignment)
      {
      case qaExclusive:
      {
        qit->second.push_back(queueTraits.size());
        queueTraits.push_back(qTraits[i]);
        break;
      }
      case qaShared:
      {
        // Queues may be shared between different render graphs. Queue sharing inside single render graph makes no sense ( possible synchronization deadlocks,
        // when two command sequences designed to work in parallel will be spawned serially )
        auto last = begin(queueTraits) + currentSize;
        auto it = std::find(begin(queueTraits), last , qTraits[i]);
        if (it == last)
        {
          qit->second.push_back(queueTraits.size());
          queueTraits.push_back(qTraits[i]);
        }
        else
          qit->second.push_back(std::distance(begin(queueTraits), it));
        break;
      }
      default:
        break;
      }
    }
  }
  auto d = device.lock();
  for( auto& qt : queueTraits )
    d->addRequestedQueue(qt);
}

void Surface::realize()
{
  if (isRealized())
    return;

  auto deviceSh          = device.lock();
  VkPhysicalDevice phDev = deviceSh->physical.lock()->physicalDevice;
  VkDevice vkDevice      = deviceSh->device;

  // collect surface properties
  VK_CHECK_LOG_THROW( vkGetPhysicalDeviceSurfaceCapabilitiesKHR(phDev, surface, &surfaceCapabilities), "failed vkGetPhysicalDeviceSurfaceCapabilitiesKHR for surface " << getID() );

  // collect available presentation modes
  uint32_t presentModeCount;
  VK_CHECK_LOG_THROW( vkGetPhysicalDeviceSurfacePresentModesKHR(phDev, surface, &presentModeCount, nullptr), "Could not get present modes for surface " << getID());
  CHECK_LOG_THROW( presentModeCount == 0, "No present modes defined for this surface" );
  presentModes.resize(presentModeCount);
  VK_CHECK_LOG_THROW( vkGetPhysicalDeviceSurfacePresentModesKHR(phDev, surface, &presentModeCount, presentModes.data()), "Could not get present modes " << presentModeCount << " for surface " << getID());

  // check if presentation mode from surface traits is available
  auto presentIt = std::find(begin(presentModes), end(presentModes), surfaceTraits.swapchainPresentMode);
  if (presentIt == end(presentModes))
  {
    // presentation mode from surface traits is not available. Choose the most appropriate one and inform user about the change

    auto prefIt = replacementModes.find(surfaceTraits.swapchainPresentMode);
    CHECK_LOG_THROW(prefIt == end(replacementModes), "Presentation mode <" <<surfaceTraits.swapchainPresentMode << "> not available on GPU and not recognized by library");
    VkPresentModeKHR finalPresentationMode = surfaceTraits.swapchainPresentMode;
    for (auto it = begin(prefIt->second); it != end(prefIt->second); ++it)
    {
      auto secondChoiceIt = std::find(begin(presentModes), end(presentModes), *it);
      if (secondChoiceIt == end(presentModes))
        continue;
      finalPresentationMode = *it;
      break;
    }
    CHECK_LOG_THROW(finalPresentationMode == surfaceTraits.swapchainPresentMode, "Presentation mode <" << surfaceTraits.swapchainPresentMode << "> not available on GPU. Library cannot find the replacement");

    LOG_WARNING << "Warning : <" << presentationModeNames.at(surfaceTraits.swapchainPresentMode) <<"> presentation mode  not available. Library will use <" << presentationModeNames.at(finalPresentationMode) << "> presentation mode instead." << std::endl ;
    surfaceTraits.swapchainPresentMode = finalPresentationMode;
  }

  uint32_t surfaceFormatCount;
  VK_CHECK_LOG_THROW( vkGetPhysicalDeviceSurfaceFormatsKHR(phDev, surface, &surfaceFormatCount, nullptr), "Could not get surface formats for surface " << getID());
  CHECK_LOG_THROW(surfaceFormatCount == 0, "No surface formats defined for surface " << getID());
  surfaceFormats.resize(surfaceFormatCount);
  VK_CHECK_LOG_THROW( vkGetPhysicalDeviceSurfaceFormatsKHR(phDev, surface, &surfaceFormatCount, surfaceFormats.data()), "Could not get surface formats " << surfaceFormatCount << " for surface " << getID());

  uint32_t queueFamilyCount = deviceSh->physical.lock()->queueFamilyProperties.size();
  supportsPresent.resize(queueFamilyCount);
  for (uint32_t i = 0; i < queueFamilyCount; i++)
    VK_CHECK_LOG_THROW(vkGetPhysicalDeviceSurfaceSupportKHR(phDev, i, surface, &supportsPresent[i]), "failed vkGetPhysicalDeviceSurfaceSupportKHR for family " << i );

  CHECK_LOG_THROW(renderGraphData.empty(), "There are no render graphs defined for surface " << getID());

  // get all queues and create command pools and entry semaphores for them
  for (uint32_t i=0; i<queueTraits.size(); ++i )
  {
    std::shared_ptr<Queue> queue = deviceSh->getQueue(queueTraits[i], true);
    CHECK_LOG_THROW(queue.get() == nullptr, "Cannot get the queue for this surface : " << i);
    CHECK_LOG_THROW(supportsPresent[queue->familyIndex] == VK_FALSE, "Support not present for(device,surface,familyIndex) : " << queue->familyIndex);
    queues.push_back(queue);

    // first queue able to perform graphics operations will become presentation queue
    if (presentationQueueIndex == -1 && ((queueTraits[i].mustHave & VK_QUEUE_GRAPHICS_BIT) != 0))
      presentationQueueIndex = i;

    auto commandPool = std::make_shared<CommandPool>(queue->familyIndex);
    commandPool->validate(deviceSh.get());
    commandPools.push_back(commandPool);

  }

  recreateSwapChain();
  resized = true;

  // Create synchronization objects
  VkSemaphoreCreateInfo semaphoreCreateInfo{};
    semaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  for (uint32_t i = 0; i < renderGraphData.size(); ++i)
  {

    // for all command sequences - figure out which queues they use, add command buffers for them
    auto renderGraphName = std::get<0>(renderGraphData[i]);
    auto queueIndices = renderGraphQueueIndices.find(renderGraphName);
    CHECK_LOG_THROW(queueIndices == end(renderGraphQueueIndices), "Missing renderGraphQueueIndices for render graph : " << renderGraphName);

    auto pcbit = primaryCommandBuffers.insert({ renderGraphName,std::vector<std::shared_ptr<CommandBuffer>>() }).first;
    auto qcbit = queueSubmissionCompletedSemaphores.insert({ renderGraphName, std::vector<VkSemaphore>() }).first;
    for (auto& queueIndex : queueIndices->second)
    {
      auto commandBuffer = std::make_shared<CommandBuffer>(VK_COMMAND_BUFFER_LEVEL_PRIMARY, deviceSh.get(), commandPools[queueIndex], swapChainImageCount);
      pcbit->second.push_back(commandBuffer);

      VkSemaphore semaphore;
      VK_CHECK_LOG_THROW(vkCreateSemaphore(vkDevice, &semaphoreCreateInfo, nullptr, &semaphore), "Could not create render complete semaphore");
      qcbit->second.push_back(semaphore);
    }
    // register time statistics for all render graphs
    for (uint32_t j = 0; j < queueIndices->second.size(); ++j)
    {
      if (timeStatistics->hasGroup(TSS_GROUP_PRIMARY_BUFFERS + i))
        continue;
      std::wstringstream ostr;
      std::wstring rgName;
      rgName.assign(begin(renderGraphName), end(renderGraphName));
      ostr << rgName << " (" << queueIndices->second[j] << ")";
      timeStatistics->registerGroup(TSS_GROUP_PRIMARY_BUFFERS + i, L"Primary buffers " + ostr.str());

      timeStatistics->registerChannel(20 + 10 * i + 0, TSS_GROUP_PRIMARY_BUFFERS + i, L"validatePrimaryNodes " + ostr.str(), glm::vec4(0.0f, 0.0f, 0.0f, 0.5f));
      timeStatistics->registerChannel(20 + 10 * i + 1, TSS_GROUP_PRIMARY_BUFFERS + i, L"validatePrimaryDescriptors " + ostr.str(), glm::vec4(1.0f, 1.0f, 0.0f, 0.5f));
      timeStatistics->registerChannel(20 + 10 * i + 2, TSS_GROUP_PRIMARY_BUFFERS + i, L"buildPrimaryCommandBuffer " + ostr.str(), glm::vec4(1.0f, 0.0f, 0.0f, 0.5f));
    }
  }

  // define basic command buffers required to render a frame
  presentCommandBuffer = std::make_shared<CommandBuffer>(VK_COMMAND_BUFFER_LEVEL_PRIMARY, deviceSh.get(), commandPools[presentationQueueIndex], swapChainImageCount);

  // create all semaphores required to render a frame
  VK_CHECK_LOG_THROW( vkCreateSemaphore(vkDevice, &semaphoreCreateInfo, nullptr, &imageAvailableSemaphore), "Could not create image available semaphore");
  VK_CHECK_LOG_THROW( vkCreateSemaphore(vkDevice, &semaphoreCreateInfo, nullptr, &renderFinishedSemaphore), "Could not create image available semaphore");

  VkFenceCreateInfo fenceCreateInfo{};
    fenceCreateInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
    fenceCreateInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  waitFences.resize(swapChainImageCount);
  for (auto& fence : waitFences)
    VK_CHECK_LOG_THROW(vkCreateFence(vkDevice, &fenceCreateInfo, nullptr, &fence), "Could not create a surface wait fence");

  realized = true;
}

void Surface::cleanup()
{
  VkDevice dev = device.lock()->device;
  eventSurfaceRenderStart  = nullptr;
  eventSurfaceRenderFinish = nullptr;
  if (swapChain != VK_NULL_HANDLE)
  {
    swapChainImages.clear();
    vkDestroySwapchainKHR(dev, swapChain, nullptr);
    swapChain = VK_NULL_HANDLE;
  }
  auto v = viewer.lock();
  if (surface != VK_NULL_HANDLE)
  {
    for (auto& rgData : renderGraphData)
    {
      auto executable = v->getRenderGraphExecutable(std::get<0>(rgData));
      if(executable == nullptr)
        continue;
      for (auto& frameBuffer : executable->frameBuffers)
        frameBuffer->reset(this);
    }
    renderGraphData.clear();
    for (auto& fence : waitFences)
      vkDestroyFence(dev, fence, nullptr);
    waitFences.clear();

    for (auto& semaphores : queueSubmissionCompletedSemaphores)
      for (auto sem : semaphores.second)
        vkDestroySemaphore(dev, sem, nullptr);
    queueSubmissionCompletedSemaphores.clear();
    if (renderFinishedSemaphore != VK_NULL_HANDLE)
    {
      vkDestroySemaphore(dev, renderFinishedSemaphore, nullptr);
      renderFinishedSemaphore = VK_NULL_HANDLE;
    }
    if (imageAvailableSemaphore != VK_NULL_HANDLE)
    {
      vkDestroySemaphore(dev, imageAvailableSemaphore, nullptr);
      imageAvailableSemaphore = VK_NULL_HANDLE;
    }
    primaryCommandBuffers.clear();
    presentCommandBuffer = nullptr;
    commandPools.clear();
    for(auto q : queues )
      device.lock()->releaseQueue(q);
    queues.clear();
    if(surfaceTraits.destroySurfaceOnCleanup)
      vkDestroySurfaceKHR(v->getInstance(), surface, nullptr);
    surface = VK_NULL_HANDLE;
  }
}

void Surface::recreateSwapChain()
{
  auto deviceSh = device.lock();
  VkDevice vkDevice = deviceSh->device;
  VkPhysicalDevice phDev = deviceSh->physical.lock()->physicalDevice;

  vkDeviceWaitIdle(vkDevice);

  VkSwapchainKHR oldSwapChain = swapChain;

  VK_CHECK_LOG_THROW(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(phDev, surface, &surfaceCapabilities), "failed vkGetPhysicalDeviceSurfaceCapabilitiesKHR");
  swapChainSize = surfaceCapabilities.currentExtent;
//  LOG_ERROR << "cs " << swapChainSize.width << "x" << swapChainSize.height << std::endl;

  VkSwapchainCreateInfoKHR swapchainCreateInfo{};
    swapchainCreateInfo.sType                 = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
    swapchainCreateInfo.surface               = surface;
    swapchainCreateInfo.minImageCount         = surfaceTraits.minSwapChainImageCount;
    swapchainCreateInfo.imageFormat           = surfaceTraits.swapChainDefinition.attachment.format;
    swapchainCreateInfo.imageColorSpace       = surfaceTraits.swapChainImageColorSpace;
    swapchainCreateInfo.imageExtent           = swapChainSize;
    swapchainCreateInfo.imageArrayLayers      = surfaceTraits.swapChainDefinition.attachment.attachmentSize.arrayLayers;
    swapchainCreateInfo.imageUsage            = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
    swapchainCreateInfo.imageSharingMode      = VK_SHARING_MODE_EXCLUSIVE;
    swapchainCreateInfo.queueFamilyIndexCount = 0;
    swapchainCreateInfo.pQueueFamilyIndices   = nullptr;
    swapchainCreateInfo.preTransform          = surfaceTraits.preTransform;
    swapchainCreateInfo.compositeAlpha        = surfaceTraits.compositeAlpha;
    swapchainCreateInfo.presentMode           = surfaceTraits.swapchainPresentMode;
    swapchainCreateInfo.clipped               = VK_TRUE;
    swapchainCreateInfo.oldSwapchain          = oldSwapChain;
  VK_CHECK_LOG_THROW( vkCreateSwapchainKHR(vkDevice, &swapchainCreateInfo, nullptr, &swapChain), "Could not create swapchain" );

  // remove old swap chain and all images
  if (oldSwapChain != VK_NULL_HANDLE)
  {
    swapChainImages.clear();
    vkDestroySwapchainKHR(vkDevice, oldSwapChain, nullptr);
  }

  // collect new swap chain images
  uint32_t newImageCount;
  VK_CHECK_LOG_THROW(vkGetSwapchainImagesKHR(vkDevice, swapChain, &newImageCount, nullptr), "Could not get swapchain images");
  std::vector<VkImage> images(newImageCount);
  VK_CHECK_LOG_THROW(vkGetSwapchainImagesKHR(vkDevice, swapChain, &newImageCount, images.data()), "Could not get swapchain images " << newImageCount);
  for (uint32_t i = 0; i < newImageCount; i++)
    swapChainImages.push_back(std::make_shared<Image>(deviceSh.get(), images[i], surfaceTraits.swapChainDefinition.attachment.format, surfaceTraits.swapChainDefinition.attachment.attachmentSize));

  CHECK_LOG_THROW( swapChainImageCount != 0 && newImageCount != swapChainImageCount, "Cannot change swapChainImageCount while working" );
  swapChainImageCount = newImageCount;

  if(presentCommandBuffer != nullptr)
    presentCommandBuffer->invalidate(std::numeric_limits<uint32_t>::max());
}

void Surface::beginFrame()
{
  actions.performActions();
  auto deviceSh = device.lock();

  VkResult result = vkAcquireNextImageKHR(deviceSh->device, swapChain, UINT64_MAX, imageAvailableSemaphore, VK_NULL_HANDLE, &swapChainImageIndex);
  if ((result == VK_ERROR_OUT_OF_DATE_KHR) || (result == VK_SUBOPTIMAL_KHR))
  {
    // recreate swapchain
    recreateSwapChain();
    resized = true;
    // try to acquire images again - throw error for every reason other than VK_SUCCESS
    result = vkAcquireNextImageKHR(deviceSh->device, swapChain, UINT64_MAX, imageAvailableSemaphore, (VkFence)nullptr, &swapChainImageIndex);
  }
  VK_CHECK_LOG_THROW(result, "failed vkAcquireNextImageKHR");
  VK_CHECK_LOG_THROW(vkWaitForFences(deviceSh->device, 1, &waitFences[swapChainImageIndex], VK_TRUE, UINT64_MAX), "failed to wait for fence");
  VK_CHECK_LOG_THROW(vkResetFences(deviceSh->device, 1, &waitFences[swapChainImageIndex]), "failed to reset a fence");
}

void Surface::validateRenderGraphs()
{
  RenderContext renderContext(this, presentationQueueIndex);
  auto v = viewer.lock();
  if (resized)
  {
    for (auto& rgData : renderGraphData)
    {
      auto renderGraphName = std::get<0>(rgData);
      auto executable = v->getRenderGraphExecutable(renderGraphName);
      if(executable == nullptr)
        continue;
      executable->resizeImages(renderContext, swapChainImages);
      for (auto& frameBuffer : executable->frameBuffers)
      {
        auto rp = frameBuffer->getRenderPass().lock();
        rp->invalidate(renderContext);
        frameBuffer->invalidate(renderContext);
      }
    }
    resized = false;
  }

  for (auto& rgData : renderGraphData)
  {
    auto renderGraphName = std::get<0>(rgData);
    auto executable = v->getRenderGraphExecutable(renderGraphName);
    if(executable == nullptr)
      continue;
    renderContext.setRenderGraphExecutable(executable);
    for (auto& frameBuffer : executable->frameBuffers)
      frameBuffer->validate(renderContext);
    // create/update render passes and compute passes for current surface
    for (auto& commandSeq : executable->commands)
      for (auto& command : commandSeq)
        command->validate(renderContext);
  }

  // find last layout used by swapchain
  VkImageLayout swapChainImageFinalLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  for (auto& rgData : renderGraphData)
  {
    auto renderGraphName = std::get<0>(rgData);
    auto executable = v->getRenderGraphExecutable(renderGraphName);
    if(executable == nullptr)
      continue;
    for (auto& memImage : executable->memoryImages)
    {
      auto ait = executable->imageInfo.find(memImage.first);
      if (ait == end(executable->imageInfo))
        continue;
      // if it's swapchain image - find last layout that is not VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR nor VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
      if (ait->second.isSwapchainImage)
      {
        // FIXME : We are looking only for one mipmap and one layer. Is it OK ?
        auto allLayouts = executable->getImageLayouts(memImage.first, ImageSubresourceRange());
        auto lit = std::find_if(rbegin(allLayouts), rend(allLayouts), [](const VkImageLayout& layout) { return layout != VK_IMAGE_LAYOUT_PRESENT_SRC_KHR && layout != VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR; });
        if (lit != rend(allLayouts))
          swapChainImageFinalLayout = *lit;
      }
    }
  }
  presentCommandBuffer->setActiveIndex(swapChainImageIndex);
  if (!presentCommandBuffer->isValid())
  {
    presentCommandBuffer->cmdBegin();

    PipelineBarrier presentBarrier
    (
      VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
      VK_ACCESS_MEMORY_READ_BIT,
      VK_QUEUE_FAMILY_IGNORED,
      VK_QUEUE_FAMILY_IGNORED,
      swapChainImages[swapChainImageIndex]->getHandleImage(),
      { VK_IMAGE_ASPECT_COLOR_BIT, 0, VK_REMAINING_MIP_LEVELS, 0, VK_REMAINING_ARRAY_LAYERS },
      swapChainImageFinalLayout,
      VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
    );
    presentCommandBuffer->cmdPipelineBarrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_DEPENDENCY_BY_REGION_BIT, presentBarrier);
    presentCommandBuffer->cmdEnd();
  }
}

void Surface::setCommandBufferIndices()
{
  for (auto& pcb : primaryCommandBuffers)
    for (auto& pcbx : pcb.second)
      pcbx->setActiveIndex(swapChainImageIndex);

  RenderContext renderContext(this, presentationQueueIndex);
  for (uint32_t i = 0; i < secondaryCommandBufferNodes.size(); ++i)
  {
    auto commandBuffer = secondaryCommandBufferNodes[i]->getSecondaryBuffer(renderContext);
    CHECK_LOG_THROW(commandBuffer == nullptr, "Secondary buffer not defined for node " << secondaryCommandBufferNodes[i]->getName());
    commandBuffer->setActiveIndex(swapChainImageIndex);
  }
}

void Surface::validatePrimaryNodes(uint32_t queueIndex)
{
  ValidateNodeVisitor validateNodeVisitor(RenderContext(this, presentationQueueIndex), true);
  auto v = viewer.lock();
  for (auto& rgData : renderGraphData)
  {
    auto renderGraphName = std::get<0>(rgData);
    auto executable = v->getRenderGraphExecutable(renderGraphName);
    if(executable == nullptr)
      continue;
    validateNodeVisitor.renderContext.setRenderGraphExecutable(executable);
    auto qit = renderGraphQueueIndices.find(renderGraphName);
    for (uint32_t i=0; i<qit->second.size(); ++i)
    {
      if (qit->second[i] == queueIndex)
      {
        for (auto& command : executable->commands[i])
          command->applyRenderContextVisitor(validateNodeVisitor);
      }
    }
  }
}

void Surface::validatePrimaryDescriptors(uint32_t queueIndex)
{
  ValidateDescriptorVisitor validateDescriptorVisitor(RenderContext(this, presentationQueueIndex), true);
  auto v = viewer.lock();
  for (auto& rgData : renderGraphData)
  {
    auto renderGraphName = std::get<0>(rgData);
    auto executable = v->getRenderGraphExecutable(renderGraphName);
    if(executable == nullptr)
      continue;
    validateDescriptorVisitor.renderContext.setRenderGraphExecutable(executable);
    auto qit = renderGraphQueueIndices.find(renderGraphName);
    for (uint32_t i = 0; i<qit->second.size(); ++i)
    {
      if (qit->second[i] == queueIndex)
      {
        for (auto& command : executable->commands[i])
          command->applyRenderContextVisitor(validateDescriptorVisitor);
      }
    }
  }
}

void Surface::buildPrimaryCommandBuffer(uint32_t queueIndex)
{
  RenderContext renderContext(this, presentationQueueIndex);
  auto v = viewer.lock();
  for (auto& rgData : renderGraphData)
  {
    auto renderGraphName = std::get<0>(rgData);
    auto executable      = v->getRenderGraphExecutable(renderGraphName);
    if(executable == nullptr)
      continue;
    auto qit             = renderGraphQueueIndices.find(renderGraphName);
    auto pcbit           = primaryCommandBuffers.find(renderGraphName);
    renderContext.setRenderGraphExecutable(executable);
    for (uint32_t i = 0; i<qit->second.size(); ++i)
    {
      if (qit->second[i] == queueIndex)
      {
        pcbit->second[i]->setActiveIndex(swapChainImageIndex);
        pcbit->second[i]->cmdBegin();
        BuildCommandBufferVisitor cbVisitor(renderContext, pcbit->second[i].get(), true);
        for (auto& command : executable->commands[i])
          command->buildCommandBuffer(cbVisitor);
        pcbit->second[i]->cmdEnd();
      }
    }
  }
}

void Surface::validateSecondaryNodes()
{
  // find all secondary buffer nodes and place its data in a Surface owned vector ( is it thread friendly ?)
  FindSecondaryCommandBuffersVisitor fscbVisitor(RenderContext(this, presentationQueueIndex));
  auto v = viewer.lock();
  for (auto& rgData : renderGraphData)
  {
    auto renderGraphName = std::get<0>(rgData);
    auto executable      = v->getRenderGraphExecutable(renderGraphName);
    if(executable == nullptr)
      continue;
    fscbVisitor.renderContext.setRenderGraphExecutable(executable);
    for ( auto& commandSeq : executable->commands)
      for (auto& command : commandSeq)
        command->applyRenderContextVisitor(fscbVisitor);
  }

  secondaryCommandBufferNodes        = fscbVisitor.nodes;
  secondaryCommandBufferRenderPasses = fscbVisitor.renderPasses;
  secondaryCommandBufferSubPasses    = fscbVisitor.subPasses;

  tbb::parallel_for
  (
    tbb::blocked_range<size_t>(0, secondaryCommandBufferNodes.size()),
      [&](const tbb::blocked_range<size_t>& r)
      {
        for (size_t i = r.begin(); i != r.end(); ++i)
        {
          RenderContext renderContext(this, presentationQueueIndex);
          renderContext.commandPool = secondaryCommandBufferNodes[i]->getSecondaryCommandPool(renderContext);
          ValidateNodeVisitor validateNodeVisitor(renderContext, false);
          secondaryCommandBufferNodes[i]->accept(validateNodeVisitor);
        }
      }
  );
}

void Surface::validateSecondaryDescriptors()
{
  tbb::parallel_for
  (
    tbb::blocked_range<size_t>(0, secondaryCommandBufferNodes.size()),
      [&](const tbb::blocked_range<size_t>& r)
      {
        for (size_t i = r.begin(); i != r.end(); ++i)
        {
          RenderContext renderContext(this, presentationQueueIndex);
          renderContext.commandPool = secondaryCommandBufferNodes[i]->getSecondaryCommandPool(renderContext);
          ValidateDescriptorVisitor validateDescriptorVisitor(renderContext, false);
          secondaryCommandBufferNodes[i]->accept(validateDescriptorVisitor);
        }
      }
  );
}

void Surface::buildSecondaryCommandBuffers()
{
  tbb::parallel_for
  (
    tbb::blocked_range<size_t>(0, secondaryCommandBufferNodes.size()),
      [&](const tbb::blocked_range<size_t>& r)
      {
        for (size_t i = r.begin(); i != r.end(); ++i)
        {
          RenderContext renderContext(this, presentationQueueIndex);
          auto commandBuffer = secondaryCommandBufferNodes[i]->getSecondaryBuffer(renderContext);
          CHECK_LOG_THROW(commandBuffer == nullptr, "Secondary buffer not defined for node " << secondaryCommandBufferNodes[i]->getName());
          commandBuffer->setActiveIndex(swapChainImageIndex);
          if (!commandBuffer->isValid())
          {
            // The problem is that above defined render context needs to use elements defined up the tree ( currentPipelineLayout, currentAssetBuffer and currentRenderMask )
            // We have to find that data
            CompleteRenderContextVisitor crcVisitor(renderContext);
            secondaryCommandBufferNodes[i]->accept(crcVisitor);

            // Now we are ready to build secondary command buffer
            BuildCommandBufferVisitor cbVisitor(renderContext, commandBuffer.get(), false);
            VkCommandBufferUsageFlags cbUsageFlags = 0;
            if (secondaryCommandBufferNodes[i]->getNumParents() > 1)
              cbUsageFlags |= VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
            if (secondaryCommandBufferRenderPasses[i] != VK_NULL_HANDLE)
              cbUsageFlags |= VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT;
            commandBuffer->cmdBegin(cbUsageFlags, secondaryCommandBufferRenderPasses[i], secondaryCommandBufferSubPasses[i]);
            secondaryCommandBufferNodes[i]->accept(cbVisitor);
            commandBuffer->cmdEnd();
          }
        }
      }
  );
}

void Surface::draw()
{
  std::vector<std::vector<CommandBuffer*>> commandBuffersToSubmit;
  std::vector<std::vector<VkSemaphore>>    semaphoresToSubmit;
  std::vector<VkSemaphore>                 submissionCompletedSemaphores;
  auto v = viewer.lock();
  // for each queue - collect all primary command buffers and "submission completed" semaphores in appropriate order
  for (uint32_t queueIndex = 0; queueIndex < queues.size(); ++queueIndex)
  {
    commandBuffersToSubmit.push_back(std::vector<CommandBuffer*>());
    semaphoresToSubmit.push_back(std::vector<VkSemaphore>());
    for (uint32_t rgIndex = 0; rgIndex<renderGraphData.size(); ++rgIndex)
    {
      auto renderGraphName = std::get<0>(renderGraphData[rgIndex]);
      auto executable = v->getRenderGraphExecutable(renderGraphName);
      if(executable == nullptr)
        continue;
      auto qit = renderGraphQueueIndices.find(renderGraphName);
      auto pcbit = primaryCommandBuffers.find(renderGraphName);
      auto qcbit = queueSubmissionCompletedSemaphores.find(renderGraphName);
      for (uint32_t i = 0; i < qit->second.size(); ++i)
      {
        if (qit->second[i] == queueIndex)
        {
          commandBuffersToSubmit.back().push_back(pcbit->second[i].get());
          semaphoresToSubmit.back().push_back(qcbit->second[i]);
          submissionCompletedSemaphores.push_back(qcbit->second[i]);
        }
      }
    }
  }
  // send command buffers to queues:
  // - all buffers must wait for imageAvailableSemaphore
  // - each command buffer submission ends with signaling appropriate semaphore
  for (uint32_t queueIndex = 0; queueIndex < queues.size(); ++queueIndex)
  {
    for (unsigned int i = 0; i < commandBuffersToSubmit[queueIndex].size(); ++i)
      commandBuffersToSubmit[queueIndex][i]->queueSubmit(queues[queueIndex]->queue, { imageAvailableSemaphore }, { VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT }, { semaphoresToSubmit[queueIndex][i] }, VK_NULL_HANDLE);
  }
  // send to rendering a command buffer that transforms swapchain image layout into VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
  std::vector<VkPipelineStageFlags> waitStages;
  waitStages.resize(submissionCompletedSemaphores.size(), VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT);
  presentCommandBuffer->queueSubmit(queues[presentationQueueIndex]->queue, submissionCompletedSemaphores, waitStages, { renderFinishedSemaphore }, waitFences[swapChainImageIndex]);
}

void Surface::endFrame()
{
  // present output image after its layout is transformed into VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
  VkPresentInfoKHR presentInfo{};
    presentInfo.sType              = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
    presentInfo.swapchainCount     = 1;
    presentInfo.pSwapchains        = &swapChain;
    presentInfo.pImageIndices      = &swapChainImageIndex;
    presentInfo.waitSemaphoreCount = 1;
    presentInfo.pWaitSemaphores    = &renderFinishedSemaphore;
    VkResult result = vkQueuePresentKHR(queues[presentationQueueIndex]->queue, &presentInfo);

  if ((result != VK_ERROR_OUT_OF_DATE_KHR) && (result != VK_SUBOPTIMAL_KHR))
    VK_CHECK_LOG_THROW(result, "failed vkQueuePresentKHR");
  window->endFrame();
}

void Surface::resizeSurface(uint32_t newWidth, uint32_t newHeight)
{
  if (!isRealized())
    return;
  if (swapChainSize.width != newWidth && swapChainSize.height != newHeight)
  {
    recreateSwapChain();
    resized = true;
  }
}

void Surface::addRenderGraph(const std::string& name, bool active)
{
  CHECK_LOG_THROW(isRealized(), "Cannot add new render graphs after surface realization");
  renderGraphData.push_back(std::make_tuple(name, active));
}

std::vector<uint32_t> Surface::getQueueIndices(const std::string renderGraphName) const
{
  auto it = renderGraphQueueIndices.find(renderGraphName);
  CHECK_LOG_THROW(it == end(renderGraphQueueIndices), "There is no render graph with name : " << renderGraphName);
  return it->second;
}

uint32_t Surface::getNumQueues() const
{
  return queues.size();
}

Queue* Surface::getQueue(uint32_t index) const
{
  return queues.at(index).get();
}

std::shared_ptr<CommandPool> Surface::getCommandPool(uint32_t index) const
{
  return commandPools.at(index);
}

void Surface::setID(std::shared_ptr<Viewer> v, uint32_t newID)
{
  viewer = v;
  id = newID;
}

void Surface::onEventSurfaceRenderStart()
{
  if (eventSurfaceRenderStart != nullptr)
    eventSurfaceRenderStart(shared_from_this());
}

void Surface::onEventSurfaceRenderFinish()
{
  if (eventSurfaceRenderFinish != nullptr)
    eventSurfaceRenderFinish(shared_from_this());
}

void Surface::onEventSurfacePrepareStatistics(TimeStatistics* viewerStatistics)
{
  if (eventSurfacePrepareStatistics != nullptr)
    eventSurfacePrepareStatistics(this, viewerStatistics, timeStatistics.get());
}

std::shared_ptr<CommandPool> Surface::getPresentationCommandPool()
{
  return commandPools[presentationQueueIndex];
}

std::shared_ptr<Queue> Surface::getPresentationQueue()
{
  return queues[presentationQueueIndex];
}


text:
import unittest

from src.graph import Graph
from src.bfs_connected_components import bfs_connected_components

class TestBfsConnectedComponents(unittest.TestCase):

    def test_bfs_connected_components(self):
        """ Test the connected graphs algorithm for the folowing setup.
        (1)--(3)    (2)--(4)      (6)
          \  /                   /  \
          (5)                  (8) (10)
         /   \
        (7)  (9)
        This should return the nodes in three subgraphs.
        """
        edges = [(1,3), (1,5), (3,5), (5,7), (5,9), (2,4), (6,8), (6,10)]
        g = Graph.build(edges=edges)

        expected = [[1,3,5,9,7], [2,4], [6,8,10]]
        actual = bfs_connected_components(g)
        self.assertEqual(actual, expected, 'should correctly determine subgraphs')


text:
@interface BWPadJobDetailViewController ()
- (BWPadJobDetailHalfViewController *)jobDetail1;
- (BWPadJobDetailHalfViewController *)jobDetail2;
- (void)configureView;
- (void)configureLogView;
- (void)configureViewWithoutLog;
- (void)doLayout;
@end

@implementation BWPadJobDetailViewController

@synthesize toolbar, largeTextArea, largeTextAreaToggle;
@synthesize job;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self doLayout];

    NSKeyValueObservingOptions newAndOld = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
    [self addObserver:self forKeyPath:@"job" options:newAndOld context:nil];

    [self.largeTextAreaToggle addTarget:self
                                 action:@selector(switchLargeTextArea:)
                       forControlEvents:UIControlEventValueChanged];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self.jobDetail2.view setNeedsLayout];

    [self.job fetchDetailsIfNeeded];

    [self configureView];
}

- (void)configureView
{
    [self configureViewWithoutLog];
    [self configureLogView];
}

- (void) configureViewWithoutLog
{
    [self.finishedLabel setText:[self.job finishedText]];
    [self.durationLabel setText:[self.job durationText]];
    [self.commitLabel setText:self.job.commit];
    [self.compareLabel setText:self.job.compare];
    [self.authorLabel setText:self.job.author];
    [self.messageLabel setText:self.job.message];
    [self.configLabel setText:self.job.configString];

    [self.parentViewController setTitle:[NSString stringWithFormat:@"Job #%@", self.job.number]];
}

- (void)configureLogView
{
    if (self.largeTextAreaToggle.selectedSegmentIndex == 0) {
        [self.largeTextArea setText:job.log];
    }
    [self.logLabel setText:[job formattedNumberOfLinesInLog]];
}

// There is an unwanted "snap" on the right table (jobDetail2) when you:
//   * start the app in landscape
//   * show this viewcontroller
//   * switch to portrait
// PDI
- (void)doLayout
{
    UITableViewController *jobDetail1 = (UITableViewController *)[[self storyboard] instantiateViewControllerWithIdentifier:@"JobDetail1"];
    UITableViewController *jobDetail2 = (UITableViewController *)[[self storyboard] instantiateViewControllerWithIdentifier:@"JobDetail2"];

    [self addChildViewController:jobDetail1];
    [self addChildViewController:jobDetail2];

    [self.view addSubview:jobDetail1.view];
    [self.view addSubview:jobDetail2.view];

    jobDetail1.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
    jobDetail2.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;

    CGFloat width = (768.0f) / 2.0f;
    CGFloat height = 154.0f;
    CGRect jobDetailFrame1 = CGRectMake(0.0f, 0.0f, width, height);
    CGRect jobDetailFrame2 = CGRectMake(width, 0.0f, width, height);

    [jobDetail1.view setFrame:jobDetailFrame1];
    [jobDetail2.view setFrame:jobDetailFrame2];

    [jobDetail1.view setNeedsLayout];
    [jobDetail2.view setNeedsLayout];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [self.job unsubscribeFromLogUpdates];
}

#pragma mark Fake IBOutlets

- (UILabel *)finishedLabel { return [self jobDetail1].finishedLabel; }
- (UILabel *)durationLabel { return [self jobDetail1].durationLabel; }
- (UILabel *)commitLabel   { return [self jobDetail1].commitLabel;   }
- (UILabel *)compareLabel  { return [self jobDetail1].compareLabel;  }
- (UILabel *)authorLabel   { return [self jobDetail2].authorLabel;   }
- (UILabel *)messageLabel  { return [self jobDetail2].messageLabel;  }
- (UILabel *)configLabel   { return [self jobDetail2].configLabel;   }
- (UILabel *)logLabel      { return [self jobDetail2].logLinesLabel;      }

- (UITableViewController *)jobDetail1 { return (UITableViewController *)[[self childViewControllers] objectAtIndex:0]; }
- (UITableViewController *)jobDetail2 { return (UITableViewController *)[[self childViewControllers] objectAtIndex:1]; }

#pragma mark Observing the model layer

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([@"job" isEqualToString:keyPath]) {
        id oldJob = [change valueForKey:NSKeyValueChangeOldKey];
        BWCDJob *newJob = (BWCDJob *)[change valueForKey:NSKeyValueChangeNewKey];
        if ([NSNull null] != oldJob) {
            [(BWCDJob *)oldJob unsubscribeFromLogUpdates];
            [((BWCDJob *)oldJob) removeObserver:self forKeyPath:@"log"];
        }
        [newJob addObserver:self forKeyPath:@"log" options:NSKeyValueObservingOptionNew context:nil];
        [newJob subscribeToLogUpdates];
        [self configureView];
    } else if ([@"log" isEqualToString:keyPath]) {
        [self configureLogView];
    }
}

#pragma mark rotation

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return YES; }

#pragma mark toolbar

- (void)switchLargeTextArea:(id)sender
{
    UISegmentedControl *seg = (UISegmentedControl *)sender;
    switch (seg.selectedSegmentIndex) {
        case 0:
            [self.largeTextArea setText:self.job.log];
            break;
        case 1:
            [self.largeTextArea setText:self.job.message];
            break;
        case 2:
            [self.largeTextArea setText:[self.job.config description]];
            break;
    }
}

#pragma mark Show Safari for compare_url

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 3) {
        [self askToViewSafariForCompare];
        [[tableView cellForRowAtIndexPath:indexPath] setSelected:NO];
    }
}

- (void)askToViewSafariForCompare
{
    NSString *msg = @"This will quit TravisCI and open Safari.";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"View in Safari?" message:msg delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"View in Safari", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSURL *url = [NSURL URLWithString:self.job.compare];
        [[UIApplication sharedApplication] openURL:url];
    }
}

#pragma mark Unloading

- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; }

- (void)viewDidUnload
{
    [super viewDidUnload];

    [self.job removeObserver:self forKeyPath:@"log"];
    [self removeObserver:self forKeyPath:@"job"];

    [self setLargeTextArea:nil];
    [self setLargeTextAreaToggle:nil];
    [self setToolbar:nil];

    [self setJob:nil];

    [[self jobDetail1].view removeFromSuperview];
    [[self jobDetail2].view removeFromSuperview];

    for (UIViewController *child in self.childViewControllers) {
        [child removeFromParentViewController];
    }
}

@end


text:
package org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.debugpoint.impl;

import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.BREAKPOINT_LABEL;
import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.ESB_BREAKPOINT_ACTION_ID;
import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.ESB_BREAKPOINT_COMMAND_LABEL;
import static org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.utils.ESBDebuggerConstants.ESB_BREAKPOINT_COMMAND_TOOL_TIP;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.emf.edit.domain.IEditingDomainProvider;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gmf.runtime.common.ui.action.AbstractActionHandler;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.Activator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractMediator;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.configure.ConfigureEsbNodeAction;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.debugger.exception.ESBDebuggerException;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;

/**
 * A {@link AbstractActionHandler} used to hook-up action for set and clear
 * breakpoints in esb design view editor.
 */
public class ESBBreakpointAction extends ConfigureEsbNodeAction {

    private static IDeveloperStudioLog log = Logger.getLog(Activator.PLUGIN_ID);

    /**
     * Creates a new {@link ESBBreakpointAction} instance.
     *
     * @param part
     *            {@link IWorkbenchPart} instance.
     */
    public ESBBreakpointAction(IWorkbenchPart part) {
        super(part);
        super.init();
        setId(ESB_BREAKPOINT_ACTION_ID);
        setText(ESB_BREAKPOINT_COMMAND_LABEL);
        setToolTipText(ESB_BREAKPOINT_COMMAND_TOOL_TIP);
        ISharedImages workbenchImages = PlatformUI.getWorkbench().getSharedImages();
        setHoverImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_ETOOL_PRINT_EDIT));
        setImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_ETOOL_PRINT_EDIT));
        setDisabledImageDescriptor(workbenchImages.getImageDescriptor(ISharedImages.IMG_ETOOL_PRINT_EDIT_DISABLED));
    }

    /**
     * Utility method for retrieving the currently selected {@link EditPart}.
     *
     * @return current selected {@link EditPart} or null if multiple edit parts
     *         or no edit parts are selected.
     */
    @Override
    protected EditPart getSelectedEditPart() {
        IStructuredSelection selection = getStructuredSelection();
        if (selection.size() == 1) {
            Object selectedEP = selection.getFirstElement();
            if (selectedEP instanceof EditPart) {
                return (EditPart) selectedEP;
            }
        }
        return null;
    }

    /**
     * Utility method for calculating the editing domain.
     *
     * @return editing domain for this action.
     */
    @Override
    protected TransactionalEditingDomain getEditingDomain() {
        IWorkbenchPart part = getWorkbenchPart();

        if (part != null) {
            IEditingDomainProvider edProvider = (IEditingDomainProvider) part.getAdapter(IEditingDomainProvider.class);

            if (edProvider != null) {
                EditingDomain domain = edProvider.getEditingDomain();

                if (domain instanceof TransactionalEditingDomain) {
                    return (TransactionalEditingDomain) domain;
                }
            }
        }
        return null;
    }

    /**
     * This method performs the action when click the menu item Toggle
     * Breakpoint
     */
    @Override
    protected void doRun(IProgressMonitor progressMonitor) {

        EditPart selectedEP = getSelectedEditPart();
        if (selectedEP instanceof AbstractMediator && ESBDebugPointTarget.canToggleDiagramDebugpoints(selectedEP)) {
            try {
                ESBDebugPointTarget.toggleDiagramDebugpoints((AbstractMediator) selectedEP, BREAKPOINT_LABEL);
            } catch (CoreException | ESBDebuggerException e) {
                log.error("Error while registering the breakpoint : " + e.getMessage(), e);
            }
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hatfield.EnviroData.Core;

namespace Hatfield.EnviroData.DataAcquisition.ESDAT.Converters
{
    public interface IESDATSharedMapper<T> where T : class
    {
        T Map(ESDATModel esdatModel);
        T Scaffold(ESDATModel esdatModel);
    }
}