text:
package org.kaazing.gateway.util.asn1;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.nio.ByteBuffer;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import org.junit.Test;

public class Asn1UtilsTest {

    // ----- BEGIN: INTEGER tests

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeIntegerWithNull() {
        Asn1Utils.decodeInteger(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeIntegerWithEmpty() {
        Asn1Utils.decodeInteger(ByteBuffer.allocate(0));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeIntegerWithoutLength() {
        Asn1Utils.decodeInteger(ByteBuffer.wrap(new byte[] { 2 }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeIntegerWithoutData() {
        Asn1Utils.decodeInteger(ByteBuffer.wrap(new byte[] { 2, 1 }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeIntegerWithWrongTag() {
        assertEquals(5, Asn1Utils.decodeInteger(ByteBuffer.wrap(new byte[] { 3, 1, 5 })));
    }

    @Test
    public void testDecodeSingleByteInteger() {
        assertEquals(5, Asn1Utils.decodeInteger(ByteBuffer.wrap(new byte[] { 2, 1, 5 })));
    }

    @Test
    public void testDecodeMultiByteInteger() {
        assertEquals(1285, Asn1Utils.decodeInteger(ByteBuffer.wrap(new byte[] { 2, 2, 5, 5 })));
    }

    @Test
    public void testEncodeIntegerZero() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[3]);
        buf.position(buf.position() + 3);
        int len = Asn1Utils.encodeInteger(0, buf);
        assertEquals(3, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 2, buf.get(0));
        assertEquals((byte) 1, buf.get(1));
        assertEquals((byte) 0, buf.get(2));
    }

    @Test
    public void testEncodeInteger1Byte() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[3]);
        buf.position(buf.position() + 3);
        int len = Asn1Utils.encodeInteger(15, buf);
        assertEquals(3, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 2, buf.get(0));
        assertEquals((byte) 1, buf.get(1));
        assertEquals((byte) 0xf, buf.get(2));
    }

    @Test
    public void testEncodeInteger2Byte() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[4]);
        buf.position(buf.position() + 4);
        int len = Asn1Utils.encodeInteger(512, buf);
        assertEquals(4, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 2, buf.get(0));
        assertEquals((byte) 2, buf.get(1));
        assertEquals((byte) 2, buf.get(2));
        assertEquals((byte) 0, buf.get(3));
    }

    @Test
    public void testSizeOfInteger() {
        assertEquals(3, Asn1Utils.sizeOfInteger(15));
        assertEquals(4, Asn1Utils.sizeOfInteger(512));
        assertEquals(6, Asn1Utils.sizeOfInteger(1954663611));
    }

    // ----- END: INTEGER tests

    // ----- BEGIN: SEQUENCE tests

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeSequenceWithNull() {
        Asn1Utils.decodeSequence(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeSequenceWithEmpty() {
        Asn1Utils.decodeSequence(ByteBuffer.allocate(0));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeSequenceWithoutLength() {
        Asn1Utils.decodeSequence(ByteBuffer.wrap(new byte[] { 0x30 }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeSequenceWithoutData() {
        Asn1Utils.decodeSequence(ByteBuffer.wrap(new byte[] { 0x30, 3 }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeSequenceWithWrongTag() {
        Asn1Utils.decodeSequence(ByteBuffer.wrap(new byte[] { 0x31, 3, 2, 1, 5 }));
    }

    @Test
    public void testDecodeSequenceWithData() {
        Asn1Utils.decodeSequence(ByteBuffer.wrap(new byte[] { 0x30, 3, 2, 1, 5 }));
    }

    @Test
    public void testEncodeSequence() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[4]);
        buf.position(buf.position() + 2);
        int len = Asn1Utils.encodeSequence(2, buf);
        assertEquals(4, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 0x30, buf.get(0));
        assertEquals((byte) 2, buf.get(1));
    }

    @Test
    public void testSizeOfSequence() {
        assertEquals(2, Asn1Utils.sizeOfSequence(0));
        assertEquals(3, Asn1Utils.sizeOfSequence(1));
        assertEquals(4, Asn1Utils.sizeOfSequence(2));
        assertEquals(5, Asn1Utils.sizeOfSequence(3));
    }

    // ----- END: SEQUENCE tests

    // ----- BEGIN: BIT STRING tests

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeBitStringWithNull() {
        Asn1Utils.decodeBitString(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeBitStringWithEmpty() {
        Asn1Utils.decodeBitString(ByteBuffer.allocate(0));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeBitStringWithoutLength() {
        Asn1Utils.decodeBitString(ByteBuffer.wrap(new byte[] { 3 }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeBitStringWithoutPaddingAndData() {
        Asn1Utils.decodeBitString(ByteBuffer.wrap(new byte[] { 3, 5 }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeBitStringWithoutData() {
        Asn1Utils.decodeBitString(ByteBuffer.wrap(new byte[] { 3, 5, 0 }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeBitStringWithInvalidTag() {
        Asn1Utils.decodeBitString(ByteBuffer.wrap(new byte[] { 4, 5, 0, 0, (byte) 0x80, 0, 0 }));
    }

    @Test
    public void testDecodeBitStringWithData() {
        BitSet bits = Asn1Utils.decodeBitString(ByteBuffer.wrap(new byte[] { 3, 5, 0, 0, (byte) 0x80, 0, 0 }));
        for (int i = 0; i < bits.length(); i++) {
            if (i == 8) {
                assertTrue(bits.get(i));
            } else {
                assertFalse(bits.get(i));
            }
        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void testEncodeBitStringNull() {
        Asn1Utils.encodeBitString(null, 0, ByteBuffer.wrap(new byte[0]));
    }

    @Test
    public void testEncodeBitString8() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[4]);
        buf.position(buf.position() + 4);
        BitSet bits = new BitSet(8);
        bits.set(3);
        bits.set(5);
        int len = Asn1Utils.encodeBitString(bits, 8, buf);
        assertEquals(4, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 3, buf.get(0));
        assertEquals((byte) 2, buf.get(1));
        assertEquals((byte) 0, buf.get(2));
        assertEquals((byte) 0x14, buf.get(3));
    }

    @Test
    public void testEncodeBitString32() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[7]);
        buf.position(buf.position() + 7);
        BitSet bits = new BitSet(32);
        bits.set(8);
        int len = Asn1Utils.encodeBitString(bits, 32, buf);
        assertEquals(7, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 3, buf.get(0));
        assertEquals((byte) 5, buf.get(1));
        assertEquals((byte) 0, buf.get(2));
        assertEquals((byte) 0, buf.get(3));
        assertEquals((byte) 0x80, buf.get(4));
        assertEquals((byte) 0, buf.get(5));
        assertEquals((byte) 0, buf.get(6));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testEncodeBitString32As8() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[7]);
        buf.position(buf.position() + 7);
        BitSet bits = new BitSet(32);
        bits.set(8);
        Asn1Utils.encodeBitString(bits, 8, buf);
    }

    @Test
    public void testSizeOfBitString() {
        BitSet bits = new BitSet(32);
        assertEquals(4, Asn1Utils.sizeOfBitString(bits, 7));
        assertEquals(4, Asn1Utils.sizeOfBitString(bits, 8));
        assertEquals(5, Asn1Utils.sizeOfBitString(bits, 9));
        assertEquals(7, Asn1Utils.sizeOfBitString(bits, 32));
    }

    // ----- END: BIT STRING tests

    // ----- BEGIN: IA5STRING tests

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeIA5StringWithNull() {
        Asn1Utils.decodeIA5String(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeIA5StringWithEmpty() {
        Asn1Utils.decodeIA5String(ByteBuffer.allocate(0));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeIA5StringWithoutLength() {
        Asn1Utils.decodeIA5String(ByteBuffer.wrap(new byte[] { 0x1b }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeIA5StringWithoutData() {
        Asn1Utils.decodeIA5String(ByteBuffer.wrap(new byte[] { 0x1b, 4 }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeIA5StringWithWrongTag() {
        Asn1Utils.decodeIA5String(ByteBuffer.wrap(new byte[] { 0x1c, 0 }));
    }

    @Test
    public void testDecodeIA5StringWithEmptyData() {
        String value = Asn1Utils.decodeIA5String(ByteBuffer.wrap(new byte[] { 0x1b, 0 }));
        assertEquals("", value);
    }

    @Test
    public void testDecodeIA5StringWithData() {
        String value = Asn1Utils.decodeIA5String(ByteBuffer.wrap(new byte[] { 0x1b, 4, 0x61, 0x72, 0x75, 0x6e }));
        assertEquals("arun", value);
    }

    @Test
    public void testEncodeIA5StringWithNull() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[2]);
        buf.position(buf.position() + 2);
        int len = Asn1Utils.encodeIA5String(null, buf);
        assertEquals(2, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 0x1b, buf.get(0));
        assertEquals((byte) 0, buf.get(1));
    }

    @Test
    public void testEncodeIA5StringWithEmpty() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[2]);
        buf.position(buf.position() + 2);
        int len = Asn1Utils.encodeIA5String("", buf);
        assertEquals(2, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 0x1b, buf.get(0));
        assertEquals((byte) 0, buf.get(1));
    }

    @Test
    public void testEncodeIA5StringWithValue() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[6]);
        buf.position(buf.position() + 6);
        int len = Asn1Utils.encodeIA5String("arun", buf);
        assertEquals(6, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 0x1b, buf.get(0));
        assertEquals((byte) 4, buf.get(1));
        assertEquals((byte) 0x61, buf.get(2));
        assertEquals((byte) 0x72, buf.get(3));
        assertEquals((byte) 0x75, buf.get(4));
        assertEquals((byte) 0x6e, buf.get(5));
    }

    @Test
    public void testSizeOfIA5String() {
        assertEquals(2, Asn1Utils.sizeOfIA5String(null));
        assertEquals(2, Asn1Utils.sizeOfIA5String(""));
        assertEquals(6, Asn1Utils.sizeOfIA5String("arun"));
    }

    // ----- END: IA5STRING tests

    // ----- BEGIN: GeneralizedTime tests

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeGeneralizedTimeWithNull() {
        Asn1Utils.decodeGeneralizedTime(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeGeneralizedTimeWithEmpty() {
        Asn1Utils.decodeGeneralizedTime(ByteBuffer.allocate(0));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeGeneralizedTimeWithoutLength() {
        Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(new byte[] { 0x18 }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeGeneralizedTimeWithoutData() {
        Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(new byte[] { 0x18, 0xf }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeGeneralizedTimeWithWrongTag() {
        byte[] data = new byte[] { 0x19, 0xe, 0x32, 0x30, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32, 0x37 };
        Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeGeneralizedTimeWithMalformedData() {
        byte[] data = new byte[] { 0x18, 0xc, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32, 0x37 };
        Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));
    }

    @Test
    public void testDecodeGeneralizedTimeWithoutTimeZone() {
        // Test date: 2010 07 12 21 45 27
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        Date expectedDate = cal.getTime();

        byte[] data = new byte[] { 0x18, 0xe, 0x32, 0x30, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32, 0x37 };
        Date actualDate = Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));

        assertEquals(expectedDate, actualDate);
    }

    @Test
    public void testDecodeGeneralizedTimeWithTimeZoneZ() {
        // Test date: 2010 07 12 21 45 27 Z
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date expectedDate = cal.getTime();

        byte[] data = new byte[] { 0x18, 0xf, 0x32, 0x30, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32, 0x37,
                0x5a };
        Date actualDate = Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));

        assertEquals(expectedDate, actualDate);
    }

    @Test
    public void testDecodeGeneralizedTimeWithPosTimeZone() {
        // Test date: 2010 07 12 21 45 27 +0800
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        Date expectedDate = cal.getTime();

        byte[] data = new byte[] { 0x18, 0x13, 0x32, 0x30, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32,
                0x37, 0x2b, 0x30, 0x38, 0x30, 0x30 };
        Date actualDate = Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));

        assertEquals(expectedDate, actualDate);
    }

    @Test
    public void testDecodeGeneralizedTimeWithNegTimeZone() {
        // Test date: 2010 07 12 21 45 27 -0800
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.setTimeZone(TimeZone.getTimeZone("GMT-8"));
        Date expectedDate = cal.getTime();

        byte[] data = new byte[] { 0x18, 0x13, 0x32, 0x30, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32,
                0x37, 0x2d, 0x30, 0x38, 0x30, 0x30 };
        Date actualDate = Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));

        assertEquals(expectedDate, actualDate);
    }

    @Test
    public void testDecodeGeneralizedTimeWithoutTimeZoneWithFracSec() {
        // Test date: 2010 07 12 21 45 27.3
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.set(Calendar.MILLISECOND, 300);
        Date expectedDate = cal.getTime();

        byte[] data = new byte[] { 0x18, 0x10, 0x32, 0x30, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32,
                0x37, 0x2e, 0x33 };
        Date actualDate = Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));

        assertEquals(expectedDate, actualDate);
    }

    @Test
    public void testDecodeGeneralizedTimeWithoutTimeZoneWithFracSec2Byte() {
        // Test date: 2010 07 12 21 45 27.36
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.set(Calendar.MILLISECOND, 360);
        Date expectedDate = cal.getTime();

        byte[] data = new byte[] { 0x18, 0x11, 0x32, 0x30, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32,
                0x37, 0x2e, 0x33, 0x36 };
        Date actualDate = Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));

        assertEquals(expectedDate, actualDate);
    }

    @Test
    public void testDecodeGeneralizedTimeWithoutTimeZoneWithFracSec4Byte() {
        // Test date: 2010 07 12 21 45 27.3629
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.set(Calendar.MILLISECOND, 362);
        Date expectedDate = cal.getTime();

        byte[] data = new byte[] { 0x18, 0x13, 0x32, 0x30, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32,
                0x37, 0x2e, 0x33, 0x36, 0x32, 0x39 };
        Date actualDate = Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));

        assertEquals(expectedDate, actualDate);
    }

    @Test
    public void testDecodeGeneralizedTimeWithTimeZoneZWithFracSec() {
        // Test date: 2010 07 12 21 45 27.3 Z
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.set(Calendar.MILLISECOND, 300);
        cal.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date expectedDate = cal.getTime();

        byte[] data = new byte[] { 0x18, 0x11, 0x32, 0x30, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32,
                0x37, 0x2e, 0x33, 0x5a };
        Date actualDate = Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));

        assertEquals(expectedDate, actualDate);
    }

    @Test
    public void testDecodeGeneralizedTimeWithPosTimeZoneWithFracSec() {
        // Test date: 2010 07 12 21 45 27.3 +0800
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.set(Calendar.MILLISECOND, 300);
        cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        Date expectedDate = cal.getTime();

        byte[] data = new byte[] { 0x18, 0x15, 0x32, 0x30, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32,
                0x37, 0x2e, 0x33, 0x2b, 0x30, 0x38, 0x30, 0x30 };
        Date actualDate = Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));

        assertEquals(expectedDate, actualDate);
    }

    @Test
    public void testDecodeGeneralizedTimeWithNegTimeZoneWithFracSec() {
        // Test date: 2010 07 12 21 45 27.3 -0800
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.set(Calendar.MILLISECOND, 300);
        cal.setTimeZone(TimeZone.getTimeZone("GMT-8"));
        Date expectedDate = cal.getTime();

        byte[] data = new byte[] { 0x18, 0x15, 0x32, 0x30, 0x31, 0x30, 0x30, 0x37, 0x31, 0x32, 0x32, 0x31, 0x34, 0x35, 0x32,
                0x37, 0x2e, 0x33, 0x2d, 0x30, 0x38, 0x30, 0x30 };
        Date actualDate = Asn1Utils.decodeGeneralizedTime(ByteBuffer.wrap(data));

        assertEquals(expectedDate, actualDate);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testEncodeGeneralizedTimeWithNull() {
        Asn1Utils.encodeGeneralizedTime(null, null);
    }

    @Test
    public void testEncodeGeneralizedTime() {
        // Test date: 2010 07 12 21 45 27 UTC
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date date = cal.getTime();

        int size = 17;
        ByteBuffer buf = ByteBuffer.wrap(new byte[size]);
        buf.position(buf.position() + size);
        int len = Asn1Utils.encodeGeneralizedTime(date, buf);

        assertEquals(size, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 0x18, buf.get(0));
        assertEquals((byte) 0xf, buf.get(1));
        assertEquals((byte) 0x32, buf.get(2));
        assertEquals((byte) 0x30, buf.get(3));
        assertEquals((byte) 0x31, buf.get(4));
        assertEquals((byte) 0x30, buf.get(5));
        assertEquals((byte) 0x30, buf.get(6));
        assertEquals((byte) 0x37, buf.get(7));
        assertEquals((byte) 0x31, buf.get(8));
        assertEquals((byte) 0x32, buf.get(9));
        assertEquals((byte) 0x32, buf.get(10));
        assertEquals((byte) 0x31, buf.get(11));
        assertEquals((byte) 0x34, buf.get(12));
        assertEquals((byte) 0x35, buf.get(13));
        assertEquals((byte) 0x32, buf.get(14));
        assertEquals((byte) 0x37, buf.get(15));
        assertEquals((byte) 0x5a, buf.get(16));
    }

    @Test
    public void testSizeOfGeneralizedTime() {
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        Date date = cal.getTime();
        assertEquals(17, Asn1Utils.sizeOfGeneralizedTime(date));
    }

    @Test
    public void testSizeOfGeneralizedTimeWithFracSet() {
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, 2010);
        cal.set(Calendar.MONTH, Calendar.JULY);
        cal.set(Calendar.DAY_OF_MONTH, 12);
        cal.set(Calendar.HOUR_OF_DAY, 21);
        cal.set(Calendar.MINUTE, 45);
        cal.set(Calendar.SECOND, 27);
        cal.set(Calendar.MILLISECOND, 300);
        cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        Date date = cal.getTime();
        assertEquals(17, Asn1Utils.sizeOfGeneralizedTime(date));
    }

    // ----- END: GeneralizedTime tests

    // ----- BEGIN: OCTET STRING tests

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeOctetStringWithNull() {
        Asn1Utils.decodeOctetString(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeOctetStringWithEmpty() {
        Asn1Utils.decodeOctetString(ByteBuffer.allocate(0));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeOctetStringWithoutLength() {
        Asn1Utils.decodeOctetString(ByteBuffer.wrap(new byte[] { 4 }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeOctetStringWithoutData() {
        Asn1Utils.decodeOctetString(ByteBuffer.wrap(new byte[] { 4, 4 }));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testDecodeOctetStringWithWrongTag() {
        Asn1Utils.decodeOctetString(ByteBuffer.wrap(new byte[] { 5, 0 }));
    }

    @Test
    public void testDecodeOctetStringWithEmptyData() {
        short[] value = Asn1Utils.decodeOctetString(ByteBuffer.wrap(new byte[] { 4, 0 }));
        assertEquals(0, value.length);
    }

    @Test
    public void testDecodeOctetStringWithData() {
        short[] value = Asn1Utils.decodeOctetString(ByteBuffer.wrap(new byte[] { 4, 4, (byte) 0xc0, (byte) 0xa8, 0, 0x0f }));
        assertEquals(4, value.length);
        assertEquals((short) 192, value[0]);
        assertEquals((short) 168, value[1]);
        assertEquals((short) 0, value[2]);
        assertEquals((short) 15, value[3]);
    }

    @Test
    public void testEncodeOctetStringNull() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[2]);
        buf.position(buf.position() + 2);
        int len = Asn1Utils.encodeOctetString(null, buf);
        assertEquals(2, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 4, buf.get(0));
        assertEquals((byte) 0, buf.get(1));
    }

    @Test
    public void testEncodeOctetStringEmpty() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[2]);
        buf.position(buf.position() + 2);
        int len = Asn1Utils.encodeOctetString(new short[] {}, buf);
        assertEquals(2, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 4, buf.get(0));
        assertEquals((byte) 0, buf.get(1));
    }

    @Test
    public void testEncodeOctetString() {
        ByteBuffer buf = ByteBuffer.wrap(new byte[6]);
        buf.position(buf.position() + 6);
        int len = Asn1Utils.encodeOctetString(new short[] { 192, 168, 0, 15 }, buf);
        assertEquals(6, len);
        assertEquals(0, buf.position());
        assertEquals((byte) 4, buf.get(0));
        assertEquals((byte) 4, buf.get(1));
        assertEquals((byte) 0xc0, buf.get(2));
        assertEquals((byte) 0xa8, buf.get(3));
        assertEquals((byte) 0, buf.get(4));
        assertEquals((byte) 0x0f, buf.get(5));
    }

    @Test
    public void testSizeOfOctetString() {
        assertEquals(2, Asn1Utils.sizeOfOctetString(null));
        assertEquals(2, Asn1Utils.sizeOfOctetString(new short[] {}));
        assertEquals(6, Asn1Utils.sizeOfOctetString(new short[] { 192, 168, 0, 15 }));
    }

    // ----- END: OCTET STRING tests
}


text:
/* globals define */

/*
 * Shared Background for the Home and Splash Screen
 */

define(function(require, exports, module) {
  var View          = require('famous/core/View');
  var Surface       = require('famous/core/Surface');
  var StateModifier = require('famous/modifiers/StateModifier');
  var Timer         = require('famous/utilities/Timer');

  function BackgroundView() {
    View.apply(this, arguments);

    this._modifiers = [];

    var rootModifier = new StateModifier({
      origin: [0, 0],
      align: [0, 0]
    });

    this.node = this.add(rootModifier);

    _createBacking.call(this);
    _createFirstPatternOverlay.call(this);
    _createSecondPatternOverlay.call(this);
  }

  BackgroundView.prototype = Object.create(View.prototype);
  BackgroundView.prototype.constructor = BackgroundView;

  BackgroundView.DEFAULT_OPTIONS = {};

  BackgroundView.prototype.show = function(transition, delay, callback) {
    var ease = {
      curve: 'easeIn',
      duration: 300
    };

    transition = transition || ease;
    delay = delay || delay === 0 ? delay : 300;

    function setMod(mod) {
      mod.setOpacity(0.999, transition);
    }

    // Animate the background in
    for (var i = 0; i < this._modifiers.length; i++) {
      var mod = this._modifiers[i];

      Timer.setTimeout(setMod.bind(this, mod), i * delay);
    }

    // Execute callback after the animations have completed
    Timer.setTimeout(function() {
      if (callback) {
        callback();
      }
    }.bind(this), delay * (this._modifiers.length - 1));
  };

  BackgroundView.prototype.hide = function(transition, delay, callback) {
    var ease = {
      curve: 'easeIn',
      duration: 0
    };

    transition = transition || ease;
    delay = delay || delay === 0 ? delay : 0;

    function setMod(mod) {
      mod.setOpacity(0.001, transition);
    }

    // Animate the background out
    for (var i = 0; i < this._modifiers.length; i++) {
      var mod = this._modifiers[i];

      Timer.setTimeout(setMod.bind(this, mod), i * delay);
    }

    // Execute callback after the animations have completed
    Timer.setTimeout(function() {
      if (callback) {
        callback();
      }
    }.bind(this), delay * (this._modifiers.length - 1));
  };

  // Shared Between the Splash page and the Home page
  function _createBacking() {
    var backing = new Surface({
      classes: ['splash', 'splash-backing'],
      properties: {
        zIndex: 1
      }
    });

    var mod = new StateModifier({
      opacity: 0.001
    });

    this._modifiers.push(mod);

    this.node.add(mod).add(backing);
  }

  // Shared Between the Splash page and the Home page
  function _createFirstPatternOverlay() {
    var firstPattern = new Surface({
      classes: ['splash', 'splash-pattern', 'splash-pattern-1'],
      properties: {
        zIndex: 2
      }
    });

    var mod = new StateModifier({
      opacity: 0.001
    });

    this._modifiers.push(mod);

    this.node.add(mod).add(firstPattern);
  }

  // Shared Between the Splash page and the Home page
  function _createSecondPatternOverlay() {
    var secondPattern = new Surface({
      classes: ['splash', 'splash-pattern', 'splash-pattern-2'],
      properties: {
        zIndex: 3
      }
    });

    var mod = new StateModifier({
      opacity: 0.001
    });

    this._modifiers.push(mod);

    this.node.add(mod).add(secondPattern);
  }

  module.exports = BackgroundView;
});

redpajama_set_name: RedPajamaGithub


text:
export function clone({
  title,
  description,
  base,
  canonical,
  meta,
  link,
  auto
}) {
  try {
    return JSON.parse(
      JSON.stringify({ title, description, base, canonical, meta, link, auto })
    );
  } catch (x) {
    return {};
  }
}

export function defaults(target, source) {
  return Object.keys(source).reduce((acc, key) => {
    if (!target.hasOwnProperty(key)) {
      target[key] = source[key];
    } else if (
      typeof target[key] === 'object' &&
      !Array.isArray(target[key]) &&
      target[key]
    ) {
      defaults(target[key], source[key]);
    }

    return target;
  }, target);
}

// This is needed as not all browsers,
// including Edge and IE has not implemented .forEach() on NodeList
export function forEach(nodes, fn) {
  if (nodes && nodes.length) {
    Array.prototype.slice.call(nodes).forEach(fn);
  }
}


text:
namespace Swan.Mapping;

using Collections;
using Reflection;

/// <summary>
/// Represents an AutoMapper-like object to map from one object type
/// to another using defined properties map or using the default behaviour
/// to copy same named properties from one object to another.
/// </summary>
public class ObjectMapper
{
    private static readonly Lazy<ObjectMapper> LazyInstance = new(() => new());

    private readonly ConcurrentDictionary<Type, ConcurrentDictionary<Type, IObjectMap>> TargetMaps = new();

    /// <summary>
    /// Gets the default instance of the object mapper.
    /// </summary>
    public static ObjectMapper Default => LazyInstance.Value;

    /// <summary>
    /// Copies the specified source.
    /// </summary>
    /// <param name="source">The source.</param>
    /// <param name="target">The target.</param>
    /// <param name="propertiesToCopy">The properties to copy.</param>
    /// <param name="ignoreProperties">The ignore properties.</param>
    /// <returns>
    /// Copied properties count.
    /// </returns>
    /// <exception cref="ArgumentNullException">
    /// source
    /// or
    /// target.
    /// </exception>
    public static int Copy(
        object? source,
        object? target,
        IEnumerable<string>? propertiesToCopy = null,
        params string[]? ignoreProperties)
    {
        return source == null
            ? throw new ArgumentNullException(nameof(source))
            : target == null
            ? throw new ArgumentNullException(nameof(target))
            : CopyInternal(
            target,
            GetSourceMap(source),
            propertiesToCopy,
            ignoreProperties);
    }

    /// <summary>
    /// Copies the specified source.
    /// </summary>
    /// <param name="source">The source.</param>
    /// <param name="target">The target.</param>
    /// <param name="propertiesToCopy">The properties to copy.</param>
    /// <param name="ignoreProperties">The ignore properties.</param>
    /// <returns>
    /// Copied properties count.
    /// </returns>
    /// <exception cref="ArgumentNullException">
    /// source
    /// or
    /// target.
    /// </exception>
    public static int Copy(
        IDictionary<string, object?> source,
        object? target,
        IEnumerable<string>? propertiesToCopy = null,
        params string[] ignoreProperties)
    {
        return source == null
            ? throw new ArgumentNullException(nameof(source))
            : target == null
            ? throw new ArgumentNullException(nameof(target))
            : CopyInternal(
            target,
            source.ToDictionary(
                x => x.Key.ToLowerInvariant(),
                x => Tuple.Create(typeof(object), x.Value)),
            propertiesToCopy,
            ignoreProperties);
    }
    /// <inheritdoc/>

    public bool HasMap(Type sourceType, Type targetType) =>
        TargetMaps.TryGetValue(targetType, out var sourceMaps) && sourceMaps.ContainsKey(sourceType);
    /// <inheritdoc/>

    public bool TryGetMap(Type sourceType, Type targetType, [MaybeNullWhen(false)] out IObjectMap map)
    {
        if (!TargetMaps.TryGetValue(targetType, out var sourceMaps))
        {
            sourceMaps = new();
            TargetMaps.TryAdd(targetType, sourceMaps);
        }

        return sourceMaps.TryGetValue(sourceType, out map);
    }

    private bool TryGetMap<TSource, TTarget>([MaybeNullWhen(false)] out IObjectMap<TSource, TTarget> map)
    {
        if (TryGetMap(typeof(TSource), typeof(TTarget), out var existingMap) &&
            existingMap is IObjectMap<TSource, TTarget> typedMap)
        {
            map = typedMap;
            return true;
        }

        map = default;
        return false;
    }

    private void TrySetMap<TSource, TTarget>(IObjectMap map)
    {
        if (map is null)
            throw new ArgumentNullException(nameof(map));

        if (!TargetMaps.TryGetValue(typeof(TTarget), out var sourceMaps))
        {
            sourceMaps = new();
            TargetMaps.TryAdd(typeof(TTarget), sourceMaps);
        }

        if (!sourceMaps.ContainsKey(typeof(TSource)))
        {
            sourceMaps[typeof(TSource)] = map;
        }
    }

    /// <summary>
    /// Creates a default map between the source and target types
    /// and adds it to this object mapper.
    /// </summary>
    /// <typeparam name="TSource">The type of the source.</typeparam>
    /// <typeparam name="TTarget">The type of the target</typeparam>
    /// <returns>A newly-created default map between the 2 objects.</returns>
    public IObjectMap<TSource, TTarget> AddMap<TSource, TTarget>()
    {
        if (TryGetMap<TSource, TTarget>(out _))
            throw new InvalidOperationException(
                $"This mapper already defines a map between target '{typeof(TTarget)}' and source '{typeof(TSource)}'");

        if (!TargetMaps.TryGetValue(typeof(TTarget), out _))
        {
            var sourceMaps = new ConcurrentDictionary<Type, IObjectMap>();
            TargetMaps.TryAdd(typeof(TTarget), sourceMaps);
        }

        var map = new ObjectMap<TSource, TTarget>(this);
        if (!map.Any())
            throw new InvalidOperationException("Types don't have any matching properties.");

        TrySetMap<TSource, TTarget>(map);

        return map;
    }

    /// <summary>
    /// Retrieves an existing map between target and source types.
    /// If the map already exists, it returns it from this mapper's internal storage.
    /// </summary>
    /// <typeparam name="TSource">The type of the source.</typeparam>
    /// <typeparam name="TTarget">The type of the target</typeparam>
    /// <returns>A map between the 2 objects.</returns>
    public IObjectMap<TSource, TTarget> GetOrAddMap<TSource, TTarget>()
    {
        if (TryGetMap<TSource, TTarget>(out var map))
            return map;

        map = new ObjectMap<TSource, TTarget>(this);
        TrySetMap<TSource, TTarget>(map);

        return map;
    }

    /// <summary>
    /// Maps the specified source.
    /// </summary>
    /// <typeparam name="TTarget">The type of the destination.</typeparam>
    /// <param name="source">The source.</param>
    /// <param name="autoResolve">if set to <c>true</c> [automatic resolve].</param>
    /// <returns>
    /// A new instance of the map.
    /// </returns>
    /// <exception cref="ArgumentNullException">source.</exception>
    /// <exception cref="InvalidOperationException">You can't map from type {source.GetType().Name} to {typeof(TDestination).Name}.</exception>
    public TTarget Apply<TTarget>(object source, bool autoResolve = true)
        where TTarget : class, new()
    {
        if (source is null)
            throw new ArgumentNullException(nameof(source));

        var sourceType = source.GetType();
        var targetType = typeof(TTarget);

        var target = new TTarget();

        if (TryGetMap(sourceType, targetType, out var map))
        {
            map.Apply(source, target);
            return target;
        }
        else
        {
            if (!autoResolve)
            {
                throw new InvalidOperationException(
                    $"You can't map from type {source.GetType().Name} to {typeof(TTarget).Name}");
            }

            // Missing mapping, try to use default behavior
            Copy(source, target);
        }

        return target;
    }

    private static int CopyInternal(
        object target,
        IReadOnlyDictionary<string, Tuple<Type, object?>> sourceProperties,
        IEnumerable<string>? propertiesToCopy,
        IEnumerable<string>? ignoreProperties)
    {
        // Filter properties
        var requiredProperties = propertiesToCopy?
            .Where(p => !string.IsNullOrWhiteSpace(p))
            .Select(p => p.ToLowerInvariant());

        var ignoredProperties = ignoreProperties?
            .Where(p => !string.IsNullOrWhiteSpace(p))
            .Select(p => p.ToLowerInvariant());

        var properties = target.GetType().Properties().Where(c => c.CanWrite);

        return properties
            .Select(x => x.PropertyName)
            .Distinct()
            .ToDictionary(x => x.ToLowerInvariant(), x => properties.First(y => y.PropertyName == x))
            .Where(x => sourceProperties.ContainsKey(x.Key))
            .When(() => requiredProperties is not null, q => q.Where(y => requiredProperties!.Contains(y.Key)))
            .When(() => ignoredProperties is not null, q => q.Where(y => !ignoredProperties!.Contains(y.Key)))
            .ToDictionary(x => x.Value, x => sourceProperties[x.Key])
            .Sum(x => TrySetValue(x.Key.PropertyInfo, x.Value, target) ? 1 : 0);
    }

    private static bool TrySetValue(PropertyInfo targetProperty, Tuple<Type, object?> sourceProperty, object targetInstance)
    {
        try
        {
            var (type, value) = sourceProperty;

            if (targetProperty.PropertyType.IsArray)
            {
                targetProperty.TrySetArray(value as IEnumerable<object>, targetInstance);
                return true;
            }

            if (targetProperty.ToPropertyProxy().TryWrite(targetInstance, value))
                return true;

        }

        catch
        {
            // swallow
        }

        return false;
    }

    private static Dictionary<string, Tuple<Type, object?>> GetSourceMap(object source)
    {
        // select distinct properties because they can be duplicated by inheritance
        var sourceProperties = source.GetType().Properties().Where(c => c.CanRead);

        return sourceProperties
            .Select(x => x.PropertyName)
            .Distinct()
            .ToDictionary(
                x => x.ToLowerInvariant(),
                x => Tuple.Create(sourceProperties.First(y => y.PropertyName == x).PropertyType.NativeType,
                    sourceProperties.First(y => y.PropertyName == x).Read(source)));
    }
}


text:
"use strict";

var exec  = require('child_process').exec,
    path  = require('path'),
    fs    = require('fs'),
    util  = require('util'),
    debug = require('debug')('module-builder');

function parseJson(str) {
  var jsonObj;

  try {
    jsonObj = JSON.parse(str);
  }
  catch (err) {
    return new Error('Failed to parse package.json file');
  }

  return jsonObj;
}

function readIfExists(filePath, callback) {
  // verify that file exists
  fs.exists(filePath, function(exists) {
    if (!exists) {
      return callback(new Error('File ' + filePath + ' not found'));
    }

    // read file content
    fs.readFile(filePath, 'utf-8', callback);
  });
}

function getPackageDeps(dir, callback) {
  // read file content
  readIfExists(path.join(dir, 'package.json'), function(err, content) {
    var pkg;

    if (err) { return callback(err); }

    pkg = parseJson(content);

    if (util.isError(pkg)) {
      callback(pkg);
    } else {
      callback(null, pkg.dependencies);
    }
  });
}

// dependencies formatted for NPM usage: express@3.1.x treeit@*
function getFormattedDeps(dependencyObj) {
  var str = [];

  Object.keys(dependencyObj).forEach(function(dep) {
    str.push(dep + '@' + dependencyObj[dep]);
  });

  return str.join(' ');
}

// main function
function install(dir, deps, callback) {
  // deps param optional
  if (typeof deps === 'function') {
    callback = deps;

    getPackageDeps(dir, function(err, deps) {
      if (err) { return callback(err); }

      executeNpm(dir, deps, callback);
    });
  } else {
    executeNpm(dir, deps, callback);
  }
}

function executeNpm(dir, deps, callback) {
  var cmd, execOpts;

  if (!deps) { return callback('No dependencies found'); }

  deps = getFormattedDeps(deps);

  cmd  = 'npm install ' + deps;
  cmd += ' --loglevel error --json';

  execOpts = {
    cwd     : dir,
    env     : {
      PATH     : process.env.PATH,
      NODE_ENV : 'production'
    }
  };

  debug('cmd', cmd);
  debug('execOpts', execOpts);

  exec(cmd, execOpts, function(err, stdout, stderr) {
    var res = {};

    if (err) { return callback(err, stdout, stderr); }

    try {
      res = JSON.parse(stdout);
    }
    catch (er) {
     //...
    }

    callback(err, res, stderr);
  });
}

module.exports = {
  parseJson        : parseJson,
  readIfExists     : readIfExists,
  getPackageDeps   : getPackageDeps,
  getFormattedDeps : getFormattedDeps,
  executeNpm       : executeNpm,
  install          : install
};


text:
package com.vmware.vim25;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for HostNetworkConfigNetStackSpec complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="HostNetworkConfigNetStackSpec">
 *   <complexContent>
 *     <extension base="{urn:vim25}DynamicData">
 *       <sequence>
 *         <element name="netStackInstance" type="{urn:vim25}HostNetStackInstance"/>
 *         <element name="operation" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "HostNetworkConfigNetStackSpec", propOrder = {
    "netStackInstance",
    "operation"
})
public class HostNetworkConfigNetStackSpec
    extends DynamicData
{

    @XmlElement(required = true)
    protected HostNetStackInstance netStackInstance;
    protected String operation;

    /**
     * Gets the value of the netStackInstance property.
     *
     * @return
     *     possible object is
     *     {@link HostNetStackInstance }
     *
     */
    public HostNetStackInstance getNetStackInstance() {
        return netStackInstance;
    }

    /**
     * Sets the value of the netStackInstance property.
     *
     * @param value
     *     allowed object is
     *     {@link HostNetStackInstance }
     *
     */
    public void setNetStackInstance(HostNetStackInstance value) {
        this.netStackInstance = value;
    }

    /**
     * Gets the value of the operation property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getOperation() {
        return operation;
    }

    /**
     * Sets the value of the operation property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setOperation(String value) {
        this.operation = value;
    }

}


text:
import {
  CLEAR_UPLOAD_COMPLETED,
  LIST_POST_RELOADED,
  LIST_CPROP_POST_RELOADED,
  LIST_MANAGE_POST_RELOADED,
  LIST_OVERVIEW_POST_RELOADED,
  LIST_NEWS_POST_RELOADED,
  LIST_OG_POST_RELOADED,
  LIST_OG_POST_NEARBY_RELOADED,
  SEARCH_NEARBY_RELOADED,
  CLEAR_CACHE_COMPLETED
}from 'shared/constants/ActionTypes'

export function clearCache () {
  return dispatch => {
    dispatch({ type: CLEAR_UPLOAD_COMPLETED })
    dispatch({ type: LIST_POST_RELOADED })
    dispatch({ type: LIST_CPROP_POST_RELOADED })
    dispatch({ type: LIST_MANAGE_POST_RELOADED })
    dispatch({ type: LIST_OVERVIEW_POST_RELOADED })
    dispatch({ type: LIST_NEWS_POST_RELOADED })
    dispatch({ type: LIST_OG_POST_RELOADED })
    dispatch({ type: LIST_OG_POST_NEARBY_RELOADED })

    return dispatch({ type: CLEAR_CACHE_COMPLETED })
  }
}


text:
/**
 * @fileoverview Tests for max-statements rule.
 * @author Ian Christian Myers
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const rule = require("../../../lib/rules/max-statements"),
    RuleTester = require("../../../lib/testers/rule-tester");

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

const ruleTester = new RuleTester();

ruleTester.run("max-statements", rule, {
    valid: [
        { code: "function foo() { var bar = 1; function qux () { var noCount = 2; } return 3; }", options: [3] },
        { code: "function foo() { var bar = 1; if (true) { for (;;) { var qux = null; } } else { quxx(); } return 3; }", options: [6] },
        { code: "function foo() { var x = 5; function bar() { var y = 6; } bar(); z = 10; baz(); }", options: [5] },
        "function foo() { var a; var b; var c; var x; var y; var z; bar(); baz(); qux(); quxx(); }",
        { code: "(function() { var bar = 1; return function () { return 42; }; })()", options: [1, { ignoreTopLevelFunctions: true }] },
        { code: "function foo() { var bar = 1; var baz = 2; }", options: [1, { ignoreTopLevelFunctions: true }] },
        { code: "define(['foo', 'qux'], function(foo, qux) { var bar = 1; var baz = 2; })", options: [1, { ignoreTopLevelFunctions: true }] },

        // object property options
        { code: "var foo = { thing: function() { var bar = 1; var baz = 2; } }", options: [2] },
        { code: "var foo = { thing() { var bar = 1; var baz = 2; } }", options: [2], parserOptions: { ecmaVersion: 6 } },
        { code: "var foo = { ['thing']() { var bar = 1; var baz = 2; } }", options: [2], parserOptions: { ecmaVersion: 6 } },
        { code: "var foo = { thing: () => { var bar = 1; var baz = 2; } }", options: [2], parserOptions: { ecmaVersion: 6 } },
        { code: "var foo = { thing: function() { var bar = 1; var baz = 2; } }", options: [{ max: 2 }] }
    ],
    invalid: [
        {
            code: "function foo() { var bar = 1; var baz = 2; var qux = 3; }",
            options: [2],
            errors: [{ message: "Function 'foo' has too many statements (3). Maximum allowed is 2." }]
        },
        {
            code: "var foo = () => { var bar = 1; var baz = 2; var qux = 3; };",
            options: [2],
            parserOptions: { ecmaVersion: 6 },
            errors: [{ message: "Arrow function has too many statements (3). Maximum allowed is 2." }]
        },
        {
            code: "var foo = function() { var bar = 1; var baz = 2; var qux = 3; };",
            options: [2],
            errors: [{ message: "Function has too many statements (3). Maximum allowed is 2." }]
        },
        {
            code: "function foo() { var bar = 1; if (true) { while (false) { var qux = null; } } return 3; }",
            options: [4],
            errors: [{ message: "Function 'foo' has too many statements (5). Maximum allowed is 4." }]
        },
        {
            code: "function foo() { var bar = 1; if (true) { for (;;) { var qux = null; } } return 3; }",
            options: [4],
            errors: [{ message: "Function 'foo' has too many statements (5). Maximum allowed is 4." }]
        },
        {
            code: "function foo() { var bar = 1; if (true) { for (;;) { var qux = null; } } else { quxx(); } return 3; }",
            options: [5],
            errors: [{ message: "Function 'foo' has too many statements (6). Maximum allowed is 5." }]
        },
        {
            code: "function foo() { var x = 5; function bar() { var y = 6; } bar(); z = 10; baz(); }",
            options: [3],
            errors: [{ message: "Function 'foo' has too many statements (5). Maximum allowed is 3." }]
        },
        {
            code: "function foo() { var x = 5; function bar() { var y = 6; } bar(); z = 10; baz(); }",
            options: [4],
            errors: [{ message: "Function 'foo' has too many statements (5). Maximum allowed is 4." }]
        },
        {
            code: ";(function() { var bar = 1; return function () { var z; return 42; }; })()",
            options: [1, { ignoreTopLevelFunctions: true }],
            errors: [{ message: "Function has too many statements (2). Maximum allowed is 1." }]
        },
        {
            code: ";(function() { var bar = 1; var baz = 2; })(); (function() { var bar = 1; var baz = 2; })()",
            options: [1, { ignoreTopLevelFunctions: true }],
            errors: [
                { message: "Function has too many statements (2). Maximum allowed is 1." },
                { message: "Function has too many statements (2). Maximum allowed is 1." }
            ]
        },
        {
            code: "define(['foo', 'qux'], function(foo, qux) { var bar = 1; var baz = 2; return function () { var z; return 42; }; })",
            options: [1, { ignoreTopLevelFunctions: true }],
            errors: [{ message: "Function has too many statements (2). Maximum allowed is 1." }]
        },
        {
            code: "function foo() { var a; var b; var c; var x; var y; var z; bar(); baz(); qux(); quxx(); foo(); }",
            errors: [{ message: "Function 'foo' has too many statements (11). Maximum allowed is 10." }]
        },

        // object property options
        {
            code: "var foo = { thing: function() { var bar = 1; var baz = 2; var baz2; } }",
            options: [2],
            errors: [{ message: "Method 'thing' has too many statements (3). Maximum allowed is 2." }]
        },
        {
            code: "var foo = { thing() { var bar = 1; var baz = 2; var baz2; } }",
            options: [2],
            parserOptions: { ecmaVersion: 6 },
            errors: [{ message: "Method 'thing' has too many statements (3). Maximum allowed is 2." }]
        },

        /*
         * TODO decide if we want this or not
         * {
         *     code: "var foo = { ['thing']() { var bar = 1; var baz = 2; var baz2; } }",
         *     options: [2],
         *     parserOptions: { ecmaVersion: 6 },
         *     errors: [{ message: "Method ''thing'' has too many statements (3). Maximum allowed is 2." }]
         * },
         */

        {
            code: "var foo = { thing: () => { var bar = 1; var baz = 2; var baz2; } }",
            options: [2],
            parserOptions: { ecmaVersion: 6 },
            errors: [{ message: "Arrow function 'thing' has too many statements (3). Maximum allowed is 2." }]
        },
        {
            code: "var foo = { thing: function() { var bar = 1; var baz = 2; var baz2; } }",
            options: [{ max: 2 }],
            errors: [{ message: "Method 'thing' has too many statements (3). Maximum allowed is 2." }]
        }
    ]
});


text:
package de.unioninvestment.eai.portal.portlet.crud.export;

import com.vaadin.server.StreamResource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Link;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Notification.Type;
import com.vaadin.ui.ProgressBar;
import com.vaadin.ui.Table;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.LiferayTheme;

import de.unioninvestment.eai.portal.support.vaadin.context.Context;

/**
 * Modaler Dialog, der beim Export einen Fortschrittsbalken anzeigt und die
 * Möglichkeit zum Abbruch bietet.
 *
 * Im IE7/IE8 verhindert eine Sicherheitsabfrage den automatischen Download nach
 * Beendigung, daher wird hier ein separater Button angeboten und der Dialog
 * muss händisch geschlossen werden.
 *
 * @author carsten.mjartan
 */
public class ExportDialog extends Window implements ExportFrontend {
	private static final long serialVersionUID = 1L;

	private final ExportTask exportTask;

	private ProgressBar indicator;

	private final Table table;

	private boolean automaticDownload = true;

	private Link downloadLink;

	/**
	 * Initialisierung des Dialogs inkl. Widgets
	 *
	 * @param table
	 *            die Tabelle, die nach Schließen des Dialogs zu reaktivieren
	 *            ist.
	 * @param exportTask
	 *            der Hintergrund-Task
	 */
	public ExportDialog(Table table, ExportTask exportTask,
			boolean automaticDownload) {
		this.table = table;
		this.exportTask = exportTask;
		this.automaticDownload = automaticDownload;

		init();

		exportTask.setFrontend(this);
	}

	@SuppressWarnings("serial")
	private void init() {
		setCaption(Context.getMessage("portlet.crud.dialog.export.title"));
		setModal(true);
		setResizable(false);
		setWidth("400px");
		addCloseListener(new CloseListener() {
			@Override
			public void windowClose(CloseEvent e) {
				handleWindowCloseEvent();
			}
		});

		indicator = new ProgressBar(0.0f);
		indicator.setWidth("100%");
		UI.getCurrent().setPollInterval(1000);

		if (automaticDownload) {
			VerticalLayout layout = new VerticalLayout();
			layout.setMargin(true);
			layout.addComponent(indicator);

			setContent(layout);
		} else {
			HorizontalLayout layout = new HorizontalLayout();
			layout.setWidth("100%");
			layout.setMargin(true);
			layout.setSpacing(true);

			downloadLink = new Link();
			downloadLink.setStyleName(LiferayTheme.BUTTON_LINK);
			downloadLink
					.setCaption(Context.getMessage("portlet.crud.dialog.export.download"));
			downloadLink.setEnabled(false);

			layout.addComponents(indicator, downloadLink);
			layout.setComponentAlignment(indicator, Alignment.MIDDLE_CENTER);
			layout.setComponentAlignment(downloadLink, Alignment.MIDDLE_CENTER);
			layout.setExpandRatio(indicator, 1f);

			setContent(layout);
		}

	}

	protected void handleWindowCloseEvent() {
		UI.getCurrent().setPollInterval(-1);
		if (!exportTask.isFinished()) {
			exportTask.cancel();
		}
		table.setEnabled(true);
	}

	@Override
	public void updateProgress(float progress) {
		indicator.setValue(progress);
	}

	@Override
	public void finished() {
		startDownloadAndCloseDialog("_blank");
	}

	@Override
	public void finished(StreamResource resource) {
		downloadLink.setResource(resource);
		downloadLink.setEnabled(true);
	}

	private void startDownloadAndCloseDialog(String targetWindow) {
		ExportDialog.this.exportTask.sendToClient(targetWindow);
		close();
		// table.getApplication().getMainWindow().requestRepaint();
	}

	@Override
	public void handleException(final Exception e) {
		displayErrorMessage(e);
		close();
	}

	private void displayErrorMessage(final Exception e) {
		Notification.show(e.getMessage(), Type.ERROR_MESSAGE);
	}

	/**
	 * @return indicator for testing
	 */
	ProgressBar getIndicator() {
		return indicator;
	}

}


text:
package org.apache.ignite.internal.visor.query;

import java.util.List;
import org.apache.ignite.IgniteException;
import org.apache.ignite.compute.ComputeJobResult;
import org.apache.ignite.internal.QueryMXBeanImpl;
import org.apache.ignite.internal.processors.task.GridInternal;
import org.apache.ignite.internal.processors.task.GridVisorManagementTask;
import org.apache.ignite.internal.visor.VisorJob;
import org.apache.ignite.internal.visor.VisorOneNodeTask;
import org.jetbrains.annotations.Nullable;

/**
 * Task to cancel queries on initiator node.
 */
@GridInternal
@GridVisorManagementTask
public class VisorQueryCancelOnInitiatorTask extends VisorOneNodeTask<VisorQueryCancelOnInitiatorTaskArg, Void> {
    /** */
    private static final long serialVersionUID = 0L;

    /** {@inheritDoc} */
    @Override protected VisorCancelQueryOnInitiatorJob job(VisorQueryCancelOnInitiatorTaskArg arg) {
        return new VisorCancelQueryOnInitiatorJob(arg, debug);
    }

    /** {@inheritDoc} */
    @Nullable @Override protected Void reduce0(List<ComputeJobResult> results) throws IgniteException {
        return null;
    }

    /** Job to cancel query on node. */
    private static class VisorCancelQueryOnInitiatorJob extends VisorJob<VisorQueryCancelOnInitiatorTaskArg, Void> {
        /** */
        private static final long serialVersionUID = 0L;

        /**
         * Create job with specified argument.
         *
         * @param arg Job argument.
         * @param debug Flag indicating whether debug information should be printed into node log.
         */
        protected VisorCancelQueryOnInitiatorJob(VisorQueryCancelOnInitiatorTaskArg arg, boolean debug) {
            super(arg, debug);
        }

        /** {@inheritDoc} */
        @Override protected Void run(VisorQueryCancelOnInitiatorTaskArg arg) throws IgniteException {
            new QueryMXBeanImpl(ignite.context()).cancelSQL(arg.getNodeId(), arg.getQueryId());

            return null;
        }
    }
}


text:
<?php

/**
 * Displays a list of blog posts by tag.
 */

$page->id = 'blog';
$page->layout = $appconf['Blog']['layout'];

require_once ('apps/blog/lib/Filters.php');

$preview_chars = (int) Appconf::blog('Blog', 'preview_chars') ? (int) Appconf::blog('Blog', 'preview_chars') : false;

$page->limit = 10;
$page->tag = urldecode ($this->params[0]);
if (! $page->tag) {
	$this->redirect ('/blog');
}
$page->num = (count ($this->params) > 1 && is_numeric ($this->params[1])) ? $this->params[1] - 1 : 0;
$page->offset = $page->num * $page->limit;

$p = new blog\Post;
$posts = $p->tagged ($page->tag, $page->limit, $page->offset);
$page->count = $p->count_by_tag ($page->tag);
$page->last = $page->offset + count ($posts);
$page->more = ($page->count > $page->last) ? true : false;
$page->next = $page->num + 2;

$footer = Appconf::blog ('Blog', 'post_footer');
$footer_stripped = strip_tags ($footer);
$footer = ($footer && ! empty ($footer_stripped))
	? $tpl->run_includes ($footer)
	: false;

if (Appconf::blog ('Blog', 'post_format') === 'markdown') {
	require_once ('apps/blog/lib/markdown.php');
}

foreach ($posts as $post) {
	$post->url = '/blog/post/' . $post->id . '/' . URLify::filter ($post->title);
	$post->tag_list = (strlen ($post->tags) > 0) ? explode (',', $post->tags) : array ();
	$post->social_buttons = $appconf['Social Buttons'];
	if (Appconf::blog ('Blog', 'post_format') === 'html') {
		$post->body = $tpl->run_includes ($post->body);
	} else {
		$post->body = $tpl->run_includes (Markdown ($post->body));
	}
	if ($preview_chars) {
		$post->body = blog_filter_truncate ($post->body, $preview_chars)
			. ' url . '">' . __ ('Read more') . '';
	} else {
		$post->footer = $footer;
	}
	echo $tpl->render ('blog/post', $post);
}

$page->title = __ ('Tagged: %s', $tpl->sanitize ($page->tag));

$page->add_script (sprintf (
	'<link rel="alternate" type="application/rss+xml" href="http://%s/blog/rss" />',
	$_SERVER['HTTP_HOST']
));

echo $tpl->render ('blog/tag', $page);


text:
package org.apache.ignite.internal.processors.cache;

import org.apache.ignite.configuration.*;

/**
 *
 */
public class IgniteCacheTxNearEnabledInvokeTest extends IgniteCacheTxInvokeTest {
    /** {@inheritDoc} */
    @Override protected NearCacheConfiguration nearConfiguration() {
        return new NearCacheConfiguration();
    }
}


text:
**SPATIAL**
   *|adjective*

 of or relating to space and the relationship of objects within it