text:
package org.apache.nifi.processors.standard;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import org.apache.nifi.flowfile.attributes.CoreAttributes;
import org.apache.nifi.util.MockFlowFile;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Test;

public class TestSplitText {

    final String originalFilename = "original.txt";
    final Path dataPath = Paths.get("src/test/resources/TestSplitText");
    final Path file = dataPath.resolve(originalFilename);
    final static String TEST_INPUT_DATA = "HeaderLine1\nLine2SpacesAtEnd  \nLine3\nLine4\n\n\nLine8\nLine9\n\n\n13\n14\n15    EndofLine15\n16\n"
            + "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nLastLine\n";

    @Test
    public void testLastLineExceedsSizeLimit() {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "2");
        runner.setProperty(SplitText.FRAGMENT_MAX_SIZE, "20 B");

        runner.enqueue("Line #1\nLine #2\nLine #3\nLong line exceeding limit");
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        final MockFlowFile originalFlowFile = runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0);
        originalFlowFile.assertAttributeEquals(SplitText.FRAGMENT_COUNT, "3");
        originalFlowFile.assertAttributeExists(SplitText.FRAGMENT_ID);
        runner.assertTransferCount(SplitText.REL_SPLITS, 3);
    }

    @Test
    public void testIncompleteHeader() {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "2");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "2");
        runner.setProperty(SplitText.FRAGMENT_MAX_SIZE, "50 B");

        runner.enqueue("Header Line #1");
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 1);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 0);
        runner.assertTransferCount(SplitText.REL_SPLITS, 0);
    }

    @Test
    public void testSingleCharacterHeaderMarker() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "7");
        runner.setProperty(SplitText.HEADER_MARKER, "H");
        runner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "false");

        runner.enqueue(file);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals("fragment.count", "2");
        runner.assertTransferCount(SplitText.REL_SPLITS, 2);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splits.get(0).assertAttributeEquals(SplitText.SPLIT_LINE_COUNT, "7");
        splits.get(0).assertAttributeEquals(SplitText.FRAGMENT_SIZE, "86");
        splits.get(1).assertAttributeEquals(SplitText.SPLIT_LINE_COUNT, "3");
        splits.get(1).assertAttributeEquals(SplitText.FRAGMENT_SIZE, "54");
        final String fragmentUUID = splits.get(0).getAttribute(SplitText.FRAGMENT_ID);
        for (int i = 0; i < splits.size(); i++) {
            final MockFlowFile split = splits.get(i);
            split.assertAttributeEquals(SplitText.FRAGMENT_INDEX, String.valueOf(i+1));
            split.assertAttributeEquals(SplitText.FRAGMENT_ID, fragmentUUID);
            split.assertAttributeEquals(SplitText.FRAGMENT_COUNT, String.valueOf(splits.size()));
            split.assertAttributeEquals(SplitText.SEGMENT_ORIGINAL_FILENAME, file.getFileName().toString());
        }
    }

    @Test
    public void testMultipleHeaderIndicators() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "1");
        runner.setProperty(SplitText.HEADER_MARKER, "Head");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "5");
        runner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "false");

        runner.enqueue(file);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals("fragment.count", "3");
        runner.assertTransferCount(SplitText.REL_SPLITS, 3);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splits.get(0).assertAttributeEquals(SplitText.SPLIT_LINE_COUNT, "5");
        splits.get(0).assertAttributeEquals(SplitText.FRAGMENT_SIZE, "62");
        splits.get(1).assertAttributeEquals(SplitText.SPLIT_LINE_COUNT, "5");
        splits.get(1).assertAttributeEquals(SplitText.FRAGMENT_SIZE, "55");
        splits.get(2).assertAttributeEquals(SplitText.SPLIT_LINE_COUNT, "1");
        splits.get(2).assertAttributeEquals(SplitText.FRAGMENT_SIZE, "23");
        final String fragmentUUID = splits.get(0).getAttribute(SplitText.FRAGMENT_ID);
        for (int i = 0; i < splits.size(); i++) {
            final MockFlowFile split = splits.get(i);
            split.assertAttributeEquals(SplitText.FRAGMENT_INDEX, String.valueOf(i + 1));
            split.assertAttributeEquals(SplitText.FRAGMENT_ID, fragmentUUID);
            split.assertAttributeEquals(SplitText.FRAGMENT_COUNT, String.valueOf(splits.size()));
            split.assertAttributeEquals(SplitText.SEGMENT_ORIGINAL_FILENAME, file.getFileName().toString());
        }
    }

    @Test
    public void testZeroLinesNoMaxSize() {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "0");

        runner.assertNotValid();
    }

    @Test
    public void testMultipleSplitDirectives() {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "2");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "2");
        runner.setProperty(SplitText.FRAGMENT_MAX_SIZE, "50 B");
        runner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "false");

        runner.enqueue("Header Line #1\nHeader Line #2\nLine #1\nLine #2\n"
                + "Line #3 This line has additional text added so that it exceeds the maximum fragment size\n"
                + "Line #4\nLine #5\nLine #6\nLine #7\nLine #8\nLine #9\nLine #10\n");
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals("fragment.count", "6");
        runner.assertTransferCount(SplitText.REL_SPLITS, 6);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        assertEquals(46, splits.get(0).getSize());
        assertEquals(119, splits.get(1).getSize());
        assertEquals(46, splits.get(2).getSize());
        assertEquals(46, splits.get(3).getSize());
        assertEquals(46, splits.get(4).getSize());
        assertEquals(39, splits.get(5).getSize());
    }

    @Test
    public void testFlowFileIsOnlyHeader() {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "2");
        runner.setProperty(SplitText.FRAGMENT_MAX_SIZE, "50 B");
        runner.setProperty(SplitText.HEADER_MARKER, "Head");

        runner.enqueue("Header Line #1\nHeaderLine#2\n");
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals("fragment.count", "1");
        runner.assertTransferCount(SplitText.REL_SPLITS, 1);

        // repeat with header cou8nt versus header marker
        runner.clearTransferState();
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "2");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "2");
        runner.setProperty(SplitText.FRAGMENT_MAX_SIZE, "50 B");

        runner.enqueue("Header Line #1\nHeaderLine #2\n");
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals("fragment.count", "1");
        runner.assertTransferCount(SplitText.REL_SPLITS, 1);

        // repeat single header line with no newline characters
        runner.clearTransferState();
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "1");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "2");
        runner.setProperty(SplitText.FRAGMENT_MAX_SIZE, "50 B");

        runner.enqueue("Header Line #1");
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals("fragment.count", "1");
        runner.assertTransferCount(SplitText.REL_SPLITS, 1);
    }

    @Test
    public void testMaxSizeExceeded() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "2");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "0");
        runner.setProperty(SplitText.FRAGMENT_MAX_SIZE, "71 B");
        runner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "false");

        runner.enqueue(file);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals(SplitText.FRAGMENT_COUNT, "2");
        runner.assertTransferCount(SplitText.REL_SPLITS, 2);

        List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        String fragmentUUID = splits.get(0).getAttribute(SplitText.FRAGMENT_ID);
        for (int i = 0; i < splits.size(); i++) {
            final MockFlowFile split = splits.get(i);
            split.assertAttributeEquals(SplitText.SPLIT_LINE_COUNT, "5");
            split.assertAttributeEquals(SplitText.FRAGMENT_SIZE, "70");
            split.assertAttributeEquals(SplitText.FRAGMENT_INDEX, String.valueOf(i + 1));
            split.assertAttributeEquals(SplitText.FRAGMENT_ID, fragmentUUID);
            split.assertAttributeEquals(SplitText.FRAGMENT_COUNT, String.valueOf(splits.size()));
            split.assertAttributeEquals(SplitText.SEGMENT_ORIGINAL_FILENAME, file.getFileName().toString());
        }

        // Repeat test without header
        runner.clearTransferState();
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "0");
        runner.setProperty(SplitText.FRAGMENT_MAX_SIZE, "71 B");
        runner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "false");

        runner.enqueue(file);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals(SplitText.FRAGMENT_COUNT, "2");
        runner.assertTransferCount(SplitText.REL_SPLITS, 2);

        splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        fragmentUUID = splits.get(0).getAttribute(SplitText.FRAGMENT_ID);
        splits.get(0).assertContentEquals("Header Line #1\nHeader Line #2\nLine #1\nLine #2\nLine #3\nLine #4\nLine #5\n");
        splits.get(1).assertContentEquals("Line #6\nLine #7\nLine #8\nLine #9\nLine #10");
        splits.get(0).assertAttributeEquals(SplitText.SPLIT_LINE_COUNT, "7");
        splits.get(0).assertAttributeEquals(SplitText.FRAGMENT_SIZE, "70");
        splits.get(0).assertAttributeEquals(SplitText.FRAGMENT_INDEX, "1");
        splits.get(0).assertAttributeEquals(SplitText.FRAGMENT_ID, fragmentUUID);
        splits.get(0).assertAttributeEquals(SplitText.FRAGMENT_COUNT, "2");
        splits.get(0).assertAttributeEquals(SplitText.SEGMENT_ORIGINAL_FILENAME, file.getFileName().toString());
        splits.get(1).assertAttributeEquals(SplitText.SPLIT_LINE_COUNT, "5");
        splits.get(1).assertAttributeEquals(SplitText.FRAGMENT_SIZE, "40");
        splits.get(1).assertAttributeEquals(SplitText.FRAGMENT_INDEX, "2");
        splits.get(1).assertAttributeEquals(SplitText.FRAGMENT_ID, fragmentUUID);
        splits.get(1).assertAttributeEquals(SplitText.FRAGMENT_COUNT, "2");
        splits.get(1).assertAttributeEquals(SplitText.SEGMENT_ORIGINAL_FILENAME, file.getFileName().toString());
    }

    @Test
    public void testSplitWithOnlyCarriageReturn() {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "2");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");

        runner.enqueue("H1\rH2\r1\r2\r3\r\r\r\r\r\r\r10\r11\r12\r");
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals(SplitText.FRAGMENT_COUNT, "4");
        runner.assertTransferCount(SplitText.REL_SPLITS, 4);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splits.get(0).assertContentEquals("H1\rH2\r1\r2\r3");
        splits.get(1).assertContentEquals("H1\rH2");
        splits.get(2).assertContentEquals("H1\rH2");
        splits.get(3).assertContentEquals("H1\rH2\r10\r11\r12");

        runner.clearTransferState();
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");

        runner.enqueue("1\r2\r3\r\r\r\r\r\r\r10\r11\r12\r");
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals(SplitText.FRAGMENT_COUNT, "2");
        runner.assertTransferCount(SplitText.REL_SPLITS, 2);

        final List<MockFlowFile> splitsWithNoHeader = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splitsWithNoHeader.get(0).assertContentEquals("1\r2\r3");
        splitsWithNoHeader.get(1).assertContentEquals("10\r11\r12");

    }

    @Test
    public void testSplitWithCarriageReturnAndNewLines() {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "2");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");

        runner.enqueue("H1\r\nH2\r\n1\r\n2\r\n3\r\n\r\n\r\n\r\n\r\n\r\n\r\n10\r\n11\r\n12\r\n");
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals(SplitText.FRAGMENT_COUNT, "4");
        runner.assertTransferCount(SplitText.REL_SPLITS, 4);

        final List<MockFlowFile> splits =runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splits.get(0).assertContentEquals("H1\r\nH2\r\n1\r\n2\r\n3");
        splits.get(1).assertContentEquals("H1\r\nH2");
        splits.get(2).assertContentEquals("H1\r\nH2");
        splits.get(3).assertContentEquals("H1\r\nH2\r\n10\r\n11\r\n12");

        runner.clearTransferState();
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");

        runner.enqueue("1\r\n2\r\n3\r\n\r\n\r\n\r\n\r\n\r\n\r\n10\r\n11\r\n12\r\n");
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals(SplitText.FRAGMENT_COUNT, "2");
        runner.assertTransferCount(SplitText.REL_SPLITS, 2);

        final List<MockFlowFile> splitsWithNoHeader =runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splitsWithNoHeader.get(0).assertContentEquals("1\r\n2\r\n3");
        splitsWithNoHeader.get(1).assertContentEquals("10\r\n11\r\n12");
    }

    @Test
    public void testRoutesToFailureIfHeaderLinesNotAllPresent() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "100");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");

        runner.enqueue(file);
        runner.run();
        runner.assertAllFlowFilesTransferred(SplitText.REL_FAILURE, 1);
    }

    @Test
    public void testZeroByteOutput() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");

        runner.enqueue(file);
        runner.run();
        runner.assertTransferCount(SplitText.REL_SPLITS, 4);
    }

    @Test
    public void testZeroByteInputWithoutHeader() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "1");

        runner.enqueue("".getBytes());
        runner.run();
        runner.assertTransferCount(SplitText.REL_SPLITS, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
    }

    @Test
    public void testZeroByteInput() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "1");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "1");

        runner.enqueue("".getBytes());
        runner.run();
        runner.assertTransferCount(SplitText.REL_SPLITS, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
    }

    @Test
    public void testSplitWithoutHeader() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");

        runner.enqueue(file);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals(SplitText.FRAGMENT_COUNT, "4");
        runner.assertTransferCount(SplitText.REL_SPLITS, 4);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);

        final String expected0 = "Header Line #1\nHeader Line #2\nLine #1";
        final String expected1 = "Line #2\nLine #3\nLine #4";
        final String expected2 = "Line #5\nLine #6\nLine #7";
        final String expected3 = "Line #8\nLine #9\nLine #10";

        splits.get(0).assertContentEquals(expected0);
        splits.get(1).assertContentEquals(expected1);
        splits.get(2).assertContentEquals(expected2);
        splits.get(3).assertContentEquals(expected3);
    }

    @Test
    public void testOneLineSplitWithoutHeader() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "1");

        runner.enqueue(TEST_INPUT_DATA);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.getFlowFilesForRelationship(SplitText.REL_ORIGINAL).get(0).assertAttributeEquals(SplitText.FRAGMENT_COUNT, "11");
        runner.assertTransferCount(SplitText.REL_SPLITS, 11);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);

        splits.get(0).assertContentEquals("HeaderLine1");
        splits.get(1).assertContentEquals("Line2SpacesAtEnd  ");
        splits.get(2).assertContentEquals("Line3");
        splits.get(3).assertContentEquals("Line4");
        splits.get(4).assertContentEquals("Line8");
        splits.get(5).assertContentEquals("Line9");
        splits.get(6).assertContentEquals("13");
        splits.get(7).assertContentEquals("14");
        splits.get(8).assertContentEquals("15    EndofLine15");
        splits.get(9).assertContentEquals("16");
        splits.get(10).assertContentEquals("LastLine");
    }

    @Test
    public void testFiveLineSplitWithoutHeader() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "5");

        runner.enqueue(TEST_INPUT_DATA);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.assertTransferCount(SplitText.REL_SPLITS, 4);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);

        splits.get(0).assertContentEquals("HeaderLine1\nLine2SpacesAtEnd  \nLine3\nLine4");
        splits.get(1).assertContentEquals("\nLine8\nLine9");
        splits.get(2).assertContentEquals("13\n14\n15    EndofLine15\n16");
        splits.get(3).assertContentEquals("\n\nLastLine");
    }

    @Test
    public void testFiveLineSplitWithoutHeaderRetainNewline() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "5");
        runner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "false");

        runner.enqueue(TEST_INPUT_DATA);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.assertTransferCount(SplitText.REL_SPLITS, 10);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);

        splits.get(0).assertContentEquals("HeaderLine1\nLine2SpacesAtEnd  \nLine3\nLine4\n\n");
        splits.get(1).assertContentEquals("\nLine8\nLine9\n\n\n");
        splits.get(2).assertContentEquals("13\n14\n15    EndofLine15\n16\n\n");
        splits.get(3).assertContentEquals("\n\n\n\n\n");
        splits.get(4).assertContentEquals("\n\n\n\n\n");
        splits.get(5).assertContentEquals("\n\n\n\n\n");
        splits.get(6).assertContentEquals("\n\n\n\n\n");
        splits.get(7).assertContentEquals("\n\n\n\n\n");
        splits.get(8).assertContentEquals("\n\n\n\n\n");
        splits.get(9).assertContentEquals("\n\nLastLine\n");
    }

    @Test
    public void testFiveLineSplitWithHeaderRetainNewline() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "1");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "5");
        runner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "false");
        runner.enqueue(TEST_INPUT_DATA);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.assertTransferCount(SplitText.REL_SPLITS, 10);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);

        splits.get(0).assertContentEquals("HeaderLine1\nLine2SpacesAtEnd  \nLine3\nLine4\n\n\n");
        splits.get(1).assertContentEquals("HeaderLine1\nLine8\nLine9\n\n\n13\n");
        splits.get(2).assertContentEquals("HeaderLine1\n14\n15    EndofLine15\n16\n\n\n");
        splits.get(3).assertContentEquals("HeaderLine1\n\n\n\n\n\n");
        splits.get(4).assertContentEquals("HeaderLine1\n\n\n\n\n\n");
        splits.get(5).assertContentEquals("HeaderLine1\n\n\n\n\n\n");
        splits.get(6).assertContentEquals("HeaderLine1\n\n\n\n\n\n");
        splits.get(7).assertContentEquals("HeaderLine1\n\n\n\n\n\n");
        splits.get(8).assertContentEquals("HeaderLine1\n\n\n\n\n\n");
        splits.get(9).assertContentEquals("HeaderLine1\n\nLastLine\n");
    }

    @Test
    public void testFiveLineSplitWithHeaderNotRetainNewline() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "1");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "5");
        runner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "true");

        runner.enqueue(TEST_INPUT_DATA);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.assertTransferCount(SplitText.REL_SPLITS, 10);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splits.get(0).assertContentEquals("HeaderLine1\nLine2SpacesAtEnd  \nLine3\nLine4");
        splits.get(1).assertContentEquals("HeaderLine1\nLine8\nLine9\n\n\n13");
        splits.get(2).assertContentEquals("HeaderLine1\n14\n15    EndofLine15\n16");
        splits.get(3).assertContentEquals("HeaderLine1");
        splits.get(4).assertContentEquals("HeaderLine1");
        splits.get(5).assertContentEquals("HeaderLine1");
        splits.get(6).assertContentEquals("HeaderLine1");
        splits.get(7).assertContentEquals("HeaderLine1");
        splits.get(8).assertContentEquals("HeaderLine1");
        splits.get(9).assertContentEquals("HeaderLine1\n\nLastLine");
    }

    @Test
    public void testOneLineSplitWithHeader() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "1");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "1");

        runner.enqueue(TEST_INPUT_DATA);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.assertTransferCount(SplitText.REL_SPLITS, 47);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);

        splits.get(0).assertContentEquals("HeaderLine1\nLine2SpacesAtEnd  ");
        splits.get(1).assertContentEquals("HeaderLine1\nLine3");
        splits.get(2).assertContentEquals("HeaderLine1\nLine4");
        splits.get(3).assertContentEquals("HeaderLine1");
        splits.get(4).assertContentEquals("HeaderLine1");
        splits.get(5).assertContentEquals("HeaderLine1\nLine8");
        splits.get(6).assertContentEquals("HeaderLine1\nLine9");
        splits.get(7).assertContentEquals("HeaderLine1");
        splits.get(8).assertContentEquals("HeaderLine1");
        splits.get(9).assertContentEquals("HeaderLine1\n13");
        splits.get(10).assertContentEquals("HeaderLine1\n14");
        splits.get(11).assertContentEquals("HeaderLine1\n15    EndofLine15");
        splits.get(12).assertContentEquals("HeaderLine1\n16");
        for (int i = 13; i < 46; i++) {
            splits.get(i).assertContentEquals("HeaderLine1");
        }
        splits.get(46).assertContentEquals("HeaderLine1\nLastLine");
    }

    @Test
    public void testSplitWithTwoLineHeader() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "2");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");

        runner.enqueue(file);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.assertTransferCount(SplitText.REL_SPLITS, 4);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        for (int i = 0; i < splits.size(); i++) {
            final MockFlowFile split = splits.get(i);
            split.assertContentEquals(file.getParent().resolve((i + 1) + ".txt"));
            split.assertAttributeEquals(SplitText.FRAGMENT_INDEX, String.valueOf(i + 1));
        }
    }

    @Test
    public void testSplitWithTwoLineHeaderAndEvenMultipleOfLines() throws IOException {
        final TestRunner runner = TestRunners.newTestRunner(new SplitText());
        runner.setProperty(SplitText.HEADER_LINE_COUNT, "2");
        runner.setProperty(SplitText.LINE_SPLIT_COUNT, "5");

        runner.enqueue(file);
        runner.run();

        runner.assertTransferCount(SplitText.REL_FAILURE, 0);
        runner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        runner.assertTransferCount(SplitText.REL_SPLITS, 2);

        final List<MockFlowFile> splits = runner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splits.get(0).assertContentEquals(file.getParent().resolve("5.txt"));
        splits.get(0).assertAttributeEquals(SplitText.FRAGMENT_INDEX, String.valueOf(1));
        splits.get(1).assertContentEquals(file.getParent().resolve("6.txt"));
        splits.get(1).assertAttributeEquals(SplitText.FRAGMENT_INDEX, String.valueOf(2));
    }

    @Test
    public void testSplitThenMerge() throws IOException {
        final TestRunner splitRunner = TestRunners.newTestRunner(new SplitText());
        splitRunner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");
        splitRunner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "false");

        splitRunner.enqueue(file);
        splitRunner.run();

        splitRunner.assertTransferCount(SplitText.REL_SPLITS, 4);
        splitRunner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        splitRunner.assertTransferCount(SplitText.REL_FAILURE, 0);

        final List<MockFlowFile> splits = splitRunner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        for (final MockFlowFile flowFile : splits) {
            flowFile.assertAttributeEquals(SplitText.SEGMENT_ORIGINAL_FILENAME, originalFilename);
            flowFile.assertAttributeEquals(SplitText.FRAGMENT_COUNT, "4");
        }

        final TestRunner mergeRunner = TestRunners.newTestRunner(new MergeContent());
        mergeRunner.setProperty(MergeContent.MERGE_FORMAT, MergeContent.MERGE_FORMAT_CONCAT);
        mergeRunner.setProperty(MergeContent.MERGE_STRATEGY, MergeContent.MERGE_STRATEGY_DEFRAGMENT);
        mergeRunner.enqueue(splits.toArray(new MockFlowFile[0]));
        mergeRunner.run();

        mergeRunner.assertTransferCount(MergeContent.REL_MERGED, 1);
        mergeRunner.assertTransferCount(MergeContent.REL_ORIGINAL, 4);
        mergeRunner.assertTransferCount(MergeContent.REL_FAILURE, 0);

        final List<MockFlowFile> packed = mergeRunner.getFlowFilesForRelationship(MergeContent.REL_MERGED);
        MockFlowFile flowFile = packed.get(0);
        flowFile.assertAttributeEquals(CoreAttributes.FILENAME.key(), originalFilename);
        assertEquals(Files.size(dataPath.resolve(originalFilename)), flowFile.getSize());
        flowFile.assertContentEquals(file);
    }

    /*
     * If an input FlowFile has a number of blank lines greater than the Line Split Count property,
     * ensure that the remainder of the FlowFile will be processed, resulting in no data loss.
     */
    @Test
    public void testSplitWithOnlyNewLines() {
        final TestRunner splitRunner = TestRunners.newTestRunner(new SplitText());
        splitRunner.setProperty(SplitText.HEADER_LINE_COUNT, "2");
        splitRunner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");
        splitRunner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "true");

        splitRunner.enqueue("H1\nH2\n1\n2\n3\n\n\n\n\n\n\n10\n11\n12\n");

        splitRunner.run();
        splitRunner.assertTransferCount(SplitText.REL_SPLITS, 4);
        splitRunner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        splitRunner.assertTransferCount(SplitText.REL_FAILURE, 0);

        final List<MockFlowFile> splits = splitRunner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splits.get(0).assertContentEquals("H1\nH2\n1\n2\n3");
        splits.get(1).assertContentEquals("H1\nH2");
        splits.get(2).assertContentEquals("H1\nH2");
        splits.get(3).assertContentEquals("H1\nH2\n10\n11\n12");

        splitRunner.clearTransferState();
        splitRunner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        splitRunner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");
        splitRunner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "true");

        splitRunner.enqueue("1\n2\n3\n\n\n\n\n\n\n10\n11\n12\n");

        splitRunner.run();
        splitRunner.assertTransferCount(SplitText.REL_SPLITS, 2);
        splitRunner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        splitRunner.assertTransferCount(SplitText.REL_FAILURE, 0);

        final List<MockFlowFile> splitsWithNoHeader = splitRunner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splitsWithNoHeader.get(0).assertContentEquals("1\n2\n3");
        splitsWithNoHeader.get(1).assertContentEquals("10\n11\n12");

    }

    /*
     * If an input FlowFile has X blank lines at the end of a file and Line Split Count is
     * greater than X, verify that newlines are removed.
     */
    @Test
    public void testWithLotsOfBlankLinesAtEnd() {
        // verify with header lines
        final TestRunner splitRunner = TestRunners.newTestRunner(new SplitText());
        splitRunner.setProperty(SplitText.HEADER_LINE_COUNT, "2");
        splitRunner.setProperty(SplitText.LINE_SPLIT_COUNT, "10");
        splitRunner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "true");

        splitRunner.enqueue("H1\nH2\n1\n\n\n");

        splitRunner.run();
        splitRunner.assertTransferCount(SplitText.REL_SPLITS, 1);
        splitRunner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        splitRunner.assertTransferCount(SplitText.REL_FAILURE, 0);

        final List<MockFlowFile> splits = splitRunner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splits.get(0).assertContentEquals("H1\nH2\n1");

        // verify without headers
        splitRunner.clearTransferState();
        splitRunner.setProperty(SplitText.HEADER_LINE_COUNT, "0");

        splitRunner.enqueue("1\n2\n\n\n\n");
        splitRunner.run();

        splitRunner.assertTransferCount(SplitText.REL_SPLITS, 1);
        splitRunner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        splitRunner.assertTransferCount(SplitText.REL_FAILURE, 0);

        final List<MockFlowFile> splitsWithNoHeader = splitRunner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splitsWithNoHeader.get(0).assertContentEquals("1\n2");
    }

    /*
     * If an input FlowFile has X blank lines at the end of a file and Header Line Count = 0,
     * ensure all newlines removed from end of file. Previous behavior was: In the case where X is greater than
     * Line Split Count, there will be split files consisting of nothing but blank lines,
     * specifically one fewer lines than Line Split Count (i.e. only the final newline character is removed).
     *
     * Ensure that the above behavior is no longer reflected by the Processor.
     */
    @Test
    public void testAllNewLinesTrimmed() {
        final TestRunner splitRunner = TestRunners.newTestRunner(new SplitText());
        splitRunner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        splitRunner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");
        splitRunner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "true");

        splitRunner.enqueue("1\n2\n\n\n\n\n\n\n\n");

        splitRunner.run();
        splitRunner.assertTransferCount(SplitText.REL_SPLITS, 1);
        splitRunner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        splitRunner.assertTransferCount(SplitText.REL_FAILURE, 0);

        final List<MockFlowFile> splits = splitRunner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        MockFlowFile split0 = splits.get(0);
        split0.assertContentEquals("1\n2");
        split0.assertAttributeEquals(SplitText.FRAGMENT_INDEX, "1");
        split0.assertAttributeEquals(SplitText.FRAGMENT_COUNT, "1");
        split0.assertAttributeEquals(SplitText.SPLIT_LINE_COUNT, "2");
    }

    @Test
    public void testFragmentCountIsActualFlowFileCount() {
        final TestRunner splitRunner = TestRunners.newTestRunner(new SplitText());
        splitRunner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        splitRunner.setProperty(SplitText.LINE_SPLIT_COUNT, "1");
        splitRunner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "true");

        splitRunner.enqueue("1\n2\n\n\n\n\n\n\n\n");

        splitRunner.run();
        splitRunner.assertTransferCount(SplitText.REL_SPLITS, 2);
        splitRunner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        splitRunner.assertTransferCount(SplitText.REL_FAILURE, 0);

        final List<MockFlowFile> splits = splitRunner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        MockFlowFile split0 = splits.get(0);
        split0.assertContentEquals("1");
        split0.assertAttributeEquals(SplitText.FRAGMENT_INDEX, "1");
        split0.assertAttributeEquals(SplitText.FRAGMENT_COUNT, "2");
        split0.assertAttributeEquals(SplitText.SPLIT_LINE_COUNT, "1");
        MockFlowFile split1 = splits.get(1);
        split1.assertContentEquals("2");
        split1.assertAttributeEquals(SplitText.FRAGMENT_INDEX, "2");
        split1.assertAttributeEquals(SplitText.FRAGMENT_COUNT, "2");
        split1.assertAttributeEquals(SplitText.SPLIT_LINE_COUNT, "1");
    }

    /*
     * Previous behavior that was exhibited:
     * If an input FlowFile has X blank lines at the end of a file and
     * Header Line Count = 1 (or any non-zero value), the blank lines
     * are removed and no split file of just blanks is created. However,
     * the final line does contain a newline character. In other split
     * files, the final line has the newline character removed.
     *
     * Ensure that this behavior has been addressed. The Split file that
     * does contain content should not have the trailing new line. The
     * last FlowFile should be generated, containing nothing.
     */
    @Test
    public void testConsistentTrailingOfNewLines() {
        final TestRunner splitRunner = TestRunners.newTestRunner(new SplitText());
        splitRunner.setProperty(SplitText.HEADER_LINE_COUNT, "1");
        splitRunner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");
        splitRunner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "true");

        splitRunner.enqueue("H1\n1\n\n\n\n\n\n\n\n");

        splitRunner.run();
        splitRunner.assertTransferCount(SplitText.REL_SPLITS, 3);
        splitRunner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        splitRunner.assertTransferCount(SplitText.REL_FAILURE, 0);

        final List<MockFlowFile> splits = splitRunner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splits.get(0).assertContentEquals("H1\n1");
        splits.get(1).assertContentEquals("H1");
        splits.get(2).assertContentEquals("H1");
    }

    @Test
    public void testWithSplitThatStartsWithNewLine() {
        final TestRunner splitRunner = TestRunners.newTestRunner(new SplitText());
        splitRunner.setProperty(SplitText.HEADER_LINE_COUNT, "1");
        splitRunner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");
        splitRunner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "true");

        splitRunner.enqueue("H1\n1\n2\n3\n\n\n4\n");

        splitRunner.run();
        splitRunner.assertTransferCount(SplitText.REL_SPLITS, 2);
        splitRunner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        splitRunner.assertTransferCount(SplitText.REL_FAILURE, 0);

        final List<MockFlowFile> splits = splitRunner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splits.get(0).assertContentEquals("H1\n1\n2\n3");
        splits.get(1).assertContentEquals("H1\n\n\n4");

        splitRunner.clearTransferState();

        splitRunner.setProperty(SplitText.HEADER_LINE_COUNT, "0");
        splitRunner.enqueue("1\n2\n3\n\n\n4\n");

        splitRunner.run();
        splitRunner.assertTransferCount(SplitText.REL_SPLITS, 2);
        splitRunner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        splitRunner.assertTransferCount(SplitText.REL_FAILURE, 0);

        final List<MockFlowFile> splitsWithoutHeader = splitRunner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splitsWithoutHeader.get(0).assertContentEquals("1\n2\n3");
        splitsWithoutHeader.get(1).assertContentEquals("\n\n4");
    }

    @Test
    public void testWithEmptyHeaderLines() {
        final TestRunner splitRunner = TestRunners.newTestRunner(new SplitText());
        splitRunner.setProperty(SplitText.HEADER_LINE_COUNT, "2");
        splitRunner.setProperty(SplitText.LINE_SPLIT_COUNT, "3");
        splitRunner.setProperty(SplitText.REMOVE_TRAILING_NEWLINES, "true");

        splitRunner.enqueue("\n\n1\n\n\n\n\n");

        splitRunner.run();
        splitRunner.assertTransferCount(SplitText.REL_SPLITS, 2);
        splitRunner.assertTransferCount(SplitText.REL_ORIGINAL, 1);
        splitRunner.assertTransferCount(SplitText.REL_FAILURE, 0);

        final List<MockFlowFile> splits = splitRunner.getFlowFilesForRelationship(SplitText.REL_SPLITS);
        splits.get(0).assertContentEquals("\n\n1");
        splits.get(1).assertContentEquals("\n");
    }

}


text:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Features;
using Abp.Dependency;
using Abp.Runtime.Session;

namespace Abp.Web.Features
{
    public class FeaturesScriptManager : IFeaturesScriptManager, ITransientDependency
    {
        public IAbpSession AbpSession { get; set; }

        private readonly IFeatureManager _featureManager;
        private readonly IFeatureChecker _featureChecker;

        public FeaturesScriptManager(IFeatureManager featureManager, IFeatureChecker featureChecker)
        {
            _featureManager = featureManager;
            _featureChecker = featureChecker;

            AbpSession = NullAbpSession.Instance;
        }

        public async Task<string> GetScriptAsync()
        {
            var allFeatures = _featureManager.GetAll().ToList();
            var currentValues = new Dictionary<string, string>();

            if (AbpSession.TenantId.HasValue)
            {
                var currentTenantId = AbpSession.GetTenantId();
                foreach (var feature in allFeatures)
                {
                    currentValues[feature.Name] = await _featureChecker.GetValueAsync(currentTenantId, feature.Name);
                }
            }
            else
            {
                foreach (var feature in allFeatures)
                {
                    currentValues[feature.Name] = feature.DefaultValue;
                }
            }

            var script = new StringBuilder();

            script.AppendLine("(function() {");

            script.AppendLine();

            script.AppendLine("    abp.features = abp.features || {};");

            script.AppendLine();

            script.AppendLine("    abp.features.allFeatures = {");

            for (var i = 0; i < allFeatures.Count; i++)
            {
                var feature = allFeatures[i];
                script.AppendLine("        '" + feature.Name.Replace("'", @"\'") + "': {");
                script.AppendLine("             value: '" + currentValues[feature.Name].Replace(@"\", @"\\").Replace("'", @"\'") + "'");
                script.Append("        }");

                if (i < allFeatures.Count - 1)
                {
                    script.AppendLine(",");
                }
                else
                {
                    script.AppendLine();
                }
            }

            script.AppendLine("    };");

            script.AppendLine();
            script.Append("})();");

            return script.ToString();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'helper'

class TestMkerl < Test::Unit::TestCase
  def test_something_for_real
    flunk "hey buddy, you should probably rename this file and start testing for real"
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web;

namespace Hexdigits.DisplayModeMatrix
{
    public class Evidence : IEquatable<Evidence>
    {
        public string Name { get; set; }

        public Expression<Func<HttpContextBase, bool>> Expression { get; set; }

        internal double Weight { get; set; }

        public override string ToString() => $"{Name}, {Weight}: {Expression}";

        public bool Equals(Evidence another) => Name == another.Name;

        public override int GetHashCode() => Name.GetHashCode();
    }
}


text:
namespace ELua {

	/// <summary>
	/// @author Easily
	/// </summary>
	public class LuaVar : LuaObject {

		public string name;
		public LuaBinder binder;
		public LuaObject target;

		public LuaVar(LVM vm, string name, LuaBinder binder) : base(vm, Type.Var) {
			this.name = name;
			this.binder = binder;
			target = binder.target;
		    uid = vm.NewUID();
		}

	    public override void Bind(LuaObject obj) {
            target = obj;
            binder.Rebind(obj);
	    }

		public override LuaObject ToObject() {
			return target;
		}

        public override string ToString() {
			return name;
		}

	}

}


text:
import re

from zerver.lib.actions import do_add_realm_filter
from zerver.lib.test_classes import ZulipTestCase
from zerver.models import RealmFilter, get_realm

class RealmFilterTest(ZulipTestCase):

    def test_list(self) -> None:
        email = self.example_email('iago')
        self.login(email)
        realm = get_realm('zulip')
        do_add_realm_filter(
            realm,
            "#(?P<id>[123])",
            "https://realm.com/my_realm_filter/%(id)s")
        result = self.client_get("/json/realm/filters")
        self.assert_json_success(result)
        self.assertEqual(200, result.status_code)
        self.assertEqual(len(result.json()["filters"]), 1)

    def test_create(self) -> None:
        email = self.example_email('iago')
        self.login(email)
        data = {"pattern": "", "url_format_string": "https://realm.com/my_realm_filter/%(id)s"}
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_error(result, 'This field cannot be blank.')

        data['pattern'] = '$a'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_error(result, 'Invalid filter pattern.  Valid characters are [ a-zA-Z_#=/:+!-].')

        data['pattern'] = r'ZUL-(?P<id>\d++)'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_error(result, 'Invalid filter pattern.  Valid characters are [ a-zA-Z_#=/:+!-].')

        data['pattern'] = r'ZUL-(?P<id>\d+)'
        data['url_format_string'] = '$fgfg'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_error(result, 'Enter a valid URL.')

        data['pattern'] = r'ZUL-(?P<id>\d+)'
        data['url_format_string'] = 'https://realm.com/my_realm_filter/'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_error(result, 'Invalid URL format string.')

        data['url_format_string'] = 'https://realm.com/my_realm_filter/#hashtag/%(id)s'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_success(result)
        self.assertIsNotNone(re.match(data['pattern'], 'ZUL-15'))

        data['pattern'] = r'ZUL2-(?P<id>\d+)'
        data['url_format_string'] = 'https://realm.com/my_realm_filter/?value=%(id)s'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_success(result)
        self.assertIsNotNone(re.match(data['pattern'], 'ZUL2-15'))

        data['pattern'] = r'_code=(?P<id>[0-9a-zA-Z]+)'
        data['url_format_string'] = 'https://example.com/product/%(id)s/details'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_success(result)
        self.assertIsNotNone(re.match(data['pattern'], '_code=123abcdZ'))

        data['pattern'] = r'PR (?P<id>[0-9]+)'
        data['url_format_string'] = 'https://example.com/web#view_type=type&model=model&action=12345&id=%(id)s'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_success(result)
        self.assertIsNotNone(re.match(data['pattern'], 'PR 123'))

        data['pattern'] = r'lp/(?P<id>[0-9]+)'
        data['url_format_string'] = 'https://realm.com/my_realm_filter/?value=%(id)s&sort=reverse'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_success(result)
        self.assertIsNotNone(re.match(data['pattern'], 'lp/123'))

        data['pattern'] = r'lp:(?P<id>[0-9]+)'
        data['url_format_string'] = 'https://realm.com/my_realm_filter/?sort=reverse&value=%(id)s'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_success(result)
        self.assertIsNotNone(re.match(data['pattern'], 'lp:123'))

        data['pattern'] = r'!(?P<id>[0-9]+)'
        data['url_format_string'] = 'https://realm.com/index.pl?Action=AgentTicketZoom;TicketNumber=%(id)s'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_success(result)
        self.assertIsNotNone(re.match(data['pattern'], '!123'))

        # This is something we'd like to support, but don't currently;
        # this test is a reminder of something we should allow in the
        # future.
        data['pattern'] = r'(?P<org>[a-zA-Z0-9_-]+)/(?P<repo>[a-zA-Z0-9_-]+)#(?P<id>[0-9]+)'
        data['url_format_string'] = 'https://github.com/%(org)s/%(repo)s/issue/%(id)s'
        result = self.client_post("/json/realm/filters", info=data)
        self.assert_json_success(result)
        self.assertIsNotNone(re.match(data['pattern'], 'zulip/zulip#123'))

    def test_not_realm_admin(self) -> None:
        email = self.example_email('hamlet')
        self.login(email)
        result = self.client_post("/json/realm/filters")
        self.assert_json_error(result, 'Must be an organization administrator')
        result = self.client_delete("/json/realm/filters/15")
        self.assert_json_error(result, 'Must be an organization administrator')

    def test_delete(self) -> None:
        email = self.example_email('iago')
        self.login(email)
        realm = get_realm('zulip')
        filter_id = do_add_realm_filter(
            realm,
            "#(?P<id>[123])",
            "https://realm.com/my_realm_filter/%(id)s")
        filters_count = RealmFilter.objects.count()
        result = self.client_delete("/json/realm/filters/{0}".format(filter_id + 1))
        self.assert_json_error(result, 'Filter not found')

        result = self.client_delete("/json/realm/filters/{0}".format(filter_id))
        self.assert_json_success(result)
        self.assertEqual(RealmFilter.objects.count(), filters_count - 1)


text:
package de.hsbremen.powerwall.kinect.sandbox;

import com.jme3.app.SimpleApplication;
import com.jme3.asset.AssetManager;
import com.jme3.bullet.BulletAppState;
import com.jme3.input.InputManager;
import com.jme3.input.KeyInput;
import com.jme3.input.controls.ActionListener;
import com.jme3.input.controls.KeyTrigger;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.post.FilterPostProcessor;
import com.jme3.post.filters.BloomFilter;
import com.jme3.renderer.ViewPort;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Node;
import com.jme3.shadow.DirectionalLightShadowFilter;
import com.jme3.shadow.DirectionalLightShadowRenderer;
import com.jme3.shadow.EdgeFilteringMode;
import com.jme3.texture.Texture;
import com.jme3.texture.Texture.WrapMode;
import com.jme3.util.SkyFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Scene class which creates the actual Sandbox with all its objects in it
 * @author Jan Schulte
 */
public class Scene  implements ActionListener {

	// constants
	public static final float		GROUND_SIZE = 40.0f;

	public static final float		BOX_SIZE_MIN = 0.4f;
	public static final float		BOX_SIZE_MAX = 1.0f;
	public static final float		BOX_MASS = 4.0f;
	public static final int			BOX_COUNT = 20;
	public static final float		BOX_SPAWN_HEIGHT = 8.0f;

	public static final float		CONTROLLER_SIZE = 1.4f;
	public static final float		CONTROLLER_MASS = 0.0f;
	public static final float		CONTROLLER_MIN_HEIGHT = 1.6f;
	public static final float		CONTROLLER_MAX_HEIGHT = 100.0f;

	public static final boolean		STEREO_CAMERA = true;
	public static final boolean		MOUSE_INPUT = false;

	// global objects
	private SimpleApplication		mApplication = null;
    private BulletAppState			mBulletAppState = null;
	private KinectController		mKinectController = null;
	private Camera					mCamera = null;

	// Scene objects
	private DirectionalLight		mSunLight = null;
	private List<SceneObject>		mObjects = new ArrayList<SceneObject>();

    // helper objects
	private Random					mRandom = new Random();

	/**
	 *  Contructor
	 */
    public Scene(SimpleApplication _application) {
		mApplication = _application;

		// create jBullet Physics
		mBulletAppState = new BulletAppState();
		mBulletAppState.setThreadingType(BulletAppState.ThreadingType.PARALLEL);
		mApplication.getStateManager().attach(mBulletAppState);
		//mBulletAppState.getPhysicsSpace().enableDebug(mApplication.getAssetManager());

		// create Scene
		create();
	}

    private void create() {
		createGround();
		createBoxes();
		createController();

		setupScene();
	}

	public void reset() {
		int minGroundSize = -(int)(GROUND_SIZE / 2.0f);
		int maxGroundSize = (-1) * minGroundSize;

		for (SceneObject object : mObjects) {
			// spawn box at random location
			int x = randInt(minGroundSize, maxGroundSize);
			int z = randInt(minGroundSize, maxGroundSize);

			object.setPosition(new Vector3f(x, BOX_SPAWN_HEIGHT, z));
			object.getController().activate();
		}
	}

	public void update(float _delta) {
		if (mCamera != null) {
			mCamera.update(_delta);
		}
		if (mKinectController != null) {
			mKinectController.update(_delta);
		}
	}

	private void setupScene() {
		// get global objects
		AssetManager assetManager = mApplication.getAssetManager();
		Node rootNode = mApplication.getRootNode();
		//ViewPort viewPort = mApplication.getViewPort();
		InputManager inputManager = mApplication.getInputManager();

		//init input
		inputManager.addMapping("reset", new KeyTrigger(KeyInput.KEY_R));
		inputManager.addListener(this, "reset");

		// add skysphere
		Texture west = assetManager.loadTexture("Textures/skybox/lefttron.jpg");
		Texture east =  assetManager.loadTexture("Textures/skybox/righttron.jpg");
		Texture north = assetManager.loadTexture("Textures/skybox/fronttron.jpg");
		Texture south =  assetManager.loadTexture("Textures/skybox/backtron.jpg");
		Texture up =  assetManager.loadTexture("Textures/skybox/uptron.jpg");
		Texture down =  assetManager.loadTexture("Textures/skybox/downtron.jpg");
		rootNode.attachChild(SkyFactory.createSky(assetManager, west, east, north, south, up, down));

		// create ambient light
		AmbientLight al = new AmbientLight();
        al.setColor(ColorRGBA.White.mult(0.3f));
        rootNode.addLight(al);

		// Directional Light
		mSunLight = new DirectionalLight();
		mSunLight.setColor(ColorRGBA.White);
		mSunLight.setDirection(new Vector3f(0.0f, -1.0f, -1.0f).normalizeLocal());
		mApplication.getRootNode().addLight(mSunLight);

		// setup shadow renderer
		final int SHADOWMAP_SIZE = 1024;
        DirectionalLightShadowRenderer dlsr1 = new DirectionalLightShadowRenderer(assetManager, SHADOWMAP_SIZE, 3);
        dlsr1.setLight(mSunLight);
		dlsr1.setLambda(0.55f);
        dlsr1.setShadowIntensity(0.6f);
        dlsr1.setEdgeFilteringMode(EdgeFilteringMode.Bilinear);
        //dlsr.displayDebug();
		if (mCamera.isSingleView()) {
			mCamera.addProcessor(dlsr1);
		} else {
			mCamera.addProcessorRight(dlsr1);
		}

		if (!mCamera.isSingleView()) {
			DirectionalLightShadowRenderer dlsr2 = new DirectionalLightShadowRenderer(assetManager, SHADOWMAP_SIZE, 3);
			dlsr2.setLight(mSunLight);
			dlsr2.setLambda(0.55f);
			dlsr2.setShadowIntensity(0.6f);
			dlsr2.setEdgeFilteringMode(EdgeFilteringMode.Bilinear);
			mCamera.addProcessorLeft(dlsr2);
		}

		FilterPostProcessor fpp1 = new FilterPostProcessor(assetManager);
        DirectionalLightShadowFilter dlsf1 = new DirectionalLightShadowFilter(assetManager, SHADOWMAP_SIZE, 3);
        dlsf1.setLight(mSunLight);
        dlsf1.setEnabled(true);
		dlsf1.setLambda(0.55f);
        dlsf1.setShadowIntensity(0.6f);
        dlsf1.setEdgeFilteringMode(EdgeFilteringMode.Bilinear);
        fpp1.addFilter(dlsf1);

		// glow filter
		BloomFilter bloom1 = new BloomFilter(BloomFilter.GlowMode.Objects);
		bloom1.setBloomIntensity(4.0f);
		bloom1.setBlurScale(1.0f);
		fpp1.addFilter(bloom1);

		if (mCamera.isSingleView()) {
			mCamera.addProcessor(fpp1);
		} else {
			mCamera.addProcessorRight(fpp1);

			FilterPostProcessor fpp2 = new FilterPostProcessor(assetManager);
			DirectionalLightShadowFilter dlsf2 = new DirectionalLightShadowFilter(assetManager, SHADOWMAP_SIZE, 3);
			dlsf2.setLight(mSunLight);
			dlsf2.setEnabled(true);
			dlsf2.setLambda(0.55f);
			dlsf2.setShadowIntensity(0.6f);
			dlsf2.setEdgeFilteringMode(EdgeFilteringMode.Bilinear);
			fpp1.addFilter(dlsf2);

			// glow filter
			BloomFilter bloom2 = new BloomFilter(BloomFilter.GlowMode.Objects);
			bloom2.setBloomIntensity(4.0f);
			bloom2.setBlurScale(1.0f);
			fpp2.addFilter(bloom2);
			mCamera.addProcessorLeft(fpp2);
		}
	}

	private void createGround() {
		// get global objects
		AssetManager assetManager = mApplication.getAssetManager();
		Node rootNode = mApplication.getRootNode();

		// create ground & add to scene
		Material material = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");

		Texture diffuseTexture = assetManager.loadTexture("Textures/skybox/downtron.jpg");
		//Texture diffuseTexture = assetManager.loadTexture("Textures/ground_02.png");
		//Texture normalTexture = assetManager.loadTexture("Textures/ground_02_n.png");
		//diffuseTexture.setMinFilter(Texture.MinFilter.Trilinear);
		//diffuseTexture.setMagFilter(Texture.MagFilter.Bilinear);
		//diffuseTexture.setAnisotropicFilter(16);
		diffuseTexture.setWrap(WrapMode.Repeat);
		//normalTexture.setWrap(WrapMode.Repeat);

		material.setTexture("DiffuseMap", diffuseTexture);
		//material.setTexture("NormalMap", normalTexture);
		material.setBoolean("UseMaterialColors",true);
		material.setColor("Diffuse",ColorRGBA.White);
		material.setColor("Specular",ColorRGBA.White);
		material.setFloat("Shininess", 64f);  // [0,128]

		BoxObject ground = new BoxObject("Ground", new Vector3f(0.0f, 0.0f, 0.0f), new Vector3f(GROUND_SIZE, 0.1f, GROUND_SIZE), material, 0.0f, new Vector2f(4.0f, 4.0f));
		addToScene(ground);
	}

	private void createBoxes() {
		// get global objects
		AssetManager assetManager = mApplication.getAssetManager();

		// create ground & add to scene
		/*
		Material material = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
		Texture diffuseTexture = assetManager.loadTexture("Textures/crate_02.png");
		material.setTexture("ColorMap", diffuseTexture);
		*/

		Texture diffuseTexture_01 = assetManager.loadTexture("Textures/crate_02.png");
		Texture normalTexture_01 = assetManager.loadTexture("Textures/crate_02_n.png");
		Texture diffuseTexture_02 = assetManager.loadTexture("Textures/crate_03.png");
		Texture normalTexture_02 = assetManager.loadTexture("Textures/crate_03_n.png");

		//diffuseTexture.setMinFilter(Texture.MinFilter.Trilinear);
		//diffuseTexture.setMagFilter(Texture.MagFilter.Bilinear);
		//diffuseTexture.setAnisotropicFilter(16);
		diffuseTexture_01.setWrap(WrapMode.Repeat);
		normalTexture_01.setWrap(WrapMode.Repeat);
		diffuseTexture_02.setWrap(WrapMode.Repeat);
		normalTexture_02.setWrap(WrapMode.Repeat);

		int minGroundSize = -(int)(GROUND_SIZE / 2.0f);
		int maxGroundSize = (-1) * minGroundSize;

		for (int i = 0; i < BOX_COUNT; ++i) {
			int textureId = randInt(0, 1);

			Material material = new Material(assetManager, "Common/MatDefs/Light/Lighting.j3md");
			if (textureId == 0)
			{
				material.setTexture("DiffuseMap", diffuseTexture_01);
				material.setTexture("NormalMap", normalTexture_01);
			}
			else
			{
				material.setTexture("DiffuseMap", diffuseTexture_02);
				material.setTexture("NormalMap", normalTexture_02);
			}
			material.setBoolean("UseMaterialColors",true);
			material.setColor("Diffuse",ColorRGBA.White);
			material.setColor("Specular",ColorRGBA.White);
			material.setFloat("Shininess", 128f);  // [0,128]

			// spawn box at random location
			int x = randInt(minGroundSize, maxGroundSize);
			int z = randInt(minGroundSize, maxGroundSize);
			float size = randFloat(BOX_SIZE_MIN, BOX_SIZE_MAX);

			BoxObject ground = new BoxObject("box_" + i, new Vector3f(x, BOX_SPAWN_HEIGHT, z), new Vector3f(size, size, size), material, BOX_MASS * size, null);
			addToScene(ground);
		}
	}

	private void createController() {
		// get global objects
		AssetManager assetManager = mApplication.getAssetManager();

		// create sphere based controller
		Material material = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
		material.setColor("Color", new ColorRGBA(0.2f, 0.2f, 1.0f, 0.7f));
		material.setColor("GlowColor", ColorRGBA.Blue);
		material.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);

		SphereObject controller = new SphereObject("Controller", new Vector3f(0.0f, 1.0f, 6.0f), CONTROLLER_SIZE, material, CONTROLLER_MASS);
		controller.setQueueBucket(Bucket.Transparent);
		addToScene(controller);
		mBulletAppState.getPhysicsSpace().add(controller.getGhostController());

		// create camera
		if (STEREO_CAMERA) {
			mCamera = new StereoCamera(mApplication, controller);
		} else {
			mCamera = new ChaseCamera(mApplication, controller);
		}
		// create kinect controller
		mKinectController = new KinectController(mApplication, mBulletAppState, controller, mCamera);
		mBulletAppState.getPhysicsSpace().addCollisionListener(mKinectController);
	}

	private void addToScene(SceneObject _object) {
		mApplication.getRootNode().attachChild(_object);
		mBulletAppState.getPhysicsSpace().add(_object.getController());

		if (!_object.getName().equals("Controller") && !_object.getName().equals("Ground")) {
			mObjects.add(_object);
		}
	}

	public int randInt(int _min, int _max) {
		return mRandom.nextInt((_max - _min) + 1) + _min;
	}

	public float randFloat(float _min, float _max) {
		return (float) (_min + (Math.random() * ((_max - _min) + 1.0f)));
	}

	public void onAction(String _name, boolean _isPressed, float _tpf) {
		if (_name.equals("reset") && _isPressed) {
			reset();
        }
	}

}


text:
package io.vertx.codegen.rxjava2;

import io.vertx.codegen.annotations.Nullable;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;

/**
 * @author Julien Viet
 */
@VertxGen
public interface MethodWithMaybeString {
  void doSomethingWithMaybeResult(Handler<AsyncResult<@Nullable String>> handler);
}


text:
content_title: Nodeos Troubleshooting
---

### "Database dirty flag set (likely due to unclean shutdown): replay required"

`nodeos` needs to be shut down cleanly. To ensure this is done, send a `SIGTERM`, `SIGQUIT` or `SIGINT` and wait for the process to shutdown. Failing to do this will result in this error. If you get this error, your only recourse is to replay by starting `nodeos` with `--replay-blockchain`

### "Memory does not match data" Error at Restart

If you get an error such as `St9exception: content of memory does not match data expected by executable` when trying to start `nodeos`, try restarting `nodeos` with one of the following options (you can use `nodeos --help` to get a full listing of these).

```
Command Line Options for eosio::chain_plugin:
    --fix-reversible-blocks               recovers reversible block database if
                                          that database is in a bad state
    --force-all-checks                    do not skip any checks that can be
                                          skipped while replaying irreversible
                                          blocks
    --replay-blockchain                   clear chain state database and replay
                                          all blocks
    --hard-replay-blockchain              clear chain state database, recover as
                                          many blocks as possible from the block
                                          log, and then replay those blocks
    --delete-all-blocks                   clear chain state database and block
                                          log
```

### "Could not grow database file to requested size." Error

Start `nodeos` with `--shared-memory-size-mb 1024`. A 1 GB shared memory file allows approximately half a million transactions.

### What version of EOSIO am I running/connecting to?

If defaults can be used, then `cleos get info` will output a block that contains a field called `server_version`.  If your `nodeos` is not using the defaults, then you need to know the URL of the `nodeos`. In that case, use the following with your `nodeos` URL:

```sh
cleos --url http://localhost:8888 get info
```

To focus only on the version line within the block:

```sh
cleos --url http://localhost:8888 get info | grep server_version
```

### Error 3070000: WASM Exception Error

If you try to deploy the `eosio.bios` contract or `eosio.system` contract in an attempt to boot an EOSIO-based blockchain and you get the following error or similar: `Publishing contract... Error 3070000: WASM Exception Error Details: env.set_proposed_producers_ex unresolveable`, it is because you have to activate the `PREACTIVATE_FEATURE` protocol first. More details about it and how to enable it can be found in the [Bios Boot Sequence Tutorial](https://developers.eos.io/welcome/v2.1/tutorials/bios-boot-sequence/#112-set-the-eosiosystem-contract). For more information, you may also visit the [Nodeos Upgrade Guides](https://developers.eos.io/manuals/eos/latest/nodeos/upgrade-guides/).


text:
package org.apache.geode.management.internal.configuration.mutators;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;

import org.apache.geode.cache.configuration.CacheConfig;
import org.apache.geode.cache.configuration.DiskStoreType;
import org.apache.geode.distributed.ConfigurationPersistenceService;
import org.apache.geode.management.configuration.DiskStore;
import org.apache.geode.management.internal.configuration.converters.DiskStoreConverter;

public class DiskStoreManager extends CacheConfigurationManager<DiskStore> {
  private final DiskStoreConverter diskStoreConverter = new DiskStoreConverter();

  public DiskStoreManager(ConfigurationPersistenceService service) {
    super(service);
  }

  @Override
  public void add(DiskStore config, CacheConfig existing) {
    List<DiskStoreType> diskStoreTypes = existing.getDiskStores();
    if (diskStoreTypes.stream().noneMatch(diskStoreType -> diskStoreType.getName()
        .equals(config.getName()))) {
      diskStoreTypes.add(diskStoreConverter.fromConfigObject(config));
    }
  }

  @Override
  public void update(DiskStore config, CacheConfig existing) {
    throw new IllegalStateException("Not implemented");
  }

  @Override
  public void delete(DiskStore config, CacheConfig existing) {
    existing.getDiskStores().stream()
        .filter(diskStoreType -> config.getName().equals(diskStoreType.getName())).findFirst()
        .ifPresent(diskStore -> existing.getDiskStores().remove(diskStore));
  }

  @Override
  public List<DiskStore> list(DiskStore filterConfig, CacheConfig existing) {
    return existing.getDiskStores().stream()
        .filter(diskStoreType -> StringUtils.isEmpty(filterConfig.getName())
            || filterConfig.getName().equals(diskStoreType.getName()))
        .map(diskStoreConverter::fromXmlObject).collect(Collectors.toList());
  }

  @Override
  public DiskStore get(DiskStore config, CacheConfig existing) {
    return existing.getDiskStores().stream()
        .filter(diskStoreType -> diskStoreType.getName().equals(config.getName())).map(
            diskStoreConverter::fromXmlObject)
        .findFirst().orElse(null);
  }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="net.tomorrowletter.tomorrow.dao.UserDao" >
    <resultMap id="base_result_map" type="net.tomorrowletter.tomorrow.web.model.User" >
        <id column="uuid" property="uuid" jdbcType="VARCHAR" />
        <result column="nickname" property="nickname" jdbcType="VARCHAR" />
        <result column="tel" property="tel" jdbcType="VARCHAR" />
        <result column="email" property="email" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="wechat_id" property="wechatId" jdbcType="VARCHAR" />
    </resultMap>

    <sql id="base_column_list" >
        uuid, nickname, tel, email, password, wechat_id
    </sql>

    <select id="getUsers" resultMap="base_result_map">
        select
        <include refid="base_column_list" />
        from user
    </select>

    <insert id="addUser" parameterType="net.tomorrowletter.tomorrow.web.model.User">
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="uuid != null">uuid,</if>
            <if test="nickname != null">nickname,</if>
            <if test="tel != null">tel,</if>
            <if test="email != null">email,</if>
            <if test="password != null">password,</if>
            <if test="wechatId != null">wechat_id,</if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="uuid != null">#{uuid,jdbcType=VARCHAR},</if>
            <if test="nickname != null">#{nickname,jdbcType=INTEGER},</if>
            <if test="tel != null">#{tel,jdbcType=VARCHAR},</if>
            <if test="email != null">#{email,jdbcType=VARCHAR},</if>
            <if test="password != null">#{password,jdbcType=VARCHAR},</if>
            <if test="wechatId != null">#{wechatId,jdbcType=VARCHAR}</if>
        </trim>
    </insert>

    <update id="updateUser" parameterType="net.tomorrowletter.tomorrow.web.model.User">
        update user
        <set>
            <if test="nickname != null">nickname = #{nickname,jdbcType=INTEGER},</if>
            <if test="tel != null">tel = #{tel,jdbcType=VARCHAR},</if>
            <if test="email != null">email = #{email,jdbcType=VARCHAR},</if>
            <if test="password != null">password = #{password,jdbcType=VARCHAR},</if>
            <if test="wechatId != null">wechat_id = #{wechatId,jdbcType=BIGINT}</if>
        </set>
        where uuid = #{uuid,jdbcType=VARCHAR}
    </update>
</mapper>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE topic PUBLIC "urn:pubid:dita4publishers.sourceforge.net/doctypes/dita/topic" "urn:pubid:dita4publishers.sourceforge.net/doctypes/dita/topic">
<topic
  id="topic-id">
  <title>Version 0.8 Release Notes</title>

Version 0.8 is the first public release of the DOCX2DITA transform. It has the following
      noteable limitations:

Fields are not handled in any way, including xrefs, footnotes, etc.

Inline format changes (bold, italic, etc.) are ignored.

</topic>


text:
from django.contrib.auth import authenticate, login
from django.core.cache import cache
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required

from game.users.models import User
from game.contrib.random_user import random_user

from .forms import ExitSurvey, CheckForm
from .models import InteractiveStatic, Settings

def assign(request):
    if request.method == 'POST':
        return redirect('static_mode:instruction')
    return render(request, 'pages/home2.html')

# Create your views here.
@login_required(login_url='static_mode:instruction')
def lobby(request):
    if cache.get('interactive_static_instruction_{}'.format(request.user.id)):
        return render(request, 'interactive_static/lobby.html')
    return redirect('static_mode:instruction')

@login_required(login_url='/')
def exit_survey(request):
    """
    username = models.CharField(max_length=255, blank=True, null=True)
    game = models.OneToOneField(Interactive)
    age = models.PositiveSmallIntegerField(null=True)
    gender = models.CharField(max_length=10, choices=(('m', 'Male'),
                                                      ('f', 'Female'),
                                                      ), blank=True, null=True)
    feedback = models.TextField(null=True)
    :param request:
    :return:
    """
    form = ExitSurvey(request.POST or None)
    u = User.objects.get(username=request.user.username)
    u.exited = True
    u.save()
    if request.method == 'POST':
        if form.is_valid():
            try:
                game = InteractiveStatic.objects.get(users=u)
                game_id = game.id
            except InteractiveStatic.DoesNotExist:
                game_id = -1
            instance = form.save(commit=False)
            instance.username = u.username
            instance.game = game_id
            instance.save()
            return redirect('static_mode:done')
        else:
            print('NOT Valid')
    return render(request, 'control/survey.html', {'form': form, 'score': round(request.user.get_score * .25, 2)})

def done(request):
    return render(request, 'interactive_static/done.html')

def instruction(request):
    form = CheckForm(request.POST or None)
    if request.user.is_anonymous:
        u, password = random_user('static')
        u = authenticate(username=u.username, password=password)
        login(request, u)
        cache.set('interactive_static_instruction_{}'.format(u.id), False)
    else:
        u = request.user
        if u.game_type != 'static':
            return redirect('/')
    if request.method == 'POST':
        if form.is_valid():
            cache.set('interactive_static_instruction_{}'.format(u.id), True)
            return redirect('static_mode:lobby')
    game_settings = Settings.objects.order_by('?')[0]
    cache.set('interactive_static_instruction_{}'.format(u.id), True)
    return render(request, 'interactive_static/instructions.html', {'players_num': game_settings.max_users,
                                                                    'rounds_num': game_settings.max_rounds,
                                                                    'following_num': game_settings.max_following,
                                                                    'form': form,
                                                                    })


text:
package org.trade.core.notifiers.provided;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import org.trade.core.auditing.events.InstanceStateChangeEvent;
import org.trade.core.auditing.events.ModelStateChangeEvent;
import org.trade.core.model.notification.Notification;
import org.trade.core.notifiers.INotifierService;
import org.trade.core.utils.NotifierProperties;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hahnml on 12.05.2017.
 */
public enum NotificationMessageFactory {
    INSTANCE;

    private Configuration configuration;

    private NotifierProperties properties;

    NotificationMessageFactory() {
        properties = new NotifierProperties();

        Path dir = Paths.get(properties.getNotificationMessageTemplateDirectory());

        // Check if the path is relative to make it absolute if required
        if (!dir.isAbsolute()) {
            dir = Paths.get(".", properties.getNotificationMessageTemplateDirectory()).toAbsolutePath().normalize();
        }

        configuration = new Configuration(Configuration.VERSION_2_3_26);
        try {
            configuration.setDirectoryForTemplateLoading(dir.toFile());
        } catch (IOException e) {
            e.printStackTrace();
        }

        DefaultObjectWrapperBuilder owb = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_26);

        configuration.setDefaultEncoding("UTF-8");
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        configuration.setLogTemplateExceptions(false);
        configuration.setObjectWrapper(owb.build());
    }

    public Template getMessageTemplate(String templateName) throws Exception {
        // Resolve and return the template
        return this.configuration.getTemplate(templateName);
    }

    public Template getMessageTemplate(INotifierService service, String messageFormat) throws Exception {
        // Resolve and return the template
        return this.configuration.getTemplate(properties.getNotifierMessageTemplate(service.getNotifierServiceId(), messageFormat));
    }

    public String createMessage(INotifierService service, String message, Notification notification, Object
            notificationSource, String messageFormat) throws Exception {
        String result;

        String resourceURL = notification.getResourceURL();

        if (message == null || message.isEmpty()) {
            // Generate a message
            if (notificationSource instanceof ModelStateChangeEvent || notificationSource instanceof
                    InstanceStateChangeEvent) {
                // Resolve the correct template
                Template temp = getMessageTemplate(service, messageFormat);

                Map<String, Object> data = new HashMap<>();
                data.put("notification", notification);
                data.put("notificationSource", notificationSource);

                Writer out = new StringWriter();
                temp.process(data, out);
                result = out.toString();
            } else {
                result = notificationSource.toString() + "\n" + "TraDE URL: " + resourceURL;
            }
        } else {
            result = message;
        }

        return result;
    }
}


text:
blockcheck
==========

Утилита для определения типа блокировок сайтов из единого реестра запрещенной информации на стороне провайдера.

Данная утилита позволяет определить:

* Подмену DNS-ответов
* Перенаправление DNS-серверов
* Блокировку DNS-серверов
* "Обычный" DPI (фильтрация URL на определенных IP-адресах и портах)
* "Полный" DPI (фильтрация URL на всех IP-адресах и/или портах)
* Подмену SSL(HTTPS)-сертификата (прослушивание HTTPS-трафика)
* Блокировку по IP-адресу

Приложение автоматически отправляет статистику об используемом типе блокировки на сервер.

http://habrahabr.ru/post/229377/ — статистика по провайдерам


text:
extern crate robin_core;

#[cfg(test)]
mod parser_tests {
    use robin_core::ast::{BooleanExpression, Expression, IdentifierExpression, ListExpression,
                          NumberExpression};
    use robin_core::parser::ExprsParser;

    #[test]
    fn parse_an_empty_list() {
        let expr = Expression::List(ListExpression::new_unquoted(vec![]));

        let parser = ExprsParser::new();

        assert_eq!(parser.parse("()"), Ok(vec![expr]));
    }

    #[test]
    fn parse_a_list_with_one_value() {
        let expr = Expression::List(ListExpression::new_unquoted(vec![Box::new(
            Expression::Identifier(IdentifierExpression::new("hello".to_string())),
        )]));

        let parser = ExprsParser::new();

        assert_eq!(parser.parse("(hello)"), Ok(vec![expr]));
    }

    #[test]
    fn parse_a_list_with_multiple_values() {
        let expr = Expression::List(ListExpression::new_unquoted(vec![
            Box::new(Expression::Identifier(IdentifierExpression::new(
                "hello".to_string(),
            ))),
            Box::new(Expression::Boolean(BooleanExpression::new(true))),
        ]));

        let parser = ExprsParser::new();

        assert_eq!(parser.parse("(hello true)"), Ok(vec![expr]));
    }

    #[test]
    fn parse_a_list_with_symbols() {
        let expr = Expression::List(ListExpression::new_unquoted(vec![Box::new(
            Expression::Identifier(IdentifierExpression::new("+".to_string())),
        )]));

        let parser = ExprsParser::new();

        assert_eq!(parser.parse("(+)"), Ok(vec![expr]));
    }

    #[test]
    fn parse_a_list_with_multiple_symbols() {
        let expr = Expression::List(ListExpression::new_unquoted(vec![
            Box::new(Expression::Identifier(IdentifierExpression::new(
                "+".to_string(),
            ))),
            Box::new(Expression::Number(NumberExpression::new(1 as f64))),
            Box::new(Expression::Number(NumberExpression::new(1 as f64))),
        ]));

        let parser = ExprsParser::new();

        assert_eq!(parser.parse("(+ 1 1)"), Ok(vec![expr]));
    }
}


text:
namespace Microsoft.Azure.Management.Compute.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Encryption settings for disk or snapshot
    /// </summary>
    public partial class EncryptionSettingsCollection
    {
        /// <summary>
        /// Initializes a new instance of the EncryptionSettingsCollection
        /// class.
        /// </summary>
        public EncryptionSettingsCollection()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the EncryptionSettingsCollection
        /// class.
        /// </summary>
        /// <param name="enabled">Set this flag to true and provide
        /// DiskEncryptionKey and optional KeyEncryptionKey to enable
        /// encryption. Set this flag to false and remove DiskEncryptionKey and
        /// KeyEncryptionKey to disable encryption. If EncryptionSettings is
        /// null in the request object, the existing settings remain
        /// unchanged.</param>
        /// <param name="encryptionSettings">A collection of encryption
        /// settings, one for each disk volume.</param>
        /// <param name="encryptionSettingsVersion">Describes what type of
        /// encryption is used for the disks. Once this field is set, it cannot
        /// be overwritten. '1.0' corresponds to Azure Disk Encryption with AAD
        /// app.'1.1' corresponds to Azure Disk Encryption.</param>
        public EncryptionSettingsCollection(bool enabled, IList<EncryptionSettingsElement> encryptionSettings = default(IList<EncryptionSettingsElement>), string encryptionSettingsVersion = default(string))
        {
            Enabled = enabled;
            EncryptionSettings = encryptionSettings;
            EncryptionSettingsVersion = encryptionSettingsVersion;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets set this flag to true and provide DiskEncryptionKey
        /// and optional KeyEncryptionKey to enable encryption. Set this flag
        /// to false and remove DiskEncryptionKey and KeyEncryptionKey to
        /// disable encryption. If EncryptionSettings is null in the request
        /// object, the existing settings remain unchanged.
        /// </summary>
        [JsonProperty(PropertyName = "enabled")]
        public bool Enabled { get; set; }

        /// <summary>
        /// Gets or sets a collection of encryption settings, one for each disk
        /// volume.
        /// </summary>
        [JsonProperty(PropertyName = "encryptionSettings")]
        public IList<EncryptionSettingsElement> EncryptionSettings { get; set; }

        /// <summary>
        /// Gets or sets describes what type of encryption is used for the
        /// disks. Once this field is set, it cannot be overwritten. '1.0'
        /// corresponds to Azure Disk Encryption with AAD app.'1.1' corresponds
        /// to Azure Disk Encryption.
        /// </summary>
        [JsonProperty(PropertyName = "encryptionSettingsVersion")]
        public string EncryptionSettingsVersion { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="Rest.ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (EncryptionSettings != null)
            {
                foreach (var element in EncryptionSettings)
                {
                    if (element != null)
                    {
                        element.Validate();
                    }
                }
            }
        }
    }
}


text:
package com.github.ambry.clustermap;

import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Metrics for the {@link HelixClusterManager}
 */
class HelixClusterManagerMetrics {
  private final HelixClusterManager.HelixClusterManagerCallback clusterMapCallback;
  private final MetricRegistry registry;

  public final Counter liveInstanceChangeTriggerCount;
  public final Counter instanceConfigChangeTriggerCount;
  public final Counter idealStateChangeTriggerCount;
  public final Counter routingTableChangeTriggerCount;
  public final Counter getPartitionIdFromStreamMismatchCount;
  public final Counter getWritablePartitionIdsMismatchCount;
  public final Counter getAllPartitionIdsMismatchCount;
  public final Counter hasDatacenterMismatchCount;
  public final Counter getDatacenterNameMismatchCount;
  public final Counter getDataNodeIdMismatchCount;
  public final Counter getReplicaIdsMismatchCount;
  public final Counter getDataNodeIdsMismatchCount;
  public final Counter ignoredUpdatesCount;
  public final Counter instanceConfigChangeErrorCount;

  public Gauge<Long> helixClusterManagerInstantiationFailed;
  public Gauge<Long> helixClusterManagerRemoteInstantiationFailed;
  public Gauge<Long> helixClusterManagerCurrentXid;

  /**
   * Metrics for the {@link HelixClusterManager}
   * @param registry The {@link MetricRegistry} associated with the {@link HelixClusterManager}
   * @param  clusterMapCallback The {@link HelixClusterManager.HelixClusterManagerCallback} used to query information
   *                            from {@link HelixClusterManager}
   */
  HelixClusterManagerMetrics(MetricRegistry registry,
      final HelixClusterManager.HelixClusterManagerCallback clusterMapCallback) {
    this.clusterMapCallback = clusterMapCallback;
    this.registry = registry;
    liveInstanceChangeTriggerCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "liveInstanceChangeTriggerCount"));
    instanceConfigChangeTriggerCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "instanceConfigChangeTriggerCount"));
    idealStateChangeTriggerCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "idealStateChangeTriggerCount"));
    routingTableChangeTriggerCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "routingTableChangeTriggerCount"));
    getPartitionIdFromStreamMismatchCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "getPartitionIdFromStreamMismatchCount"));
    getWritablePartitionIdsMismatchCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "getWritablePartitionIdsMismatchCount"));
    getAllPartitionIdsMismatchCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "getAllPartitionIdsMismatchCount"));
    hasDatacenterMismatchCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "hasDatacenterMismatchCount"));
    getDatacenterNameMismatchCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "getDatacenterNameMismatchCount"));
    getDataNodeIdMismatchCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "getDataNodeIdMismatchCount"));
    getReplicaIdsMismatchCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "getReplicaIdsMismatchCount"));
    getDataNodeIdsMismatchCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "getDataNodeIdsMismatchCount"));
    ignoredUpdatesCount = registry.counter(MetricRegistry.name(HelixClusterManager.class, "ignoredUpdatesCount"));
    instanceConfigChangeErrorCount =
        registry.counter(MetricRegistry.name(HelixClusterManager.class, "instanceConfigChangeErrorCount"));
  }

  void initializeInstantiationMetric(final boolean instantiated, final long instantiationExceptionCount) {
    helixClusterManagerInstantiationFailed = () -> instantiated ? 0L : 1L;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "instantiationFailed"),
        helixClusterManagerInstantiationFailed);

    helixClusterManagerRemoteInstantiationFailed = () -> instantiationExceptionCount;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "instantiationExceptionCount"),
        helixClusterManagerRemoteInstantiationFailed);
  }

  void initializeXidMetric(final AtomicLong currentXid) {
    helixClusterManagerCurrentXid = currentXid::get;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "currentXid"), helixClusterManagerCurrentXid);
  }

  /**
   * Initialize datacenter related metrics.
   */
  void initializeDatacenterMetrics() {
    Gauge<Long> datacenterCount = clusterMapCallback::getDatacenterCount;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "datacenterCount"), datacenterCount);
  }

  /**
   * Initialize datanode related metrics.
   */
  void initializeDataNodeMetrics() {
    Gauge<Long> dataNodeCount = clusterMapCallback::getDatanodeCount;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "dataNodeCount"), dataNodeCount);

    Gauge<Long> dataNodeDownCount = clusterMapCallback::getDownDatanodesCount;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "dataNodeDownCount"), dataNodeDownCount);

    for (final AmbryDataNode datanode : clusterMapCallback.getDatanodes()) {
      final String metricName = datanode.getHostname() + "-" + datanode.getPort() + "-DataNodeResourceState";
      Gauge<Long> dataNodeState = () -> datanode.getState() == HardwareState.AVAILABLE ? 1L : 0L;
      registry.register(MetricRegistry.name(HelixClusterManager.class, metricName), dataNodeState);
    }
  }

  /**
   * Initialize disk related metrics.
   */
  void initializeDiskMetrics() {
    Gauge<Long> diskCount = clusterMapCallback::getDiskCount;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "diskCount"), diskCount);

    Gauge<Long> diskDownCount = clusterMapCallback::getDownDisksCount;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "diskDownCount"), diskDownCount);

    for (final AmbryDisk disk : clusterMapCallback.getDisks(null)) {
      final String metricName =
          disk.getDataNode().getHostname() + "-" + disk.getDataNode().getPort() + "-" + disk.getMountPath()
              + "-DiskResourceState";
      Gauge<Long> diskState = () -> disk.getState() == HardwareState.AVAILABLE ? 1L : 0L;
      registry.register(MetricRegistry.name(HelixClusterManager.class, metricName), diskState);
    }
  }

  /**
   * Initialize partition related metrics.
   */
  void initializePartitionMetrics() {
    Gauge<Long> partitionCount = clusterMapCallback::getPartitionCount;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "partitionCount"), partitionCount);

    Gauge<Long> partitionReadWriteCount = clusterMapCallback::getPartitionReadWriteCount;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "partitionReadWriteCount"),
        partitionReadWriteCount);

    Gauge<Long> partitionSealedCount = clusterMapCallback::getPartitionSealedCount;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "partitionSealedCount"), partitionSealedCount);

    Gauge<Long> isMajorityReplicasDownForAnyPartition = () -> {
      for (PartitionId partition : clusterMapCallback.getPartitions()) {
        List<? extends ReplicaId> replicas = partition.getReplicaIds();
        int replicaCount = replicas.size();
        int downReplicas = 0;
        for (ReplicaId replicaId : replicas) {
          if (replicaId.isDown()) {
            downReplicas++;
          }
        }
        if (downReplicas > replicaCount / 2) {
          return 1L;
        }
      }
      return 0L;
    };
    registry.register(MetricRegistry.name(HelixClusterManager.class, "isMajorityReplicasDownForAnyPartition"),
        isMajorityReplicasDownForAnyPartition);
  }

  /**
   * Initialize capacity related metrics.
   */
  void initializeCapacityMetrics() {
    Gauge<Long> rawTotalCapacityInBytes = clusterMapCallback::getRawCapacity;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "rawTotalCapacityBytes"), rawTotalCapacityInBytes);
    Gauge<Long> allocatedRawCapacityInBytes = clusterMapCallback::getAllocatedRawCapacity;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "allocatedRawCapacityBytes"),
        allocatedRawCapacityInBytes);

    Gauge<Long> allocatedUsableCapacityInBytes = clusterMapCallback::getAllocatedUsableCapacity;
    registry.register(MetricRegistry.name(HelixClusterManager.class, "allocatedUsableCapacityBytes"),
        allocatedUsableCapacityInBytes);
  }
}


text:
class FurnitureModuleProperty
    attr_accessor :name, :image
    include FurnitureHelpers
end


text:
'use strict';
var chalk = require( 'chalk' );
var table = require( 'text-table' );

/**
 * @param {Errors[]} errorsCollection
 */
module.exports = function( errorsCollection ) {
  var errorCount = 0;
  /**
   * Formatting every error set.
   */
  var report = errorsCollection.map( function( errors ) {
    if ( ! errors.isEmpty() ) {
      errorCount += errors.getErrorCount();

      var output = errors.getErrorList().map( function( error ) {
        return [
          '',
          chalk.gray( error.line ),
          chalk.gray( error.column ),
          process.platform !== 'win32' ? chalk.blue( error.message ) : chalk.cyan( error.message )
        ];
      } );

      return [
        '',
        chalk.underline( errors.getFilename() ),
        table( output ),
        ''
      ].join('\n');
    }
    return '';
  });

  if ( errorCount ) {
    // Output results
    console.log( report.join('') );
  } else {
    console.log( 'No code style errors found.' );
  }
};

// Expose path to reporter so it can be configured in e.g. grunt-jscs-checker
module.exports.path = __dirname;