text:
package org.broadinstitute.hellbender.engine;

import org.broadinstitute.hellbender.GATKBaseTest;
import org.broadinstitute.hellbender.exceptions.GATKException;
import org.broadinstitute.hellbender.utils.SimpleInterval;
import org.broadinstitute.hellbender.utils.io.IOUtils;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.internal.junit.ArrayAsserts;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public final class ReferenceContextUnitTest extends GATKBaseTest {

    private static final Path TEST_REFERENCE = IOUtils.getPath(hg19MiniReference);

    @DataProvider(name = "EmptyReferenceContextDataProvider")
    public Object[][] getEmptyReferenceContextData() {
        // Default-constructed ReferenceContexts and ReferenceContexts constructed from null ReferenceDataSources
        // and/or null intervals should behave as empty context objects.
        return new Object[][] {
                { new ReferenceContext() },
                { new ReferenceContext(null, null, 0, 0) },
                { new ReferenceContext(null, new SimpleInterval("1", 1, 1), 0, 0 ) },
                { new ReferenceContext(new ReferenceFileSource(TEST_REFERENCE), null) }
        };
    }

    @Test(dataProvider = "EmptyReferenceContextDataProvider")
    public void testEmptyReferenceContext( final ReferenceContext refContext) {
        Assert.assertFalse(refContext.hasBackingDataSource() && refContext.getInterval() != null,
                           "Empty ReferenceContext reports having both a backing data source and an interval");
        Assert.assertEquals(refContext.getBases().length, 0, "Empty ReferenceContext should have returned an empty bases array from getBases()");
        Assert.assertFalse(refContext.iterator().hasNext(), "Empty ReferenceContext should have returned an empty bases iterator from iterator()");
    }

    @DataProvider(name = "WindowlessReferenceIntervalDataProvider")
    public Object[][] getWindowlessReferenceIntervals() {
        return new Object[][] {
                { new SimpleInterval("1", 1, 3), "NNN" },
                { new SimpleInterval("1", 11041, 11045), "GCAAA" },
                { new SimpleInterval("1", 11210, 11220), "CGGTGCTGTGC" },
                { new SimpleInterval("2", 9995, 10005), "NNNNNNCGTAT" },
                { new SimpleInterval("2", 10001, 10080), "CGTATCCCACACACCACACCCACACACCACACCCACACACACCCACACCCACACCCACACACACCACACCCACACACCAC" },
                { new SimpleInterval("2", 10005, 10084), "TCCCACACACCACACCCACACACCACACCCACACACACCCACACCCACACCCACACACACCACACCCACACACCACACCC" },
                { new SimpleInterval("2", 15995, 16000), "TGTCAG" }
        };
    }

    @Test(dataProvider = "WindowlessReferenceIntervalDataProvider")
    public void testWindowlessReferenceContext( final SimpleInterval interval, final String expectedBases ) {
        try (ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE)) {
            ReferenceContext refContext = new ReferenceContext(reference, interval);

            checkReferenceContextBases(refContext, expectedBases);
            Assert.assertEquals(refContext.getInterval(), interval, "Wrong interval in reference context");
            Assert.assertEquals(refContext.getWindow(), interval, "Window in windowless reference context not equal to original interval");
            Assert.assertEquals(refContext.numWindowLeadingBases(), 0, "Non-zero leading window size in windowless reference context");
            Assert.assertEquals(refContext.numWindowTrailingBases(), 0, "Non-zero trailing window size in windowless reference context");
        }
    }

    @DataProvider(name = "WindowedReferenceIntervalDataProvider")
    public Object[][] getWindowedReferenceIntervals() {
        return new Object[][] {
                // Window off the start of the contig:
                { new SimpleInterval("1", 1, 3), 5, 5, new SimpleInterval("1", 1, 8), "NNNNNNNN" },
                // Window in middle of contig with equal, non-zero start and stop offsets
                { new SimpleInterval("1", 11041, 11045), 5, 5, new SimpleInterval("1", 11036, 11050), "CAGGAGCAAAGTCGC" },
                // Window in middle of contig with start offset only
                { new SimpleInterval("1", 11210, 11220), 3, 0, new SimpleInterval("1", 11207, 11220), "TCACGGTGCTGTGC" },
                // Window in middle of contig with stop offset only
                { new SimpleInterval("2", 9995, 10005), 0, 3, new SimpleInterval("2", 9995, 10008), "NNNNNNCGTATCCC" },
                // Window in middle of contig with unequal, non-zero start and stop offsets
                { new SimpleInterval("2", 10005, 10084), 3, 8, new SimpleInterval("2", 10002, 10092), "GTATCCCACACACCACACCCACACACCACACCCACACACACCCACACCCACACCCACACACACCACACCCACACACCACACCCACACCCAC" },
                // Window off the end of the contig
                { new SimpleInterval("2", 15995, 16000), 2, 5, new SimpleInterval("2", 15993, 16000), "TGTGTCAG" }
        };
    }

    @Test(dataProvider = "WindowedReferenceIntervalDataProvider")
    public void testWindowedContext( final SimpleInterval interval, final int windowStartOffset, final int windowStopOffset, final SimpleInterval expectedWindow, final String expectedBases ) {
        try (ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE)) {
            ReferenceContext refContext = new ReferenceContext(reference, interval, windowStartOffset, windowStopOffset);

            checkReferenceContextBases(refContext, expectedBases);
            Assert.assertEquals(refContext.getInterval(), interval, "Wrong interval in reference context");
            Assert.assertEquals(refContext.getWindow(), expectedWindow, "Window in windowed reference context not equal to expected window");
            Assert.assertEquals(refContext.numWindowLeadingBases(), interval.getStart() - expectedWindow.getStart(),
                    "Leading window size in windowed reference context not equal to expected value");
            Assert.assertEquals(refContext.numWindowTrailingBases(), 0, expectedWindow.getEnd() - interval.getEnd(),
                    "Trailing window size in windowed reference context not equal to expected value");
        }
    }

    @Test(dataProvider = "WindowedReferenceIntervalDataProvider")
    public void testWindowedContextUsingIntervalObjects( final SimpleInterval interval, final int windowStartOffset, final int windowStopOffset, final SimpleInterval expectedWindow, final String expectedBases ) {
        try (ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE)) {
            ReferenceContext refContext = new ReferenceContext(reference, interval, expectedWindow);

            checkReferenceContextBases(refContext, expectedBases);
            Assert.assertEquals(refContext.getInterval(), interval, "Wrong interval in reference context");
            Assert.assertEquals(refContext.getWindow(), expectedWindow, "Window in windowed reference context not equal to expected window");
            Assert.assertEquals(refContext.numWindowLeadingBases(), interval.getStart() - expectedWindow.getStart(),
                    "Leading window size in windowed reference context not equal to expected value");
            Assert.assertEquals(refContext.numWindowTrailingBases(), 0, expectedWindow.getEnd() - interval.getEnd(),
                    "Trailing window size in windowed reference context not equal to expected value");
        }
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void testNullIntervalAndNonNullWindow() {
        try (ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE)) {
            new ReferenceContext(reference, null, new SimpleInterval("1", 1, 3));
        }
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void testIntervalNotInWindow() {
        try (ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE)) {
            new ReferenceContext(reference, new SimpleInterval("1", 1, 3), new SimpleInterval("1", 10, 30));
        }
    }

    @Test
    public void testWindowedContextUsingIntervalObjects_nullWindow() {
        try (ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE)) {
            final SimpleInterval ival = new SimpleInterval("1", 1, 3);
            final ReferenceContext refContext = new ReferenceContext(reference, ival, null);
            Assert.assertEquals(refContext.getWindow(), ival);
            Assert.assertEquals(refContext.getInterval(), ival);
        }
    }

    @Test
    public void testDynamicallyChangingWindow() {
        try (final ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE)) {
            final SimpleInterval interval = new SimpleInterval("1", 11210, 11220);
            final ReferenceContext refContext = new ReferenceContext(reference, interval);
            final String intervalBases = "CGGTGCTGTGC";

            Assert.assertEquals(interval, refContext.getWindow());
            Assert.assertEquals(refContext.numWindowLeadingBases(), 0);
            Assert.assertEquals(refContext.numWindowTrailingBases(), 0);
            checkReferenceContextBases(refContext, intervalBases);
            Assert.assertEquals(refContext.getBase(), intervalBases.getBytes()[0]);
            Assert.assertEquals(refContext.getForwardBases(), intervalBases.getBytes());

            refContext.setWindow(5, 5);
            Assert.assertEquals(refContext.getWindow(), new SimpleInterval(interval.getContig(), interval.getStart() - 5, interval.getEnd() + 5));
            Assert.assertEquals(refContext.numWindowLeadingBases(), 5);
            Assert.assertEquals(refContext.numWindowTrailingBases(), 5);
            checkReferenceContextBases(refContext, "GCTCA" + intervalBases + "CAGGG");
            Assert.assertEquals(refContext.getBase(), intervalBases.getBytes()[0]);
            Assert.assertEquals(refContext.getForwardBases(), (intervalBases+"CAGGG").getBytes());

            refContext.setWindow(0, 10);
            Assert.assertEquals(refContext.getWindow(), new SimpleInterval(interval.getContig(), interval.getStart(), interval.getEnd() + 10));
            Assert.assertEquals(refContext.numWindowLeadingBases(), 0);
            Assert.assertEquals(refContext.numWindowTrailingBases(), 10);
            checkReferenceContextBases(refContext, intervalBases + "CAGGGCGCCC");
            Assert.assertEquals(refContext.getBase(), intervalBases.getBytes()[0]);
            Assert.assertEquals(refContext.getForwardBases(), (intervalBases+"CAGGGCGCCC").getBytes());

            refContext.setWindow(20, 3);
            Assert.assertEquals(refContext.getWindow(), new SimpleInterval(interval.getContig(), interval.getStart() - 20, interval.getEnd() + 3));
            Assert.assertEquals(refContext.numWindowLeadingBases(), 20);
            Assert.assertEquals(refContext.numWindowTrailingBases(), 3);
            checkReferenceContextBases(refContext, "CTACAGGACCCGCTTGCTCA" + intervalBases + "CAG");
            Assert.assertEquals(refContext.getBase(), intervalBases.getBytes()[0]);
            Assert.assertEquals(refContext.getForwardBases(), (intervalBases+"CAG").getBytes());

            refContext.setWindow(0, 0);
            Assert.assertEquals(interval, refContext.getWindow());
            Assert.assertEquals(refContext.numWindowLeadingBases(), 0);
            Assert.assertEquals(refContext.numWindowTrailingBases(), 0);
            checkReferenceContextBases(refContext, intervalBases);
            Assert.assertEquals(refContext.getBase(), intervalBases.getBytes()[0]);
            Assert.assertEquals(refContext.getForwardBases(), intervalBases.getBytes());
        }
    }

    @Test
    public void testGetBasesStaticWindow() {
        try (final ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE)) {
            final SimpleInterval interval = new SimpleInterval("1", 11210, 11220);
            final ReferenceContext refContext = new ReferenceContext(reference, interval);
            final String intervalBases = "CGGTGCTGTGC";

            checkReferenceContextBasesFromInterval(refContext, intervalBases, interval);
            Assert.assertEquals(refContext.getWindow(), interval);

            checkReferenceContextBasesFromInterval(refContext, "GCTCA" + intervalBases + "CAGGG",
                    new SimpleInterval(interval.getContig(), interval.getStart() - 5, interval.getEnd() + 5)
            );
            Assert.assertEquals(refContext.getWindow(), interval);

            checkReferenceContextBasesFromInterval(refContext, intervalBases + "CAGGGCGCCC",
                    new SimpleInterval(interval.getContig(), interval.getStart() - 0, interval.getEnd() + 10)
            );
            Assert.assertEquals(refContext.getWindow(), interval);

            checkReferenceContextBasesFromInterval(refContext, "CTACAGGACCCGCTTGCTCA" + intervalBases + "CAG",
                    new SimpleInterval(interval.getContig(), interval.getStart() - 20, interval.getEnd() + 3)
            );
            Assert.assertEquals(refContext.getWindow(), interval);
        }
    }

    @DataProvider
    private Object[][] provideForTestCopyConstructor() {
        return new Object[][] {
                {
                        new SimpleInterval("1", 11210, 11220),
                        new SimpleInterval("1", 2650, 2650),
                        0,
                        0
                },
                {
                        new SimpleInterval("1", 11210, 11220),
                        new SimpleInterval("1", 2650, 2650),
                        3,
                        5
                },
                {
                        new SimpleInterval("1", 11210, 11220),
                        new SimpleInterval("1", 2640, 2650),
                        0,
                        0
                },
                {
                        new SimpleInterval("1", 11210, 11220),
                        new SimpleInterval("1", 2640, 2650),
                        3,
                        5
                },
                {
                        new SimpleInterval("1", 11210, 11220),
                        new SimpleInterval("2", 2650, 2650),
                        3,
                        5
                },
                {
                        new SimpleInterval("1", 11210, 11220),
                        new SimpleInterval("2", 2650, 2650),
                        0,
                        0
                },
                {
                        new SimpleInterval("1", 11210, 11220),
                        new SimpleInterval("2", 2650, 2660),
                        3,
                        5
                },
                {
                        new SimpleInterval("1", 11210, 11220),
                        new SimpleInterval("2", 2650, 2660),
                        0,
                        0
                },
        };
    }

    @Test(dataProvider = "provideForTestCopyConstructor")
    public void testCopyConstructor(final SimpleInterval originalInterval, final SimpleInterval newInterval, final int leadingBases, final int trailingBases) {
        try (final ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE)) {

            final ReferenceContext refContext = new ReferenceContext(reference, originalInterval, leadingBases, trailingBases);
            Assert.assertEquals(refContext.getInterval(), originalInterval, "Set interval is different from expected interval!");

            final ReferenceContext newRefContext = new ReferenceContext(refContext, newInterval);
            Assert.assertEquals(newRefContext.getInterval(), newInterval, "Set interval is different from expected interval!");

            final SimpleInterval newWindow = newRefContext.getWindow();

            final int newLeadingBases = newInterval.getStart() - newWindow.getStart();
            final int newTrailingBases = newWindow.getEnd() - newInterval.getEnd();

            Assert.assertEquals(newLeadingBases, leadingBases, "New window leading bases are not the same as old window leading bases!");
            Assert.assertEquals(newTrailingBases, trailingBases, "New window trailing bases are not the same as old window trailing bases!");
        }
    }

    private void checkReferenceContextBases( final ReferenceContext refContext, final String expectedBases ) {

        final byte[] contextBases = refContext.getBases();

        final List<Byte> contextBasesFromIterator = new ArrayList<>();
        final Iterator<Byte> baseIterator = refContext.iterator();
        while ( baseIterator.hasNext() ) {
            contextBasesFromIterator.add(baseIterator.next());
        }

        Assert.assertEquals(contextBases.length, expectedBases.length(), "Wrong number of bases from refContext.getBases()");

        final byte[] expectedBasesByteArray = expectedBases.getBytes();
        for ( int baseIndex = 0; baseIndex < expectedBases.length(); ++baseIndex ) {
            Assert.assertEquals(contextBases[baseIndex], expectedBasesByteArray[baseIndex], "Base #" + (baseIndex + 1) + " incorrect from refContext.getBases()");
            Assert.assertEquals(contextBasesFromIterator.get(baseIndex).byteValue(), expectedBasesByteArray[baseIndex], "Base #" + (baseIndex + 1) + " incorrect from refContext.iterator()");
        }
    }

    private void checkReferenceContextBasesFromInterval( final ReferenceContext refContext, final String expectedBases, final SimpleInterval interval ) {

        // Do this once for the interval-based call:
        final byte[] contextBases = refContext.getBases(interval);
        checkReferenceContextBasesFromIntervalHelper(expectedBases, contextBases);

        // Do this again for the leading/trailing bounds-based call:
        final byte[] contextBases2 = refContext.getBases(interval);

        // First check that the two context bases are the same:
        Assert.assertEquals(contextBases2, contextBases);

        // Now check vs the expected values:
        checkReferenceContextBasesFromIntervalHelper(expectedBases, contextBases2);
    }

    private void checkReferenceContextBasesFromIntervalHelper(final String expectedBases, final byte[] contextBases) {
        Assert.assertEquals(contextBases.length, expectedBases.length(), "Wrong number of bases from refContext.getBases()");

        final byte[] expectedBasesByteArray = expectedBases.getBytes();
        for ( int baseIndex = 0; baseIndex < expectedBases.length(); ++baseIndex ) {
            Assert.assertEquals(contextBases[baseIndex], expectedBasesByteArray[baseIndex], "Base #" + (baseIndex + 1) + " incorrect from refContext.getBases()");
        }
    }

    @DataProvider(name = "InvalidWindowDataProvider")
    public Object[][] getInvalidWindows() {
        return new Object[][] {
                // window start offset < 0
                {-1, 1},
                // window stop offset < 0
                {1, -1},
                // window start offset < 0 && window stop offset < 0
                {-1, -1}
        };
    }

    @Test(dataProvider = "InvalidWindowDataProvider", expectedExceptions = GATKException.class)
    public void testInvalidWindowHandlingAtConstruction( final int windowStartOffset, final int windowStopOffset ) {
        try ( ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE) ) {
            SimpleInterval interval = new SimpleInterval("1", 5, 10);
            ReferenceContext refContext = new ReferenceContext(reference, interval, windowStartOffset, windowStopOffset);
        }
    }

    @Test(dataProvider = "InvalidWindowDataProvider", expectedExceptions = GATKException.class)
    public void testInvalidWindowHandlingPostConstruction( final int windowStartOffset, final int windowStopOffset ) {
        try ( ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE) ) {
            SimpleInterval interval = new SimpleInterval("1", 5, 10);
            ReferenceContext refContext = new ReferenceContext(reference, interval);
            refContext.setWindow(windowStartOffset, windowStopOffset);
        }
    }

    @DataProvider(name = "SubintervalDataProvider")
    public Object[][] getSubintervals() {
        return new Object[][] {
                // start (1120x):   01234567890
                // reference bases: CGGTGCTGTGC
                {"1", 11211, 1, "CGG"},
                {"1", 11219, 1, "TGC"},
                {"1", 11217, 2, "CTGTG"}
        };
    }

    @Test(dataProvider = "SubintervalDataProvider")
    public void testGetKmerAround(final String contig, final int start, final int padding, String expectedSubsequence){
        // the interval of a ReferenceContext object is *in*clusive on both ends
        try (final ReferenceDataSource reference = new ReferenceFileSource(TEST_REFERENCE)) {
            final SimpleInterval interval = new SimpleInterval(contig, start, start);
            final ReferenceContext refContext = new ReferenceContext(reference, interval);
            final String kmer = refContext.getKmerAround(start, padding);
            Assert.assertEquals(kmer, expectedSubsequence);
        }
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package arbolbjava;

/**
 *
 * @author RickAg
 */
public class TreeNode {

    private int leftKey;
    private int rightKey;
    private TreeNode leftBranch;
    private TreeNode middleBranch;
    private TreeNode rightBranch;
    private TreeNode father;

    public TreeNode() {
        leftKey = -1;
        rightKey = -1;
        leftBranch = null;
        rightBranch = null;
        middleBranch = null;
        father = null;
    }

    public TreeNode(TreeNode father) {
        leftKey = -1;
        rightKey = -1;
        leftBranch = null;
        rightBranch = null;
        middleBranch = null;
        father = father;
    }

    public TreeNode(int leftKey, int rightKey, TreeNode father) {
        this.leftKey = leftKey;
        this.rightKey = rightKey;
        this.father = father;
        leftBranch = null;
        rightBranch = null;
        middleBranch = null;
    }

    public TreeNode(int leftKey, TreeNode father) {
        this.leftKey = leftKey;
        this.rightKey = -1;
        this.father = father;
        leftBranch = null;
        rightBranch = null;
        middleBranch = null;
    }

    public TreeNode(int leftKey) {
        this.leftKey = leftKey;
        rightKey = -1;
        leftBranch = null;
        rightBranch = null;
        middleBranch = null;
        father = null;
    }

    public int getLeftKey() {
        return leftKey;
    }

    public void setLeftKey(int leftKey) {
        this.leftKey = leftKey;
    }

    public int getRightKey() {
        return rightKey;
    }

    public void setRightKey(int rightKey) {
        this.rightKey = rightKey;
    }

    public TreeNode getLeftBranch() {
        return leftBranch;
    }

    public void setLeftBranch(TreeNode leftBranch) {
        this.leftBranch = leftBranch;
    }

    public TreeNode getMiddleBranch() {
        return middleBranch;
    }

    public void setMiddleBranch(TreeNode middleBranch) {
        this.middleBranch = middleBranch;
    }

    public TreeNode getRightBranch() {
        return rightBranch;
    }

    public void setRightBranch(TreeNode rightBranch) {
        this.rightBranch = rightBranch;
    }

    public TreeNode getFather() {
        return father;
    }

    public void setFather(TreeNode father) {
        this.father = father;
    }

    boolean isLeaf() {
//        if (leftBranch.getLeftBranch() == null && leftBranch.getMiddleBranch() == null && leftBranch.getRightBranch() == null &&
//                middleBranch.getLeftBranch() == null && middleBranch.getMiddleBranch() == null && middleBranch.getRightBranch() == null &&
//                rightBranch.getLeftBranch() == null && rightBranch.getMiddleBranch() == null && rightBranch.getRightBranch() == null){
//            return true;
//        }
        if (leftBranch == null && middleBranch == null && rightBranch == null) {
            return true;
        }
        return false;
    }

    boolean isFull() {
        if (leftKey != -1 && rightKey != -1) {
            return true;
        }
        return false;
    }

    boolean leftEmpty() {
        if (leftKey != -1) {
            return false;
        }
        return true;
    }

    boolean rightEmpty() {
        if (rightKey != -1) {
            return false;
        }
        return true;
    }

    @Override
    public String toString(){
        return "Izquierdo: "+leftKey + " Derecho: "+rightKey;
    }
}

redpajama_set_name: RedPajamaGithub


text:
START_ATF_NAMESPACE
    namespace Detail
    {
        Info::CNetSocketAccept_Client2_ptr CNetSocketAccept_Client2_next(nullptr);
        Info::CNetSocketAccept_Client2_clbk CNetSocketAccept_Client2_user(nullptr);

        Info::CNetSocketAccept_Server4_ptr CNetSocketAccept_Server4_next(nullptr);
        Info::CNetSocketAccept_Server4_clbk CNetSocketAccept_Server4_user(nullptr);

        Info::CNetSocketctor_CNetSocket6_ptr CNetSocketctor_CNetSocket6_next(nullptr);
        Info::CNetSocketctor_CNetSocket6_clbk CNetSocketctor_CNetSocket6_user(nullptr);

        Info::CNetSocketCloseAll8_ptr CNetSocketCloseAll8_next(nullptr);
        Info::CNetSocketCloseAll8_clbk CNetSocketCloseAll8_user(nullptr);

        Info::CNetSocketCloseSocket10_ptr CNetSocketCloseSocket10_next(nullptr);
        Info::CNetSocketCloseSocket10_clbk CNetSocketCloseSocket10_user(nullptr);

        Info::CNetSocketConnect12_ptr CNetSocketConnect12_next(nullptr);
        Info::CNetSocketConnect12_clbk CNetSocketConnect12_user(nullptr);

        Info::CNetSocketEmptySocketBuffer14_ptr CNetSocketEmptySocketBuffer14_next(nullptr);
        Info::CNetSocketEmptySocketBuffer14_clbk CNetSocketEmptySocketBuffer14_user(nullptr);

        Info::CNetSocketFindEmptySocket16_ptr CNetSocketFindEmptySocket16_next(nullptr);
        Info::CNetSocketFindEmptySocket16_clbk CNetSocketFindEmptySocket16_user(nullptr);

        Info::CNetSocketGetSocket18_ptr CNetSocketGetSocket18_next(nullptr);
        Info::CNetSocketGetSocket18_clbk CNetSocketGetSocket18_user(nullptr);

        Info::CNetSocketGetSocketIPAddress20_ptr CNetSocketGetSocketIPAddress20_next(nullptr);
        Info::CNetSocketGetSocketIPAddress20_clbk CNetSocketGetSocketIPAddress20_user(nullptr);

        Info::CNetSocketGetSocketType22_ptr CNetSocketGetSocketType22_next(nullptr);
        Info::CNetSocketGetSocketType22_clbk CNetSocketGetSocketType22_user(nullptr);

        Info::CNetSocketGetTotalCount24_ptr CNetSocketGetTotalCount24_next(nullptr);
        Info::CNetSocketGetTotalCount24_clbk CNetSocketGetTotalCount24_user(nullptr);

        Info::CNetSocketInitAcceptSocket26_ptr CNetSocketInitAcceptSocket26_next(nullptr);
        Info::CNetSocketInitAcceptSocket26_clbk CNetSocketInitAcceptSocket26_user(nullptr);

        Info::CNetSocketOnLoop28_ptr CNetSocketOnLoop28_next(nullptr);
        Info::CNetSocketOnLoop28_clbk CNetSocketOnLoop28_user(nullptr);

        Info::CNetSocketPushIPCheckList30_ptr CNetSocketPushIPCheckList30_next(nullptr);
        Info::CNetSocketPushIPCheckList30_clbk CNetSocketPushIPCheckList30_user(nullptr);

        Info::CNetSocketRecv32_ptr CNetSocketRecv32_next(nullptr);
        Info::CNetSocketRecv32_clbk CNetSocketRecv32_user(nullptr);

        Info::CNetSocketRelease34_ptr CNetSocketRelease34_next(nullptr);
        Info::CNetSocketRelease34_clbk CNetSocketRelease34_user(nullptr);

        Info::CNetSocketSend36_ptr CNetSocketSend36_next(nullptr);
        Info::CNetSocketSend36_clbk CNetSocketSend36_user(nullptr);

        Info::CNetSocketSetSocket38_ptr CNetSocketSetSocket38_next(nullptr);
        Info::CNetSocketSetSocket38_clbk CNetSocketSetSocket38_user(nullptr);

        Info::CNetSocketdtor_CNetSocket43_ptr CNetSocketdtor_CNetSocket43_next(nullptr);
        Info::CNetSocketdtor_CNetSocket43_clbk CNetSocketdtor_CNetSocket43_user(nullptr);

        bool CNetSocketAccept_Client2_wrapper(struct CNetSocket* _this, unsigned int dwSocketIndex)
        {
           return CNetSocketAccept_Client2_user(_this, dwSocketIndex, CNetSocketAccept_Client2_next);
        };
        unsigned int CNetSocketAccept_Server4_wrapper(struct CNetSocket* _this)
        {
           return CNetSocketAccept_Server4_user(_this, CNetSocketAccept_Server4_next);
        };

        void CNetSocketctor_CNetSocket6_wrapper(struct CNetSocket* _this)
        {
           CNetSocketctor_CNetSocket6_user(_this, CNetSocketctor_CNetSocket6_next);
        };
        void CNetSocketCloseAll8_wrapper(struct CNetSocket* _this)
        {
           CNetSocketCloseAll8_user(_this, CNetSocketCloseAll8_next);
        };
        bool CNetSocketCloseSocket10_wrapper(struct CNetSocket* _this, unsigned int n)
        {
           return CNetSocketCloseSocket10_user(_this, n, CNetSocketCloseSocket10_next);
        };
        int CNetSocketConnect12_wrapper(struct CNetSocket* _this, unsigned int n, struct sockaddr_in* pAddr)
        {
           return CNetSocketConnect12_user(_this, n, pAddr, CNetSocketConnect12_next);
        };
        void CNetSocketEmptySocketBuffer14_wrapper(struct CNetSocket* _this, unsigned int n)
        {
           CNetSocketEmptySocketBuffer14_user(_this, n, CNetSocketEmptySocketBuffer14_next);
        };
        unsigned int CNetSocketFindEmptySocket16_wrapper(struct CNetSocket* _this)
        {
           return CNetSocketFindEmptySocket16_user(_this, CNetSocketFindEmptySocket16_next);
        };
        struct _socket* CNetSocketGetSocket18_wrapper(struct CNetSocket* _this, unsigned int dwIndex)
        {
           return CNetSocketGetSocket18_user(_this, dwIndex, CNetSocketGetSocket18_next);
        };
        unsigned int CNetSocketGetSocketIPAddress20_wrapper(struct CNetSocket* _this, unsigned int dwIndex)
        {
           return CNetSocketGetSocketIPAddress20_user(_this, dwIndex, CNetSocketGetSocketIPAddress20_next);
        };
        struct _SOCK_TYPE_PARAM* CNetSocketGetSocketType22_wrapper(struct CNetSocket* _this)
        {
           return CNetSocketGetSocketType22_user(_this, CNetSocketGetSocketType22_next);
        };
        struct _total_count* CNetSocketGetTotalCount24_wrapper(struct CNetSocket* _this)
        {
           return CNetSocketGetTotalCount24_user(_this, CNetSocketGetTotalCount24_next);
        };
        bool CNetSocketInitAcceptSocket26_wrapper(struct CNetSocket* _this, char* pszErrMsg)
        {
           return CNetSocketInitAcceptSocket26_user(_this, pszErrMsg, CNetSocketInitAcceptSocket26_next);
        };
        void CNetSocketOnLoop28_wrapper(struct CNetSocket* _this)
        {
           CNetSocketOnLoop28_user(_this, CNetSocketOnLoop28_next);
        };
        bool CNetSocketPushIPCheckList30_wrapper(struct CNetSocket* _this, unsigned int dwIP)
        {
           return CNetSocketPushIPCheckList30_user(_this, dwIP, CNetSocketPushIPCheckList30_next);
        };
        bool CNetSocketRecv32_wrapper(struct CNetSocket* _this, unsigned int n, char* pBuf, int nBufMaxSize, int* pnRet)
        {
           return CNetSocketRecv32_user(_this, n, pBuf, nBufMaxSize, pnRet, CNetSocketRecv32_next);
        };
        void CNetSocketRelease34_wrapper(struct CNetSocket* _this)
        {
           CNetSocketRelease34_user(_this, CNetSocketRelease34_next);
        };
        bool CNetSocketSend36_wrapper(struct CNetSocket* _this, unsigned int n, char* pBuf, int nSize, int* pnRet)
        {
           return CNetSocketSend36_user(_this, n, pBuf, nSize, pnRet, CNetSocketSend36_next);
        };
        bool CNetSocketSetSocket38_wrapper(struct CNetSocket* _this, struct _SOCK_TYPE_PARAM* pType, char* pszErrMsg)
        {
           return CNetSocketSetSocket38_user(_this, pType, pszErrMsg, CNetSocketSetSocket38_next);
        };

        void CNetSocketdtor_CNetSocket43_wrapper(struct CNetSocket* _this)
        {
           CNetSocketdtor_CNetSocket43_user(_this, CNetSocketdtor_CNetSocket43_next);
        };

        ::std::array<hook_record, 20> CNetSocket_functions =
        {
            _hook_record {
                (LPVOID)0x14047e750L,
                (LPVOID *)&CNetSocketAccept_Client2_user,
                (LPVOID *)&CNetSocketAccept_Client2_next,
                (LPVOID)cast_pointer_function(CNetSocketAccept_Client2_wrapper),
                (LPVOID)cast_pointer_function((bool(CNetSocket::*)(unsigned int))&CNetSocket::Accept_Client)
            },
            _hook_record {
                (LPVOID)0x14047e3b0L,
                (LPVOID *)&CNetSocketAccept_Server4_user,
                (LPVOID *)&CNetSocketAccept_Server4_next,
                (LPVOID)cast_pointer_function(CNetSocketAccept_Server4_wrapper),
                (LPVOID)cast_pointer_function((unsigned int(CNetSocket::*)())&CNetSocket::Accept_Server)
            },
            _hook_record {
                (LPVOID)0x14047db60L,
                (LPVOID *)&CNetSocketctor_CNetSocket6_user,
                (LPVOID *)&CNetSocketctor_CNetSocket6_next,
                (LPVOID)cast_pointer_function(CNetSocketctor_CNetSocket6_wrapper),
                (LPVOID)cast_pointer_function((void(CNetSocket::*)())&CNetSocket::ctor_CNetSocket)
            },
            _hook_record {
                (LPVOID)0x14047f060L,
                (LPVOID *)&CNetSocketCloseAll8_user,
                (LPVOID *)&CNetSocketCloseAll8_next,
                (LPVOID)cast_pointer_function(CNetSocketCloseAll8_wrapper),
                (LPVOID)cast_pointer_function((void(CNetSocket::*)())&CNetSocket::CloseAll)
            },
            _hook_record {
                (LPVOID)0x14047ec40L,
                (LPVOID *)&CNetSocketCloseSocket10_user,
                (LPVOID *)&CNetSocketCloseSocket10_next,
                (LPVOID)cast_pointer_function(CNetSocketCloseSocket10_wrapper),
                (LPVOID)cast_pointer_function((bool(CNetSocket::*)(unsigned int))&CNetSocket::CloseSocket)
            },
            _hook_record {
                (LPVOID)0x14047e830L,
                (LPVOID *)&CNetSocketConnect12_user,
                (LPVOID *)&CNetSocketConnect12_next,
                (LPVOID)cast_pointer_function(CNetSocketConnect12_wrapper),
                (LPVOID)cast_pointer_function((int(CNetSocket::*)(unsigned int, struct sockaddr_in*))&CNetSocket::Connect)
            },
            _hook_record {
                (LPVOID)0x14047eb70L,
                (LPVOID *)&CNetSocketEmptySocketBuffer14_user,
                (LPVOID *)&CNetSocketEmptySocketBuffer14_next,
                (LPVOID)cast_pointer_function(CNetSocketEmptySocketBuffer14_wrapper),
                (LPVOID)cast_pointer_function((void(CNetSocket::*)(unsigned int))&CNetSocket::EmptySocketBuffer)
            },
            _hook_record {
                (LPVOID)0x14047f180L,
                (LPVOID *)&CNetSocketFindEmptySocket16_user,
                (LPVOID *)&CNetSocketFindEmptySocket16_next,
                (LPVOID)cast_pointer_function(CNetSocketFindEmptySocket16_wrapper),
                (LPVOID)cast_pointer_function((unsigned int(CNetSocket::*)())&CNetSocket::FindEmptySocket)
            },
            _hook_record {
                (LPVOID)0x14047d3b0L,
                (LPVOID *)&CNetSocketGetSocket18_user,
                (LPVOID *)&CNetSocketGetSocket18_next,
                (LPVOID)cast_pointer_function(CNetSocketGetSocket18_wrapper),
                (LPVOID)cast_pointer_function((struct _socket*(CNetSocket::*)(unsigned int))&CNetSocket::GetSocket)
            },
            _hook_record {
                (LPVOID)0x14047f150L,
                (LPVOID *)&CNetSocketGetSocketIPAddress20_user,
                (LPVOID *)&CNetSocketGetSocketIPAddress20_next,
                (LPVOID)cast_pointer_function(CNetSocketGetSocketIPAddress20_wrapper),
                (LPVOID)cast_pointer_function((unsigned int(CNetSocket::*)(unsigned int))&CNetSocket::GetSocketIPAddress)
            },
            _hook_record {
                (LPVOID)0x14047f110L,
                (LPVOID *)&CNetSocketGetSocketType22_user,
                (LPVOID *)&CNetSocketGetSocketType22_next,
                (LPVOID)cast_pointer_function(CNetSocketGetSocketType22_wrapper),
                (LPVOID)cast_pointer_function((struct _SOCK_TYPE_PARAM*(CNetSocket::*)())&CNetSocket::GetSocketType)
            },
            _hook_record {
                (LPVOID)0x14047f130L,
                (LPVOID *)&CNetSocketGetTotalCount24_user,
                (LPVOID *)&CNetSocketGetTotalCount24_next,
                (LPVOID)cast_pointer_function(CNetSocketGetTotalCount24_wrapper),
                (LPVOID)cast_pointer_function((struct _total_count*(CNetSocket::*)())&CNetSocket::GetTotalCount)
            },
            _hook_record {
                (LPVOID)0x14047ee00L,
                (LPVOID *)&CNetSocketInitAcceptSocket26_user,
                (LPVOID *)&CNetSocketInitAcceptSocket26_next,
                (LPVOID)cast_pointer_function(CNetSocketInitAcceptSocket26_wrapper),
                (LPVOID)cast_pointer_function((bool(CNetSocket::*)(char*))&CNetSocket::InitAcceptSocket)
            },
            _hook_record {
                (LPVOID)0x14047e2b0L,
                (LPVOID *)&CNetSocketOnLoop28_user,
                (LPVOID *)&CNetSocketOnLoop28_next,
                (LPVOID)cast_pointer_function(CNetSocketOnLoop28_wrapper),
                (LPVOID)cast_pointer_function((void(CNetSocket::*)())&CNetSocket::OnLoop)
            },
            _hook_record {
                (LPVOID)0x14047ed20L,
                (LPVOID *)&CNetSocketPushIPCheckList30_user,
                (LPVOID *)&CNetSocketPushIPCheckList30_next,
                (LPVOID)cast_pointer_function(CNetSocketPushIPCheckList30_wrapper),
                (LPVOID)cast_pointer_function((bool(CNetSocket::*)(unsigned int))&CNetSocket::PushIPCheckList)
            },
            _hook_record {
                (LPVOID)0x14047e9c0L,
                (LPVOID *)&CNetSocketRecv32_user,
                (LPVOID *)&CNetSocketRecv32_next,
                (LPVOID)cast_pointer_function(CNetSocketRecv32_wrapper),
                (LPVOID)cast_pointer_function((bool(CNetSocket::*)(unsigned int, char*, int, int*))&CNetSocket::Recv)
            },
            _hook_record {
                (LPVOID)0x14047e140L,
                (LPVOID *)&CNetSocketRelease34_user,
                (LPVOID *)&CNetSocketRelease34_next,
                (LPVOID)cast_pointer_function(CNetSocketRelease34_wrapper),
                (LPVOID)cast_pointer_function((void(CNetSocket::*)())&CNetSocket::Release)
            },
            _hook_record {
                (LPVOID)0x14047ea70L,
                (LPVOID *)&CNetSocketSend36_user,
                (LPVOID *)&CNetSocketSend36_next,
                (LPVOID)cast_pointer_function(CNetSocketSend36_wrapper),
                (LPVOID)cast_pointer_function((bool(CNetSocket::*)(unsigned int, char*, int, int*))&CNetSocket::Send)
            },
            _hook_record {
                (LPVOID)0x14047dda0L,
                (LPVOID *)&CNetSocketSetSocket38_user,
                (LPVOID *)&CNetSocketSetSocket38_next,
                (LPVOID)cast_pointer_function(CNetSocketSetSocket38_wrapper),
                (LPVOID)cast_pointer_function((bool(CNetSocket::*)(struct _SOCK_TYPE_PARAM*, char*))&CNetSocket::SetSocket)
            },
            _hook_record {
                (LPVOID)0x14047dcc0L,
                (LPVOID *)&CNetSocketdtor_CNetSocket43_user,
                (LPVOID *)&CNetSocketdtor_CNetSocket43_next,
                (LPVOID)cast_pointer_function(CNetSocketdtor_CNetSocket43_wrapper),
                (LPVOID)cast_pointer_function((void(CNetSocket::*)())&CNetSocket::dtor_CNetSocket)
            },
        };
    }; // end namespace Detail
END_ATF_NAMESPACE


text:
import React from 'react'
import {Helmet} from 'react-helmet'

export default function Home() {
  return (

    <Helmet>
      <title>Gist.io • Writing for Hackers</title>
    </Helmet>

Gist.io is
Writing for Hackers

There's a scale of permanence to writing on the web. On one end, we have the tweet: brief and ephemeral. On the other end of the scale, we have longform blog writing: unlimited in length and hopefully impervious to the passage of time.

Sometimes, we want to share a bit of writing that is neither. Maybe we want to write for a specific audience, but don't want to address the people who usually read our blogs. Maybe it's just something that doesn't fit into 140 characters.

Gist.io is a solution for that, inspired by Mike Bostock's delightful bl.ocks.org

Usage

Create a gist on GitHub with a single Markdown-syntax file.

In the URL bar, replace

        gist.github.com/youruser/abc123… with

        gist.io/@youruser/abc123….

Enjoy your beautifully-presented writing.

Happy writing!

Idan Gazit

Web / Twitter / GitHub

)
}


text:
import {structureType} from "../_utils";
import {LoopAtScreen} from "../../../src/abap/3_structures/structures";

const cases = [
  {abap: "LOOP AT SCREEN. ENDLOOP."},
  {abap: "LOOP AT SCREEN. WRITE bar. ENDLOOP."},
];

structureType(cases, new LoopAtScreen());


text:
<?php

namespace App\Listeners;

use App\Events\SendMessageToFriendsWhoseBirthday;
use App\Http\Controllers\ReqApiController;
use App\Repositories\UserRepository;

class SendMessageInVk
{
    /**
     * @var ReqApiController
     */
    private $reqApi;

    /**
     * @var UserRepository
     */
    private $userRep;

    /**
     * Create the event listener.
     *
     * @param ReqApiController $reqApiController
     * @param UserRepository   $userRepository
     */
    public function __construct(ReqApiController $reqApiController, UserRepository $userRepository)
    {
        $this->reqApi = $reqApiController;
        $this->userRep = $userRepository;

        $token = $this->userRep->getToken();
        $uid = $this->userRep->getUid();
        $this->reqApi->setup($token, $uid);
    }

    /**
     * Handle the event.
     *
     * @param  SendMessageToFriendsWhoseBirthday $event
     *
     * @return void
     */
    public function handle(SendMessageToFriendsWhoseBirthday $event)
    {
        if ($event->friend['can_post'] == 1) {
            $this->reqApi->sendToWall($event->friend['vk_id'], current($event->message));
        } elseif ($event->friend['can_write_private_message'] == 1) {
            $this->reqApi->sendToPrivate($event->friend['vk_id'], current($event->message));
        }
    }
}


text:
package org.apereo.cas.configuration.model.core.config.cloud;

import org.apereo.cas.configuration.model.RestEndpointProperties;
import org.apereo.cas.configuration.model.support.aws.BaseAmazonWebServicesProperties;
import org.apereo.cas.configuration.model.support.dynamodb.AbstractDynamoDbProperties;
import org.apereo.cas.configuration.support.RequiredProperty;
import org.apereo.cas.configuration.support.RequiresModule;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.io.Serial;
import java.io.Serializable;

/**
 * This is {@link SpringCloudConfigurationProperties}. This class is only designed here
 * to allow the configuration binding logic to recognize the settings. In actuality, the fields
 * listed here are not used directly as they are directly accessed and fetched via the runtime
 * environment to bootstrap cas settings in form of a property source locator, etc.
 *
 * @author Misagh Moayyed
 * @since 5.3.0
 */
@Getter
@Setter
@Accessors(chain = true)
public class SpringCloudConfigurationProperties implements Serializable {
    @Serial
    private static final long serialVersionUID = -2749293768878152908L;

    /**
     * Config config settings.
     */
    private Cloud cloud = new Cloud();

    @Getter
    @Setter
    public static class Cloud implements Serializable {
        @Serial
        private static final long serialVersionUID = -6326706651416825269L;

        /**
         * MongoDb config settings.
         */
        private MongoDb mongo = new MongoDb();

        /**
         * Jdbc config settings.
         */
        private Jdbc jdbc = new Jdbc();

        /**
         * REST config settings.
         */
        private Rest rest = new Rest();

        /**
         * AWS config settings.
         */
        private AmazonWebServicesConfiguration aws = new AmazonWebServicesConfiguration();

        /**
         * AWS DynamoDb config settings.
         */
        private AmazonDynamoDb dynamoDb = new AmazonDynamoDb();
    }

    @RequiresModule(name = "cas-server-support-configuration-cloud-mongo")
    @Getter
    @Setter
    @Accessors(chain = true)
    public static class MongoDb implements Serializable {
        @Serial
        private static final long serialVersionUID = -6509143371334754469L;

        /**
         * Mongodb URI.
         */
        @RequiredProperty
        private String uri;
    }

    @RequiresModule(name = "cas-server-support-configuration-cloud-rest")
    @Getter
    @Accessors(chain = true)
    @Setter
    public static class Rest extends RestEndpointProperties {
        @Serial
        private static final long serialVersionUID = -4509143371334754469L;
    }

    @RequiresModule(name = "cas-server-support-configuration-cloud-jdbc")
    @Getter
    @Accessors(chain = true)
    @Setter
    public static class Jdbc implements Serializable {
        @Serial
        private static final long serialVersionUID = -7575240387340025345L;

        /**
         * SQL statement.
         */
        private String sql;

        /**
         * Database url.
         */
        private String url;

        /**
         * Database user.
         */
        private String user;

        /**
         * Database password.
         */
        private String password;

        /**
         * Driver class name.
         */
        private String driverClass;
    }

    @RequiresModule(name = "cas-server-support-aws")
    @Getter
    @Setter
    @Accessors(chain = true)
    public static class AmazonWebServicesConfiguration implements Serializable {
        @Serial
        private static final long serialVersionUID = -124404249388429120L;

        /**
         * AWS secrets manager settings.
         */
        private AmazonSecretsManager secretsManager = new AmazonSecretsManager();

        /**
         * AWS dynamo db settings.
         */
        private AmazonDynamoDb dynamoDb = new AmazonDynamoDb();

        /**
         * AWS S3 settings.
         */
        private AmazonS3 s3 = new AmazonS3();

        /**
         * AWS SSM settings.
         */
        private AmazonSystemsManagerParameterStore ssm = new AmazonSystemsManagerParameterStore();
    }

    @RequiresModule(name = "cas-server-support-configuration-cloud-aws-secretsmanager")
    @Getter
    @Setter
    @Accessors(chain = true)
    public static class AmazonSecretsManager extends BaseAmazonWebServicesProperties {
        @Serial
        private static final long serialVersionUID = -124404249387429120L;
    }

    @RequiresModule(name = "cas-server-support-configuration-cloud-aws-ssm")
    @Getter
    @Setter
    @Accessors(chain = true)
    public static class AmazonSystemsManagerParameterStore extends BaseAmazonWebServicesProperties {
        @Serial
        private static final long serialVersionUID = -224404249387429120L;
    }

    @RequiresModule(name = "cas-server-support-configuration-cloud-aws-s3")
    @Getter
    @Setter
    @Accessors(chain = true)
    public static class AmazonS3 extends BaseAmazonWebServicesProperties {
        @Serial
        private static final long serialVersionUID = -124404249387429120L;

        /**
         * Bucket name that holds the settings.
         */
        private String bucketName;
    }

    @RequiresModule(name = "cas-server-support-configuration-cloud-dynamodb")
    @Getter
    @Setter
    @Accessors(chain = true)
    public static class AmazonDynamoDb extends AbstractDynamoDbProperties {
        @Serial
        private static final long serialVersionUID = -123404249388429120L;
    }

}


text:
"""Implementation of Cluster Resolvers for Slurm workload manager."""

import os
import re
import subprocess

from tensorflow.python.distribute.cluster_resolver.cluster_resolver import ClusterResolver
from tensorflow.python.distribute.cluster_resolver.cluster_resolver import format_master_url
from tensorflow.python.training.server_lib import ClusterSpec
from tensorflow.python.util.tf_export import tf_export

def expand_hostlist(hostlist):
  """Create a list of hosts out of a SLURM hostlist.

  The order of nodes is preserved and no deduplication is done
  Input: 'n[1-2],m5,o[3-4,6,7-9]')
  Output: ['n1', 'n2', 'm5', 'o3', 'o4', 'o6', 'o7', 'o8', 'o9']
  """

  def split_hostlist(hostlist):
    """Split hostlist at commas outside of range expressions ('[3-5]')."""
    in_brackets = False
    cur_host = ''
    for c in hostlist:
      if in_brackets:
        assert c != '['
        if c == ']':
          in_brackets = False
      elif c == '[':
        in_brackets = True
      elif c == ',':
        assert cur_host != ''
        yield cur_host
        cur_host = ''
        continue
      cur_host += c
    if cur_host:
      yield cur_host

  def expand_range_expression(range_exp):
    """Expand a range expression like '3-5' to values 3,4,5."""
    for part in range_exp.split(','):
      sub_range = part.split('-')
      if len(sub_range) == 1:
        sub_range = sub_range * 2
      else:
        assert len(sub_range) == 2
      for i in range(int(sub_range[0]), int(sub_range[1]) + 1):
        yield i

  hosts = []
  try:
    for part in split_hostlist(hostlist):
      # Match prefix (anything but a range expression) and range expression
      # Both are optional
      m = re.match(r'([^,[\]]*)(\[([^\]]+)\])?$', part)
      if m is None:
        raise ValueError('Invalid part: %s' % part)
      prefix = m.group(1) or ''
      if m.group(3) is None:
        hosts.append(prefix)
      else:
        hosts.extend(
            prefix + str(i) for i in expand_range_expression(m.group(3)))
  except Exception as e:
    raise ValueError('Invalid hostlist format "%s": %s' % (hostlist, e))
  return hosts

def expand_tasks_per_node(tasks_per_node):
  """Expands the tasks per node expression from SLURM.

  The order is preserved so it can be matched to the hostlist
  Input: '3(x2),2,1'
  Output: [3, 3, 2, 1]
  """
  result = []
  try:
    for part in tasks_per_node.split(','):
      m = re.match(r'(\d+)(\(x(\d+)\))?$', part)
      assert m is not None
      num_tasks = int(m.group(1))
      num_repetitions = int(m.group(3) or 1)
      result.extend([num_tasks] * num_repetitions)
  except Exception as e:
    raise ValueError('Invalid tasks-per-node list format "%s": %s' %
                     (tasks_per_node, e))
  return result

def _get_slurm_var(name):
  """Gets the SLURM variable from the environment.

  Args:
    name: Name of the step variable

  Returns:
    SLURM_<name> from os.environ
  Raises:
    RuntimeError if variable is not found
  """
  name = 'SLURM_' + name
  try:
    return os.environ[name]
  except KeyError:
    raise RuntimeError('%s not found in environment. '
                       'Not running inside a SLURM step?' % name)

def _get_num_slurm_tasks():
  """Returns the number of SLURM tasks of the current job step.

  Returns:
    The number of tasks as an int
  """
  return int(_get_slurm_var('STEP_NUM_TASKS'))

def _get_num_nvidia_gpus():
  """Gets the number of NVIDIA GPUs by using CUDA_VISIBLE_DEVICES and nvidia-smi.

  Returns:
    Number of GPUs available on the node
  Raises:
    RuntimeError if executing nvidia-smi failed
  """
  try:
    return len(os.environ['CUDA_VISIBLE_DEVICES'].split(','))
  except KeyError:
    pass  # Ignore and fallback to using nvidia-smi
  try:
    output = subprocess.check_output(['nvidia-smi', '--list-gpus'],
                                     encoding='utf-8')
    return sum(l.startswith('GPU ') for l in output.strip().split('\n'))
  except subprocess.CalledProcessError as e:
    raise RuntimeError('Could not get number of GPUs from nvidia-smi. '
                       'Maybe it is missing?\nOutput: %s' % e.output)

def get_num_gpus():
  """Returns the number of GPUs visible on the current node.

  Currently only implemented for NVIDIA GPUs.
  """
  return _get_num_nvidia_gpus()

@tf_export('distribute.cluster_resolver.SlurmClusterResolver')
class SlurmClusterResolver(ClusterResolver):
  """ClusterResolver for system with Slurm workload manager.

  This is an implementation of ClusterResolver for Slurm clusters. This allows
  the specification of jobs and task counts, number of tasks per node, number
  of GPUs on each node and number of GPUs for each task. It retrieves system
  attributes by Slurm environment variables, resolves allocated computing node
  names, constructs a cluster and returns a ClusterResolver object which can be
  used for distributed TensorFlow.
  """

  def __init__(self,
               jobs=None,
               port_base=8888,
               gpus_per_node=None,
               gpus_per_task=None,
               tasks_per_node=None,
               auto_set_gpu=True,
               rpc_layer='grpc'):
    """Creates a new SlurmClusterResolver object.

    For any parameter not set it will query the environment for the value.
    It uses those parameters to check which nodes have processes reside on and
    resolves their hostnames.
    With the number tasks per node it offsets the port number for each process.
    With the number of GPUs per node and per task it allocates GPUs to tasks by
    setting environment variables.
    Using the resolver works best (and is easier) with homogeneous tasks but
    heterogeneous tasks (number of tasks varying per node) are also possible as
    long as the number of GPUs per task stays constant.

    Used environment variables:
      - SLURM_PROCID
      - (opt) SLURM_STEP_NUM_TASKS
      - (opt) SLURM_STEP_NODELIST
      - (opt) SLURM_STEP_TASKS_PER_NODE

    Args:
      jobs: Dictionary with job names as key and number of tasks in the job as
        value. Defaults to as many 'worker's as there are (Slurm) tasks.
      port_base: The first port number to start with for processes on a node.
      gpus_per_node: Number of GPUs available on each node. Defaults to the
        number of GPUs reported by nvidia-smi
      gpus_per_task: Number of GPUs to be used for each task. Default is to
        evenly distribute the gpus_per_node to tasks_per_node.
      tasks_per_node: Number of tasks running on each node. Can be an integer if
        the number of tasks per node is constant or a dictionary mapping
        hostnames to number of tasks on that node. If not set the Slurm
        environment is queried for the correct mapping.
      auto_set_gpu: Set the visible CUDA devices automatically while resolving
        the cluster by setting CUDA_VISIBLE_DEVICES environment variable.
        Defaults to True.
      rpc_layer: The protocol TensorFlow used to communicate between nodes.
        Defaults to 'grpc'.

    Returns:
      A ClusterResolver object which can be used with distributed TensorFlow.

    Raises:
      RuntimeError: If requested more GPUs per node then available or
        requested more tasks then assigned tasks or
        resolving missing values from the environment failed.
    """

    self._rank = self._resolve_own_rank()

    if jobs is None:
      jobs = {'worker': self._resolve_num_tasks()}

    self._jobs = jobs
    self._port_base = port_base

    if tasks_per_node is None:
      self._task_configuration = self._resolve_task_configuration()
    elif isinstance(tasks_per_node, dict):
      # User can pass in an explicit configuration as a dict
      self._task_configuration = tasks_per_node
    else:
      # User can pass a fixed number of tasks per node
      hostlist = self._resolve_hostlist()
      self._task_configuration = {
          host: int(tasks_per_node) for host in hostlist
      }

    max_tasks_per_node = max(self._task_configuration.values())
    num_tasks = sum(self._task_configuration.values())

    if gpus_per_node is None:
      gpus_per_node = get_num_gpus()
    if gpus_per_task is None:
      gpus_per_task = gpus_per_node // max_tasks_per_node
    self._gpus_per_node = gpus_per_node
    self._gpus_per_task = gpus_per_task

    self._auto_set_gpu = auto_set_gpu
    self.task_type = None
    self.task_id = None
    self.rpc_layer = rpc_layer

    self._gpu_allocation = []
    self._cluster_allocation = {}

    if max_tasks_per_node * self._gpus_per_task > self._gpus_per_node:
      raise RuntimeError('Requested more GPUs per node then available.')

    if sum(self._jobs.values()) != num_tasks:
      raise RuntimeError('Requested {} tasks but only {} were assigned.'.format(
          sum(self._jobs.values()), num_tasks))

  def _resolve_own_rank(self):
    """Returns the rank of the current task in range [0, num_tasks)."""
    return int(_get_slurm_var('PROCID'))

  def _resolve_num_tasks(self):
    """Returns the number of tasks for the current job step."""
    return _get_num_slurm_tasks()

  def _resolve_hostlist(self):
    """Returns a list of hostnames for nodes running the current job step."""
    return expand_hostlist(_get_slurm_var('STEP_NODELIST'))

  def _resolve_task_configuration(self):
    """Creates a mapping of hostnames to the number of tasks allocated on it.

    Reads the SLURM environment to determine the nodes involved in the current
    job step and number of tasks running on each node.

    Returns a dictionary mapping each hostname to the number of tasks.
    """
    hostlist = self._resolve_hostlist()
    tasks_per_node = expand_tasks_per_node(
        _get_slurm_var('STEP_TASKS_PER_NODE'))
    return {
        host: num_tasks for (host, num_tasks) in zip(hostlist, tasks_per_node)
    }

  def cluster_spec(self):
    """Returns a ClusterSpec object based on the latest instance group info.

    This returns a ClusterSpec object for use based on information from the
    specified initialization parameters and Slurm environment variables. The
    cluster specification is resolved each time this function is called. The
    resolver extract hostnames of nodes by scontrol and pack tasks in that
    order until a node a has number of tasks that is equal to specification.
    GPUs on nodes are allocated to tasks by specification through setting
    CUDA_VISIBLE_DEVICES environment variable.

    Returns:
      A ClusterSpec containing host information retrieved from Slurm's
        environment variables.
    """

    task_list = []
    self._gpu_allocation = []
    self._cluster_allocation = {}

    # Sort to make sure the order is the same for each run
    for host, num_tasks in sorted(self._task_configuration.items()):
      for port_offset, gpu_offset in zip(
          range(num_tasks), range(0, self._gpus_per_node, self._gpus_per_task)):

        host_addr = '%s:%d' % (host, self._port_base + port_offset)
        task_list.append(host_addr)
        gpu_id_list = []

        for gpu_id in range(gpu_offset, gpu_offset + self._gpus_per_task):
          gpu_id_list.append(str(gpu_id))

        self._gpu_allocation.append(','.join(gpu_id_list))

    cluster_rank_offset_start = 0
    cluster_rank_offset_end = 0

    # Sort to make sure the order is the same for each run
    for task_type, num_tasks in sorted(self._jobs.items()):
      cluster_rank_offset_end = cluster_rank_offset_start + num_tasks

      self._cluster_allocation[task_type] = (
          task_list[cluster_rank_offset_start:cluster_rank_offset_end])

      if cluster_rank_offset_start <= self._rank < cluster_rank_offset_end:
        self.task_type = task_type
        self.task_id = self._rank - cluster_rank_offset_start

      cluster_rank_offset_start = cluster_rank_offset_end

    if self._auto_set_gpu:
      os.environ['CUDA_VISIBLE_DEVICES'] = self._gpu_allocation[self._rank]

    return ClusterSpec(self._cluster_allocation)

  def get_task_info(self):
    """Returns job name and task_id for the process which calls this.

    This returns the job name and task index for the process which calls this
    function according to its rank and cluster specification. The job name and
    task index are set after a cluster is constructed by cluster_spec otherwise
    defaults to None.

    Returns:
      A string specifying job name the process belongs to and an integer
        specifying the task index the process belongs to in that job.
    """
    return self.task_type, self.task_id

  def master(self, task_type=None, task_id=None, rpc_layer=None):
    """Returns the master string for connecting to a TensorFlow master.

    Args:
      task_type: (Optional) Overrides the default auto-selected task type.
      task_id: (Optional) Overrides the default auto-selected task index.
      rpc_layer: (Optional) Overrides the default RPC protocol TensorFlow uses
        to communicate across nodes.

    Returns:
      A connection string for connecting to a TensorFlow master.
    """
    task_type = task_type if task_type is not None else self.task_type
    task_id = task_id if task_id is not None else self.task_id

    if task_type is not None and task_id is not None:
      return format_master_url(
          self.cluster_spec().task_address(task_type, task_id),
          rpc_layer or self.rpc_layer)

    return ''

  def num_accelerators(self,
                       task_type=None,
                       task_id=None,
                       config_proto=None):
    # Unused, since this is set in __init__ manually.
    del task_type, task_id, config_proto
    return {'GPU': self._gpus_per_task}


text:
"""Metagene class for metagene_counts.py

Requires:
    python 2 (https://www.python.org/downloads/)

Joy-El R.B. Talbot Copyright (c) 2014

The MIT License (MIT)

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

import re
import datetime
import subprocess
import math

from metageneMethods import confirm_integer
from MetageneError import MetageneError

class Metagene(object):
    """Create a metagene composed of a padded interval of interest.

    Attributes:
        feature_interval -- interval
            value: non-zero positive integer
        padding -- dictionary of padding values
            keys:
                'Upstream' -- left-side interval padding
                    value: positive integer
                'Downstream' -- right-side interval padding
                    value: positive integer
        length -- paddings + interval
             value: non-zero positive integer

    Methods:
        print_full -- Return metagene positions relative to interval start.
                      (instead of default summary)
    """

    ##TODO: add functionality for the start and end of feature_interval to be constant and internal interval to vary
    ##TODO: add functionality for negative paddings!!

    # restrict attributes for each instance
    __slots__ = ['feature_interval', 'padding', 'length']

    def __init__(self, interval=1, padding_upstream=0, padding_downstream=0):
        """Return metagene instance defined by interval and padding sizes.

        Keyword arguments:
        interval -- length of interval (default 1)
        padding_upstream -- length of upstream padding (default 0)
        padding_downstream -- length of downstream padding (default 0)
        """
        if confirm_integer(interval, "Interval", minimum=1):
            self.feature_interval = int(interval)
        self.padding = {'Upstream': None, 'Downstream': None}
        if confirm_integer(padding_upstream, "Upstream padding", minimum=0):
            self.padding['Upstream'] = int(padding_upstream)
        if confirm_integer(padding_downstream, "Downstream padding", minimum=0):
            self.padding['Downstream'] = int(padding_downstream)
        self.length = (self.padding['Upstream'] +
                       self.feature_interval +
                       self.padding['Downstream'])
        # end __init__ function

    def __str__(self):
        return "Upstream:{} -- Interval:{} -- Downstream:{}\tLength:{}".format(self.padding['Upstream'],
                                                                               self.feature_interval,
                                                                               self.padding['Downstream'], self.length)

    def print_full(self, pretty=False):
        """Return metagene positions relative to interval start as 0.

        Keyword arguments:
        pretty -- return human readable version (default False)
        """
        output = ""
        # add metagene schematic and position numbers
        # (relative to feature start as zero)
        if pretty:
            # ---up---int--down- labeling
            output += "{0:15s}\t\t".format('Metagene')
            for i in range(self.padding['Upstream']):
                output += "---up-"
            for i in range(self.feature_interval):
                output += "--int-"
            for i in range(self.padding['Downstream']):
                output += "-down-"
            output += "\n"

            # ---up---int--down-
            #    -1     0     1   relative position labeling
            output += "{0:15s}:\t".format('Position')
            for i in range(self.padding['Upstream'], 0, -1):
                output += "{0:5d},".format(0 - i)
            for i in range(self.feature_interval):
                output += "{0:5d},".format(i)
            for i in range(self.padding['Downstream']):
                output += "{0:5d},".format(i + self.feature_interval)
            output = output[:-1] + "\n"

        else:
            # comma-delimited position output
            # suitable header for metagene_bin.py input files
            output += "{},{}".format('Feature', 'Orientation:Gap')
            for i in range(self.padding['Upstream'], 0, -1):
                output += ",{}".format(0 - i)
            for i in range(self.feature_interval):
                output += ",{}".format(i)
            for i in range(self.padding['Downstream']):
                output += ",{}".format(i + self.feature_interval)
            output += "\n"
        return output

# end Metagene class


text:
<?php

namespace Bootstrap\Components\AppzioUiKit\Articles;

trait uiKitArticleQABlock
{

    public function uiKitArticleQABlock($params, $styles = array())
    {
        return $this->getComponentColumn(array(
            $this->getComponentRow(array(
                $this->getComponentText($params['question'], array('style' => 'article-uikit-text'))
            ), array(), array(
                'background-color' => '#f7f7f7',
            )),
            $this->getComponentRow(array(
                $this->getComponentText($params['answer'], array('style' => 'article-uikit-text'))
            ), array()),
            $this->getComponentDivider(array(
                'style' => 'article-uikit-divider'
            )),
        ));
    }

}


text:
void ps_write_numbers(BitMatrix* b, Psout* ps);
void ps_write_candidates(BitMatrix* b, Psout* ps);
void ps_write_bitmatrix(BitMatrix* b, Psout* ps);

#endif


text:
#import "ApigeeApp.h"
#import "ApigeeApp+JSON.h"
#import "ApigeeApp+Initializers.h"
#import "ApigeeCachedConfigUtil.h"
#import "ApigeeJsonUtils.h"
#import "ApigeeMonitoringClient.h"

static NSString* kApigeeDisckCacheErrorDomain = @"apigee-disk-cache";
static NSString* kApigeeConfigFileName = @"config.json";

@interface ApigeeCachedConfigUtil ()

+ (NSString *) myCacheDirectory;
+ (NSString *) configFilePath;

@end

@implementation ApigeeCachedConfigUtil

+ (NSString*)configFileName
{
    ApigeeMonitoringClient* monitoringClient = [ApigeeMonitoringClient sharedInstance];
    return [NSString stringWithFormat:@"%@_%@",
            [monitoringClient uniqueIdentifierForApp],
            kApigeeConfigFileName];
}

#pragma mark - Private implementations

+ (NSString *) myCacheDirectory
{
    return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
}

+ (NSString *) configFilePath
{
    return [[self myCacheDirectory] stringByAppendingPathComponent:[self configFileName]];
}

+ (BOOL) isCached
{
    return [[NSFileManager defaultManager] fileExistsAtPath:[self configFilePath]];
}

#pragma mark - Public implementations

+ (ApigeeApp *) parseConfiguration:(NSString*)jsonConfigAsString
                                                error:(NSError**)error
{
    id objects = [ApigeeJsonUtils decode:jsonConfigAsString error:error];

    if( (objects == nil) || *error ) {
        NSLog(@"JSON serialization returned nil");
        return nil;
    }

    return [ApigeeApp fromDictionary:objects];
}

/**
 * note: we must always return a configuration, even if there is no available entry in the cache
 */
+ (ApigeeApp *) getConfiguration:(NSError **) error
{
    if (![self isCached]) {
        return [ApigeeApp defaultConfiguration];
    }

    NSData* contents = [[NSFileManager defaultManager] contentsAtPath:[self configFilePath]];

    if (!contents) {
        if (*error) {
            NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
            [errorDetail setValue:@"Error fetching config file contents from disk"
                           forKey:NSLocalizedDescriptionKey];
            *error = [NSError errorWithDomain:kApigeeDisckCacheErrorDomain
                                         code:kApigeeGetConfiguationFailed
                                     userInfo:errorDetail];
        }

        return nil;
    }

    NSString* contentsAsString = [[NSString alloc] initWithData:contents
                                                       encoding:NSUTF8StringEncoding];
    return [self parseConfiguration:contentsAsString error:error];
}

+ (BOOL) updateConfiguration:(NSData *) fileData error:(NSError **) error
{
    if ([[NSFileManager defaultManager] createFileAtPath:[self configFilePath]
                                                contents:fileData
                                              attributes:nil]) {
        return YES;
    }

    if (*error) {
        NSMutableDictionary *errorDetail = [NSMutableDictionary dictionary];
        [errorDetail setValue:@"Error updating cache file on disk"
                       forKey:NSLocalizedDescriptionKey];
        *error = [NSError errorWithDomain:kApigeeDisckCacheErrorDomain
                                     code:kApigeeUpdateConfiguationFailed
                                 userInfo:errorDetail];
    }

    return NO;
}

@end


text:
module Matchers
  class BeLike
    def initialize(expected)
      @expected = expected.gsub(/>\s*\n\s*/, '>').gsub(/\s+/, ' ').strip
    end

    def matches?(actual)
      @actual = actual.gsub(/>\s*\n\s*/, '>').gsub(/\s+/, ' ').strip
      @expected == @actual
    end

    def failure_message
      "expected\n#{@actual}\nto be like\n#{@expected}"
    end

    def negative_failure_message
      "expected\n#{@actual}\nto be unlike\n#{@expected}"
    end
  end

  def be_like(expected)
    BeLike.new(expected)
  end
end


text:
-- Basic
CREATE FUNCTION add_one(INTEGER) RETURNS INTEGER AS '
  BEGIN
    RETURN $1 + 1;
  END;
'  LANGUAGE 'plpgsql';

SELECT * FROM add_one(1);

-- Without quoting
CREATE FUNCTION add_two(INTEGER) RETURNS INTEGER AS
$BODY$
  BEGIN
    RETURN $1 + 2;
  END;
$BODY$
  LANGUAGE 'plpgsql';

SELECT * FROM add_two(1);

-- With name for argument
CREATE FUNCTION add_three(value INTEGER) RETURNS INTEGER AS
$BODY$
  BEGIN
    RETURN value + 3;
  END;
$BODY$
  LANGUAGE 'plpgsql';

SELECT * FROM add_three(1);

-- Function overloading
CREATE FUNCTION add_three(value REAL) RETURNS INTEGER AS
$BODY$
  BEGIN
    RETURN value;
  END;
$BODY$
  LANGUAGE 'plpgsql';

SELECT * FROM add_three(1.0);

-- Declaration of variables and aliasing
CREATE FUNCTION calc_sum(first INTEGER, INTEGER) RETURNS INTEGER AS
$BODY$
  DECLARE
    result INTEGER;
    second ALIAS FOR $2;
    const CONSTANT INTEGER NOT NULL DEFAULT 42;
    copytype const%TYPE;
  BEGIN
    result := first + second;
    RETURN result;
  END;
$BODY$
  LANGUAGE 'plpgsql';

SELECT * FROM calc_sum(5, 6);

CREATE FUNCTION get_zip(name TEXT) RETURNS TEXT AS
$BODY$
  DECLARE
    cust_row customer%rowtype;
  BEGIN
    RAISE DEBUG 'Input value is %', name;
    IF name = ''
    THEN
      RAISE EXCEPTION 'Invalid value';
    END IF;

    SELECT * INTO cust_row FROM customer WHERE customer.fname = name LIMIT 1;
    RETURN cust_row.zipcode;
  END;
$BODY$
  LANGUAGE 'plpgsql';

SELECT * FROM get_zip('Dave');
SELECT * FROM get_zip('');

CREATE FUNCTION int_to_str(val INTEGER) RETURNS TEXT AS
$BODY$
  DECLARE
    result TEXT := '';
  BEGIN
    result := CASE
              WHEN val = 0
                THEN '0'
              WHEN val = 1
                THEN '1'
              WHEN val = 2
                THEN '2'
              WHEN val = 3
                THEN '3'
              WHEN val = 4
                THEN '4'
              WHEN val = 5
                THEN '5'
              WHEN val = 6
                THEN '6'
              WHEN val = 7
                THEN '7'
              WHEN val = 8
                THEN '8'
              WHEN val = 9
                THEN '9'
              ELSE 'oops'
      END;
    RETURN result;
  END;
$BODY$
  LANGUAGE 'plpgsql';

SELECT * FROM int_to_str(5);
SELECT * FROM int_to_str(56);

CREATE FUNCTION counting() RETURNS INTEGER AS
$BODY$
  DECLARE
    result INTEGER := 0;
  BEGIN
    <<counter>>
    LOOP
      result := result + 1;
      EXIT counter WHEN result > 10;
    END LOOP;

    WHILE result > 0
    LOOP
      result := result - 72;
    END LOOP;

    DECLARE
      val INTEGER := 0;
    BEGIN
      FOR ids IN 1 .. 2
      LOOP
        SELECT quantity INTO val FROM stock WHERE stock.item_id = ids;
        result := result + val;
      END LOOP;
    END;

    DECLARE
      stock_row record;
    BEGIN
      FOR stock_row IN SELECT * FROM stock
      LOOP
        result := result + stock_row.quantity;
      END LOOP;
    END;

    RETURN result;
  END;
$BODY$
  LANGUAGE 'plpgsql';

SELECT * FROM counting();


text:
#ifndef __TCPIPCONFIG_H
#define __TCPIPCONFIG_H

#include "GenericTypeDefs.h"
#include "Compiler.h"
#define GENERATED_BY_TCPIPCONFIG "Version 1.0.3383.23374"

// =======================================================================
//   Application Options
// =======================================================================

/* Application Level Module Selection
 *   Uncomment or comment the following lines to enable or
 *   disabled the following high-level application modules.
 */
%STACK_USE_UART%#define STACK_USE_UART					// Application demo using UART for IP address display and stack configuration
%STACK_USE_UART2TCP_BRIDGE%#define STACK_USE_UART2TCP_BRIDGE		// UART to TCP Bridge application example
%STACK_USE_IP_GLEANING%#define STACK_USE_IP_GLEANING
%STACK_USE_ICMP_SERVER%#define STACK_USE_ICMP_SERVER			// Ping query and response capability
%STACK_USE_ICMP_CLIENT%#define STACK_USE_ICMP_CLIENT			// Ping transmission capability
%STACK_USE_HTTP_SERVER%#define STACK_USE_HTTP_SERVER			// Old HTTP server
%STACK_USE_HTTP2_SERVER%#define STACK_USE_HTTP2_SERVER			// New HTTP server with POST, Cookies, Authentication, etc.
%STACK_USE_SSL_SERVER%#define STACK_USE_SSL_SERVER			// SSL server socket support (Requires SW300052)
%STACK_USE_SSL_CLIENT%#define STACK_USE_SSL_CLIENT			// SSL client socket support (Requires SW300052)
%STACK_USE_AUTO_IP%#define STACK_USE_AUTO_IP               // Dynamic link-layer IP address automatic configuration protocol
%STACK_USE_DHCP_CLIENT%#define STACK_USE_DHCP_CLIENT			// Dynamic Host Configuration Protocol client for obtaining IP address and other parameters
%STACK_USE_DHCP_SERVER%#define STACK_USE_DHCP_SERVER			// Single host DHCP server
%STACK_USE_FTP_SERVER%#define STACK_USE_FTP_SERVER			// File Transfer Protocol (old)
%STACK_USE_SMTP_CLIENT%#define STACK_USE_SMTP_CLIENT			// Simple Mail Transfer Protocol for sending email
%STACK_USE_SNMP_SERVER%#define STACK_USE_SNMP_SERVER			// Simple Network Management Protocol v2C Community Agent
%STACK_USE_TFTP_CLIENT%#define STACK_USE_TFTP_CLIENT			// Trivial File Transfer Protocol client
%STACK_USE_GENERIC_TCP_CLIENT_EXAMPLE%#define STACK_USE_GENERIC_TCP_CLIENT_EXAMPLE	// HTTP Client example in GenericTCPClient.c
%STACK_USE_GENERIC_TCP_SERVER_EXAMPLE%#define STACK_USE_GENERIC_TCP_SERVER_EXAMPLE	// ToUpper server example in GenericTCPServer.c
%STACK_USE_TELNET_SERVER%#define STACK_USE_TELNET_SERVER			// Telnet server
%STACK_USE_ANNOUNCE%#define STACK_USE_ANNOUNCE				// Microchip Embedded Ethernet Device Discoverer server/client
%STACK_USE_DNS%#define STACK_USE_DNS					// Domain Name Service Client for resolving hostname strings to IP addresses
%STACK_USE_NBNS%#define STACK_USE_NBNS					// NetBIOS Name Service Server for repsonding to NBNS hostname broadcast queries
%STACK_USE_REBOOT_SERVER%#define STACK_USE_REBOOT_SERVER			// Module for resetting this PIC remotely.  Primarily useful for a Bootloader.
%STACK_USE_SNTP_CLIENT%#define STACK_USE_SNTP_CLIENT			// Simple Network Time Protocol for obtaining current date/time from Internet
%STACK_USE_UDP_PERFORMANCE_TEST%#define STACK_USE_UDP_PERFORMANCE_TEST	// Module for testing UDP TX performance characteristics.  NOTE: Enabling this will cause a huge amount of UDP broadcast packets to flood your network on the discard port.  Use care when enabling this on production networks, especially with VPNs (could tunnel broadcast traffic across a limited bandwidth connection).
%STACK_USE_TCP_PERFORMANCE_TEST%#define STACK_USE_TCP_PERFORMANCE_TEST	// Module for testing TCP TX performance characteristics
%STACK_USE_DYNAMICDNS_CLIENT%#define STACK_USE_DYNAMICDNS_CLIENT		// Dynamic DNS client updater module
%STACK_USE_BERKELEY_API%#define STACK_USE_BERKELEY_API			// Berekely Sockets APIs are available

// =======================================================================
//   Data Storage Options
// =======================================================================

/* MPFS Configuration
 *   MPFS is automatically included when required for other
 *   applications.  If your custom application requires it
 *   otherwise, uncomment the appropriate selection.
 */
//#define STACK_USE_MPFS
//#define STACK_USE_MPFS2

/* MPFS Storage Location
 *   If html pages are stored in internal program memory,
 *   comment both MPFS_USE_EEPROM and MPFS_USE_SPI_FLASH, then
 *   include an MPFS image (.c or .s file) in the project.
 *   If html pages are stored in external memory, uncomment the
 *   appropriate definition.
 *
 *   Supported serial flash parts include the SST25VFxxxB series.
 */
%MPFS_USE_EEPROM%#define MPFS_USE_EEPROM
//#define MPFS_USE_SPI_FLASH

/* EEPROM Addressing Selection
 *   If using the 1Mbit EEPROM, uncomment this line
 */
//#define USE_EEPROM_25LC1024

/* EEPROM Reserved Area
 *   Number of EEPROM bytes to be reserved before MPFS storage starts.
 *   These bytes host application configurations such as IP Address,
 *   MAC Address, and any other required variables.
 *
 *   For MPFS Classic, this setting must match the Reserved setting
 *	 on the Advanced Settings page of the MPFS2 Utility.
 */
#define MPFS_RESERVE_BLOCK				(%MPFS_RESERVE_BLOCK%)

/* MPFS File Handles
 *   Maximum number of simultaneously open MPFS2 files.
 *   For MPFS Classic, this has no effect.
 */
#define MAX_MPFS_HANDLES				(7ul)

// =======================================================================
//   Network Addressing Options
// =======================================================================

/* Default Network Configuration
 *   These settings are only used if data is not found in EEPROM.
 *   To clear EEPROM, hold BUTTON0, reset the board, and continue
 *   holding until the LEDs flash.  Release, and reset again.
 */
#define MY_DEFAULT_HOST_NAME			%MY_DEFAULT_HOST_NAME%

#define MY_DEFAULT_MAC_BYTE1            (0x00)	// Use the default of
#define MY_DEFAULT_MAC_BYTE2            (0x04)	// 00-04-A3-00-00-00 if using
#define MY_DEFAULT_MAC_BYTE3            (0xA3)	// an ENCX24J600 or ZeroG ZG2100
#define MY_DEFAULT_MAC_BYTE4            (0x00)	// and wish to use the internal
#define MY_DEFAULT_MAC_BYTE5            (0x00)	// factory programmed MAC
#define MY_DEFAULT_MAC_BYTE6            (0x00)	// address instead.

#define MY_DEFAULT_IP_ADDR_BYTE1        (169ul)
#define MY_DEFAULT_IP_ADDR_BYTE2        (254ul)
#define MY_DEFAULT_IP_ADDR_BYTE3        (1ul)
#define MY_DEFAULT_IP_ADDR_BYTE4        (1ul)

#define MY_DEFAULT_MASK_BYTE1           (255ul)
#define MY_DEFAULT_MASK_BYTE2           (255ul)
#define MY_DEFAULT_MASK_BYTE3           (0ul)
#define MY_DEFAULT_MASK_BYTE4           (0ul)

#define MY_DEFAULT_GATE_BYTE1           (169ul)
#define MY_DEFAULT_GATE_BYTE2           (254ul)
#define MY_DEFAULT_GATE_BYTE3           (1ul)
#define MY_DEFAULT_GATE_BYTE4           (1ul)

#define MY_DEFAULT_PRIMARY_DNS_BYTE1	(169ul)
#define MY_DEFAULT_PRIMARY_DNS_BYTE2	(254ul)
#define MY_DEFAULT_PRIMARY_DNS_BYTE3	(1ul)
#define MY_DEFAULT_PRIMARY_DNS_BYTE4	(1ul)

#define MY_DEFAULT_SECONDARY_DNS_BYTE1	(0ul)
#define MY_DEFAULT_SECONDARY_DNS_BYTE2	(0ul)
#define MY_DEFAULT_SECONDARY_DNS_BYTE3	(0ul)
#define MY_DEFAULT_SECONDARY_DNS_BYTE4	(0ul)

// =======================================================================
//   ZeroG Wireless Options
//   If not using a ZG2100 device, ignore this section.
// =======================================================================

%STACK_USE_ZG2100%#define STACK_USE_ZG2100

%USE_GRATUITOUS_ARP%#define USE_GRATUITOUS_ARP

// Default SSID or wireless network name to connect to
#define MY_DEFAULT_SSID_NAME                "MicrochipDemoAP"

/*******************************************/
/* DOMAINS & CHANNEL COMPILE TIME DEFAULTS */
/*******************************************/
/* Valid domains:    kZGRegDomainFCC      Available Channels: 1 - 11     */
/*                   kZGRegDomainIC       Available Channels: 1 - 11     */
/*                   kZGRegDomainETSI     Available Channels: 1 - 13     */
/*                   kZGRegDomainJapanA   Available Channels: 14         */
/*                   kZGRegDomainJapanB   Available Channels: 1 - 13     */
#define MY_DEFAULT_DOMAIN                   kZGRegDomainFCC

// When attempting to find the wireless network, only these radio channels
// will be scanned.  Channels 1, 6, and 11 are the three non-overlapping
// radio channels normally used in the FCC regulatory domain.  If you add
// or subtract radio channels, be sure to also update the
// MY_DEFAULT_CHANNEL_LIST_SIZE setting.
#define MY_DEFAULT_CHANNEL_SCAN_LIST        {1, 6, 11, }
#define END_OF_MY_DEFAULT_CHANNEL_SCAN_LIST

// Count of elements in the MY_DEFAULT_CHANNEL_SCAN_LIST macro
#define MY_DEFAULT_CHANNEL_LIST_SIZE        (3u)

/**********************************/
/* SECURITY COMPILE TIME DEFAULTS */
/**********************************/
// Security used on WiFi network.  Legal values are:
// kKeyTypeNone: No encryption/authentication
// kKeyTypeWep: Wired Equivalency Protocol (WEP) encryption
// kKeyTypePsk: WPA-PSK Personal or WPA2-PSK Personal TKIP or AES
//              encryption with precalculated key (see MY_DEFAULT_PSK).
// kKeyTypeCalcPsk: WPA-PSK Personal or WPA2-PSK Personal TKIP or AES
//              encryption with the hardware dynamically generating the
//              needed key for the selected SSID and passphrase.  This
//              option requires more time to associate with the access
//              point relative to kKeyTypePsk which has the key
//              pre-calculated.
#define MY_DEFAULT_ENCRYPTION_TYPE          kKeyTypeNone

// If using security type of kKeyTypePsk, then this section must be set to
// match the key for the MY_DEFAULT_SSID_NAME and MY_DEFAULT_PSK_PHRASE
// combination.  The tool at http://www.wireshark.org/tools/wpa-psk.html
// can be used to generate this field.
#define MY_DEFAULT_PSK                      {0x86, 0xC5, 0x1D, 0x71, 0xD9, 0x1A, 0xAA, 0x49, \
                                            0x40, 0xC8, 0x88, 0xC6, 0xE9, 0x7A, 0x4A, 0xD5, \
                                            0xE5, 0x6D, 0xDA, 0x44, 0x8E, 0xFB, 0x9C, 0x0A, \
                                            0xE1, 0x47, 0x81, 0x52, 0x31, 0x1C, 0x13, 0x7C, \
                                            }
#define END_OF_MY_DEFAULT_PSK

// Default pass phrase used for kKeyTypePsk and kKeyTypeCalcPsk security modes
#define MY_DEFAULT_PSK_PHRASE               "Microchip 802.11 Secret PSK Password"

#define MY_DEFAULT_WEP_KEY_LEN				kZGWEPKeyLenLong
#define MY_DEFAULT_WEP_KEYS					MY_DEFAULT_WEP_KEYS_LONG

// Default WEP keys used in kKeyTypeWep security mode
#define MY_DEFAULT_WEP_KEYS_LONG        {   {{0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C}},\
                                            {{0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C}},\
                                            {{0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C}},\
                                            {{0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C}},\
                                            }
#define END_OF_MY_DEFAULT_WEP_KEYS_LONG
#define MY_DEFAULT_WEP_KEYS_SHORT      		{{{0x00,0x01,0x02,0x03,0x04}},\
                                        	{{0x10,0x11,0x12,0x13,0x14}},\
                                        	{{0x20,0x21,0x22,0x23,0x24}},\
                                        	{{0x30,0x31,0x32,0x33,0x34}},\
                                        	}
#define END_OF_MY_DEFAULT_WEP_KEYS_SHORT

/* Valid Key Index: 0, 1, 2, 3  */
#define MY_DEFAULT_WEP_KEY_INDEX            (0u)

/* Valid WEP auth:   kZGAuthAlgOpen   */
/*                   kZGAuthAlgShared */
#define MY_DEFAULT_WEP_AUTH                 kZGAuthAlgOpen

// These options are required for all PIC devices
#if defined(__18CXX)
    #define ZG_NO_FUNC_PTRS                 y
#endif
#define ZG_CONFIG_LIBRARY                   y
#define ZG_PKG_STDIO                        y
#define ZG_RAW_DRIVER                       y

// These options are configurable
// Provides indication if AP beacons are lost
#define CONNECTION_LOST_FEATURE             y

// Command line interface
%ZG_CONFIG_CONSOLE%#define ZG_CONFIG_CONSOLE                   y

// Provides API to switch between static and dynamic IP addressing
#if defined ( ZG_CONFIG_CONSOLE )
    %ZG_CONFIG_DHCP%#define ZG_CONFIG_DHCP                  y
#endif

// WiFi (BSS), Adhoc (IBSS) connection management turn on/off
#define ZG_CONFIG_LINKMGRII                 y

// Default link management
/* Valid Modes:   kZGLMNetworkModeIdle            (Standby / neutral state)  */
/*                kZGLMNetworkModeAdhoc           (IBSS networks)            */
/*                kZGLMNetworkModeInfrastructure  (BSS networks)             */
#define MY_DEFAULT_LINK_MGMT                kZGLMNetworkModeInfrastructure

// Uncomment this line if you do NOT need IBSS "adhoc" networks.
// If uncommented, ensure that MY_DEFAULT_LINK_MGMT is not kZGLMNetworkModeAdhoc
%ZG_CONFIG_NO_ADHOCMGRII%#define ZG_CONFIG_NO_ADHOCMGRII             y

// Uncomment this line if you do NOT need BSS "managed" networks.
// If uncommented, ensure that MY_DEFAULT_LINK_MGMT is not kZGLMNetworkModeInfrastructure
//#define ZG_CONFIG_NO_WIFIMGRII              y

// Enable Iperf application code.  Iperf is for performance benchmarking
// and should normally be left disabled, unless you are using the TCPIP
// WiFi Iperf App project.
%STACK_USE_IPERF%#define STACK_USE_IPERF                     // Iperf Application

// =======================================================================
//   PIC32MX7XX/6XX MAC Layer Options
//   If not using a PIC32MX7XX/6XX device, ignore this section.
// =======================================================================
#define	ETH_CFG_LINK			0		// set to 1 if you need to config the link to specific following parameters
										// otherwise the default connection will be attempted
										// depending on the selected PHY
	#define	ETH_CFG_AUTO		1		// use auto negotiation
	#define	ETH_CFG_10			1		// use/advertise 10 Mbps capability
	#define	ETH_CFG_100			1		// use/advertise 100 Mbps capability
	#define	ETH_CFG_HDUPLEX		1		// use/advertise half duplex capability
	#define	ETH_CFG_FDUPLEX		1		// use/advertise full duplex capability
	#define	ETH_CFG_AUTO_MDIX	1		// use/advertise auto MDIX capability
	#define	ETH_CFG_SWAP_MDIX	1		// use swapped MDIX. else normal MDIX

#define EMAC_TX_DESCRIPTORS		2		// number of the TX descriptors to be created
#define EMAC_RX_DESCRIPTORS		8		// number of the RX descriptors and RX buffers to be created

#define	EMAC_RX_BUFF_SIZE		1536	// size of a RX buffer. should be multiple of 16
										// this is the size of all receive buffers processed by the ETHC
										// The size should be enough to accomodate any network received packet
										// If the packets are larger, they will have to take multiple RX buffers
										// The current implementation does not handle this situation right now and the packet is discarded.

// =======================================================================
//   Transport Layer Options
// =======================================================================

/* Transport Layer Configuration
 *   The following low level modules are automatically enabled
 *   based on module selections above.  If your custom module
 *   requires them otherwise, enable them here.
 */
%STACK_USE_TCP%#define STACK_USE_TCP
%STACK_USE_UDP%#define STACK_USE_UDP

/* Client Mode Configuration
 *   Uncomment following line if this stack will be used in CLIENT
 *   mode.  In CLIENT mode, some functions specific to client operation
 *   are enabled.
 */
%STACK_CLIENT_MODE%#define STACK_CLIENT_MODE

/* TCP Socket Memory Allocation
 *   TCP needs memory to buffer incoming and outgoing data.  The
 *   amount and medium of storage can be allocated on a per-socket
 *   basis using the example below as a guide.
 */
	// Allocate how much total RAM (in bytes) you want to allocate
	// for use by your TCP TCBs, RX FIFOs, and TX FIFOs.
	#define TCP_ETH_RAM_SIZE					(%TCP_ETH_RAM_SIZE%)
	#define TCP_PIC_RAM_SIZE					(%TCP_PIC_RAM_SIZE%)
	#define TCP_SPI_RAM_SIZE					(%TCP_SPI_RAM_SIZE%)
	#define TCP_SPI_RAM_BASE_ADDRESS			(0x00)

	// Define names of socket types
	#define TCP_SOCKET_TYPES
		#define TCP_PURPOSE_GENERIC_TCP_CLIENT 0
		#define TCP_PURPOSE_GENERIC_TCP_SERVER 1
		#define TCP_PURPOSE_TELNET 2
		#define TCP_PURPOSE_FTP_COMMAND 3
		#define TCP_PURPOSE_FTP_DATA 4
		#define TCP_PURPOSE_TCP_PERFORMANCE_TX 5
		#define TCP_PURPOSE_TCP_PERFORMANCE_RX 6
		#define TCP_PURPOSE_UART_2_TCP_BRIDGE 7
		#define TCP_PURPOSE_HTTP_SERVER 8
		#define TCP_PURPOSE_DEFAULT 9
		#define TCP_PURPOSE_BERKELEY_SERVER 10
		#define TCP_PURPOSE_BERKELEY_CLIENT 11%EXTRA_TCP_SOCKET_TYPES%
	#define END_OF_TCP_SOCKET_TYPES

	#if defined(__TCP_C)
		// Define what types of sockets are needed, how many of
		// each to include, where their TCB, TX FIFO, and RX FIFO
		// should be stored, and how big the RX and TX FIFOs should
		// be.  Making this initializer bigger or smaller defines
		// how many total TCP sockets are available.
		//
		// Each socket requires up to 56 bytes of PIC RAM and
		// 48+(TX FIFO size)+(RX FIFO size) bytes of TCP_*_RAM each.
		//
		// Note: The RX FIFO must be at least 1 byte in order to
		// receive SYN and FIN messages required by TCP.  The TX
		// FIFO can be zero if desired.
		#define TCP_CONFIGURATION
		ROM struct
		{
			BYTE vSocketPurpose;
			BYTE vMemoryMedium;
			WORD wTXBufferSize;
			WORD wRXBufferSize;
		} TCPSocketInitializer[] =
		{
%TCPSOCKET_INITIALIZER_TABLE%
		};
		#define END_OF_TCP_CONFIGURATION
	#endif

/* UDP Socket Configuration
 *   Define the maximum number of available UDP Sockets, and whether
 *   or not to include a checksum on packets being transmitted.
 */
#define MAX_UDP_SOCKETS     (%MAX_UDP_SOCKETS%)
#define UDP_USE_TX_CHECKSUM		// This slows UDP TX performance by nearly 50%, except when using the ENCX24J600, which has a super fast DMA and incurs virtually no speed pentalty.

/* Berkeley API Sockets Configuration
 *   Note that each Berkeley socket internally uses one TCP or UDP socket
 *   defined by MAX_UDP_SOCKETS and the TCPSocketInitializer[] array.
 *   Therefore, this number MUST be less than or equal to MAX_UDP_SOCKETS + the
 *   number of TCP sockets defined by the TCPSocketInitializer[] array
 *   (i.e. sizeof(TCPSocketInitializer)/sizeof(TCPSocketInitializer[0])).
 *   This define has no effect if STACK_USE_BERKELEY_API is not defined and
 *   Berkeley Sockets are disabled.  Set this value as low as your application
 *   requires to avoid waisting RAM.
 */
#define BSD_SOCKET_COUNT (5u)

// =======================================================================
//   Application-Specific Options
// =======================================================================

// -- HTTP2 Server options -----------------------------------------------

	// Maximum numbers of simultaneous HTTP connections allowed.
	// Each connection consumes 2 bytes of RAM and a TCP socket
	#define MAX_HTTP_CONNECTIONS	(2u)

	// Indicate what file to serve when no specific one is requested
	#define HTTP_DEFAULT_FILE		"index.htm"
	#define HTTPS_DEFAULT_FILE		"index.htm"
	#define HTTP_DEFAULT_LEN		(10u)		// For buffer overrun protection.
												// Set to longest length of above two strings.

	// Configure MPFS over HTTP updating
	// Comment this line to disable updating via HTTP
	#define HTTP_MPFS_UPLOAD		"mpfsupload"
	//#define HTTP_MPFS_UPLOAD_REQUIRES_AUTH	// Require password for MPFS uploads
		// Certain firewall and router combinations cause the MPFS2 Utility to fail
		// when uploading.  If this happens, comment out this definition.

	// Define which HTTP modules to use
	// If not using a specific module, comment it to save resources
	#define HTTP_USE_POST					// Enable POST support
	%HTTP_USE_COOKIES%#define HTTP_USE_COOKIES				// Enable cookie support
	%HTTP_USE_AUTHENTICATION%#define HTTP_USE_AUTHENTICATION			// Enable basic authentication support

	//#define HTTP_NO_AUTH_WITHOUT_SSL		// Uncomment to require SSL before requesting a password
	#define HTTP_SSL_ONLY_CHAR		(0xFF)	// Files beginning with this character will only be served over HTTPS
											// Set to 0x00 to require for all files
											// Set to 0xff to require for no files

	%STACK_USE_HTTP_APP_RECONFIG%#define STACK_USE_HTTP_APP_RECONFIG		// Use the AppConfig web page in the Demo App (~2.5kb ROM, ~0b RAM)
	%STACK_USE_HTTP_MD5_DEMO%#define STACK_USE_HTTP_MD5_DEMO			// Use the MD5 Demo web page (~5kb ROM, ~160b RAM)
	%STACK_USE_HTTP_EMAIL_DEMO%#define STACK_USE_HTTP_EMAIL_DEMO		// Use the e-mail demo web page

// -- SSL Options --------------------------------------------------------

	#define MAX_SSL_CONNECTIONS		(2ul)	// Maximum connections via SSL
	#define MAX_SSL_SESSIONS		(2ul)	// Max # of cached SSL sessions
	#define MAX_SSL_BUFFERS			(4ul)	// Max # of SSL buffers (2 per socket)
	#define MAX_SSL_HASHES			(5ul)	// Max # of SSL hashes  (2 per, plus 1 to avoid deadlock)

	// Bits in SSL RSA key.  This parameter is used for SSL sever
	// connections only.  The only valid value is 512 bits (768 and 1024
	// bits do not work at this time).  Note, however, that SSL client
	// operations do currently work up to 1024 bit RSA key length.
	#define SSL_RSA_KEY_SIZE		(512ul)

// -- Telnet Options -----------------------------------------------------

	// Number of simultaneously allowed Telnet sessions.  Note that you
	// must have an equal number of TCP_PURPOSE_TELNET type TCP sockets
	// declared in the TCPSocketInitializer[] array above for multiple
	// connections to work.  If fewer sockets are available than this
	// definition, then the the lesser of the two quantities will be the
	// actual limit.
	#define MAX_TELNET_CONNECTIONS	(1u)

	// Default local listening port for the Telnet server.  Port 23 is the
	// protocol default.
	#define TELNET_PORT				23

	// Default local listening port for the Telnet server when SSL secured.
	// Port 992 is the telnets protocol default.
	#define TELNETS_PORT			992

	// Force all connecting clients to be SSL secured and connected via
	// TELNETS_PORT.  Connections on port TELNET_PORT will be ignored.  If
	// STACK_USE_SSL_SERVER is undefined, this entire setting is ignored
	// (server will accept unsecured connections on TELNET_PORT and won't even
	// listen on TELNETS_PORT).
	//#define TELNET_REJECT_UNSECURED

	// Default username and password required to login to the Telnet server.
	#define TELNET_USERNAME			"admin"
	#define TELNET_PASSWORD			"microchip"

// -- SNMP Options -------------------------------------------------------

	// Comment following line if SNMP TRAP support is needed
	//#define SNMP_TRAP_DISABLED

	// This is the maximum length for community string.
	// Application must ensure that this length is observed.
	// SNMP module adds one byte extra after SNMP_COMMUNITY_MAX_LEN
	// for adding '\0' NULL character.
	#define SNMP_COMMUNITY_MAX_LEN  	(8u)
	#define SNMP_MAX_COMMUNITY_SUPPORT	(3u)
	#define NOTIFY_COMMUNITY_LEN		(SNMP_COMMUNITY_MAX_LEN)

	// Default SNMPv2C community names.  These can be overridden at run time if
	// alternate strings are present in external EEPROM or Flash (actual
	// strings are stored in AppConfig.readCommunity[] and
	// AppConfig.writeCommunity[] arrays).  These strings are case sensitive.
	// An empty string means disabled (not matchable).
	// For application security, these default community names should not be
	// used, but should all be disabled to force the end user to select unique
	// community names.  These defaults are provided only to make it easier to
	// start development.  Specifying more strings than
	// SNMP_MAX_COMMUNITY_SUPPORT will result in the later strings being
	// ignored (but still wasting program memory).  Specifying fewer strings is
	// legal, as long as at least one is present.  A string larger than
	// SNMP_COMMUNITY_MAX_LEN bytes will be ignored.
	#define SNMP_READ_COMMUNITIES		{"public", "read", ""}
    #define END_OF_SNMP_READ_COMMUNITIES
	#define SNMP_WRITE_COMMUNITIES     	{"private", "write", "public"}
    #define END_OF_SNMP_WRITE_COMMUNITIES
#endif