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

import com.facebook.presto.common.predicate.Domain;
import com.facebook.presto.common.predicate.Range;
import com.facebook.presto.common.predicate.ValueSet;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.orc.metadata.statistics.BinaryStatistics;
import com.facebook.presto.orc.metadata.statistics.BooleanStatistics;
import com.facebook.presto.orc.metadata.statistics.ColumnStatistics;
import com.facebook.presto.orc.metadata.statistics.DateStatistics;
import com.facebook.presto.orc.metadata.statistics.DecimalStatistics;
import com.facebook.presto.orc.metadata.statistics.DoubleStatistics;
import com.facebook.presto.orc.metadata.statistics.IntegerStatistics;
import com.facebook.presto.orc.metadata.statistics.StringStatistics;
import io.airlift.slice.Slice;
import org.testng.annotations.Test;

import java.math.BigDecimal;

import static com.facebook.presto.common.predicate.Domain.create;
import static com.facebook.presto.common.predicate.Domain.notNull;
import static com.facebook.presto.common.predicate.Domain.onlyNull;
import static com.facebook.presto.common.predicate.Domain.singleValue;
import static com.facebook.presto.common.predicate.Range.greaterThanOrEqual;
import static com.facebook.presto.common.predicate.Range.lessThanOrEqual;
import static com.facebook.presto.common.predicate.Range.range;
import static com.facebook.presto.common.type.BigintType.BIGINT;
import static com.facebook.presto.common.type.BooleanType.BOOLEAN;
import static com.facebook.presto.common.type.CharType.createCharType;
import static com.facebook.presto.common.type.DateType.DATE;
import static com.facebook.presto.common.type.DecimalType.createDecimalType;
import static com.facebook.presto.common.type.Decimals.encodeScaledValue;
import static com.facebook.presto.common.type.DoubleType.DOUBLE;
import static com.facebook.presto.common.type.RealType.REAL;
import static com.facebook.presto.common.type.VarbinaryType.VARBINARY;
import static com.facebook.presto.common.type.VarcharType.VARCHAR;
import static com.facebook.presto.orc.TupleDomainOrcPredicate.getDomain;
import static com.facebook.presto.orc.metadata.statistics.ShortDecimalStatisticsBuilder.SHORT_DECIMAL_VALUE_BYTES;
import static io.airlift.slice.Slices.utf8Slice;
import static java.lang.Float.floatToRawIntBits;
import static org.testng.Assert.assertEquals;

public class TestTupleDomainOrcPredicate
{
    private static final Type SHORT_DECIMAL = createDecimalType(5, 2);
    private static final Type LONG_DECIMAL = createDecimalType(20, 10);
    private static final Type CHAR = createCharType(10);

    @Test
    public void testBoolean()
    {
        assertEquals(getDomain(BOOLEAN, 0, null), Domain.none(BOOLEAN));
        assertEquals(getDomain(BOOLEAN, 10, null), Domain.all(BOOLEAN));

        assertEquals(getDomain(BOOLEAN, 0, booleanColumnStats(null, null)), Domain.none(BOOLEAN));
        assertEquals(getDomain(BOOLEAN, 0, booleanColumnStats(0L, null)), Domain.none(BOOLEAN));
        assertEquals(getDomain(BOOLEAN, 0, booleanColumnStats(0L, 0L)), Domain.none(BOOLEAN));

        assertEquals(getDomain(BOOLEAN, 10, booleanColumnStats(0L, 0L)), onlyNull(BOOLEAN));
        assertEquals(getDomain(BOOLEAN, 10, booleanColumnStats(10L, null)), notNull(BOOLEAN));

        assertEquals(getDomain(BOOLEAN, 10, booleanColumnStats(10L, 10L)), singleValue(BOOLEAN, true));
        assertEquals(getDomain(BOOLEAN, 10, booleanColumnStats(10L, 0L)), singleValue(BOOLEAN, false));

        assertEquals(getDomain(BOOLEAN, 20, booleanColumnStats(10L, 5L)), Domain.all(BOOLEAN));

        assertEquals(getDomain(BOOLEAN, 20, booleanColumnStats(10L, 10L)), create(ValueSet.ofRanges(Range.equal(BOOLEAN, true)), true));
        assertEquals(getDomain(BOOLEAN, 20, booleanColumnStats(10L, 0L)), create(ValueSet.ofRanges(Range.equal(BOOLEAN, false)), true));
    }

    private static ColumnStatistics booleanColumnStats(Long numberOfValues, Long trueValueCount)
    {
        BooleanStatistics booleanStatistics = null;
        if (trueValueCount != null) {
            booleanStatistics = new BooleanStatistics(trueValueCount);
        }
        return new ColumnStatistics(numberOfValues, 2L, booleanStatistics, null, null, null, null, null, null, null);
    }

    @Test
    public void testBigint()
    {
        assertEquals(getDomain(BIGINT, 0, null), Domain.none(BIGINT));
        assertEquals(getDomain(BIGINT, 10, null), Domain.all(BIGINT));

        assertEquals(getDomain(BIGINT, 0, integerColumnStats(null, null, null)), Domain.none(BIGINT));
        assertEquals(getDomain(BIGINT, 0, integerColumnStats(0L, null, null)), Domain.none(BIGINT));
        assertEquals(getDomain(BIGINT, 0, integerColumnStats(0L, 100L, 100L)), Domain.none(BIGINT));

        assertEquals(getDomain(BIGINT, 10, integerColumnStats(0L, null, null)), onlyNull(BIGINT));
        assertEquals(getDomain(BIGINT, 10, integerColumnStats(10L, null, null)), notNull(BIGINT));

        assertEquals(getDomain(BIGINT, 10, integerColumnStats(10L, 100L, 100L)), singleValue(BIGINT, 100L));

        assertEquals(getDomain(BIGINT, 10, integerColumnStats(10L, 0L, 100L)), create(ValueSet.ofRanges(range(BIGINT, 0L, true, 100L, true)), false));
        assertEquals(getDomain(BIGINT, 10, integerColumnStats(10L, null, 100L)), create(ValueSet.ofRanges(lessThanOrEqual(BIGINT, 100L)), false));
        assertEquals(getDomain(BIGINT, 10, integerColumnStats(10L, 0L, null)), create(ValueSet.ofRanges(greaterThanOrEqual(BIGINT, 0L)), false));

        assertEquals(getDomain(BIGINT, 10, integerColumnStats(5L, 0L, 100L)), create(ValueSet.ofRanges(range(BIGINT, 0L, true, 100L, true)), true));
        assertEquals(getDomain(BIGINT, 10, integerColumnStats(5L, null, 100L)), create(ValueSet.ofRanges(lessThanOrEqual(BIGINT, 100L)), true));
        assertEquals(getDomain(BIGINT, 10, integerColumnStats(5L, 0L, null)), create(ValueSet.ofRanges(greaterThanOrEqual(BIGINT, 0L)), true));
    }

    private static ColumnStatistics integerColumnStats(Long numberOfValues, Long minimum, Long maximum)
    {
        return new ColumnStatistics(numberOfValues, 9L, null, new IntegerStatistics(minimum, maximum, null), null, null, null, null, null, null);
    }

    @Test
    public void testDouble()
    {
        assertEquals(getDomain(DOUBLE, 0, null), Domain.none(DOUBLE));
        assertEquals(getDomain(DOUBLE, 10, null), Domain.all(DOUBLE));

        assertEquals(getDomain(DOUBLE, 0, doubleColumnStats(null, null, null)), Domain.none(DOUBLE));
        assertEquals(getDomain(DOUBLE, 0, doubleColumnStats(0L, null, null)), Domain.none(DOUBLE));
        assertEquals(getDomain(DOUBLE, 0, doubleColumnStats(0L, 42.24, 42.24)), Domain.none(DOUBLE));

        assertEquals(getDomain(DOUBLE, 10, doubleColumnStats(0L, null, null)), onlyNull(DOUBLE));
        assertEquals(getDomain(DOUBLE, 10, doubleColumnStats(10L, null, null)), notNull(DOUBLE));

        assertEquals(getDomain(DOUBLE, 10, doubleColumnStats(10L, 42.24, 42.24)), singleValue(DOUBLE, 42.24));

        assertEquals(getDomain(DOUBLE, 10, doubleColumnStats(10L, 3.3, 42.24)), create(ValueSet.ofRanges(range(DOUBLE, 3.3, true, 42.24, true)), false));
        assertEquals(getDomain(DOUBLE, 10, doubleColumnStats(10L, null, 42.24)), create(ValueSet.ofRanges(lessThanOrEqual(DOUBLE, 42.24)), false));
        assertEquals(getDomain(DOUBLE, 10, doubleColumnStats(10L, 3.3, null)), create(ValueSet.ofRanges(greaterThanOrEqual(DOUBLE, 3.3)), false));

        assertEquals(getDomain(DOUBLE, 10, doubleColumnStats(5L, 3.3, 42.24)), create(ValueSet.ofRanges(range(DOUBLE, 3.3, true, 42.24, true)), true));
        assertEquals(getDomain(DOUBLE, 10, doubleColumnStats(5L, null, 42.24)), create(ValueSet.ofRanges(lessThanOrEqual(DOUBLE, 42.24)), true));
        assertEquals(getDomain(DOUBLE, 10, doubleColumnStats(5L, 3.3, null)), create(ValueSet.ofRanges(greaterThanOrEqual(DOUBLE, 3.3)), true));
    }

    private static ColumnStatistics doubleColumnStats(Long numberOfValues, Double minimum, Double maximum)
    {
        return new ColumnStatistics(numberOfValues, 9L, null, null, new DoubleStatistics(minimum, maximum), null, null, null, null, null);
    }

    @Test
    public void testFloat()
    {
        assertEquals(getDomain(REAL, 0, null), Domain.none(REAL));
        assertEquals(getDomain(REAL, 10, null), Domain.all(REAL));

        assertEquals(getDomain(REAL, 0, doubleColumnStats(null, null, null)), Domain.none(REAL));
        assertEquals(getDomain(REAL, 0, doubleColumnStats(0L, null, null)), Domain.none(REAL));
        assertEquals(getDomain(REAL, 0, doubleColumnStats(0L, (double) 42.24f, (double) 42.24f)), Domain.none(REAL));

        assertEquals(getDomain(REAL, 10, doubleColumnStats(0L, null, null)), onlyNull(REAL));
        assertEquals(getDomain(REAL, 10, doubleColumnStats(10L, null, null)), notNull(REAL));

        assertEquals(getDomain(REAL, 10, doubleColumnStats(10L, (double) 42.24f, (double) 42.24f)), singleValue(REAL, (long) floatToRawIntBits(42.24f)));

        assertEquals(getDomain(REAL, 10, doubleColumnStats(10L, 3.3, (double) 42.24f)), create(ValueSet.ofRanges(range(REAL, (long) floatToRawIntBits(3.3f), true, (long) floatToRawIntBits(42.24f), true)), false));
        assertEquals(getDomain(REAL, 10, doubleColumnStats(10L, null, (double) 42.24f)), create(ValueSet.ofRanges(lessThanOrEqual(REAL, (long) floatToRawIntBits(42.24f))), false));
        assertEquals(getDomain(REAL, 10, doubleColumnStats(10L, 3.3, null)), create(ValueSet.ofRanges(greaterThanOrEqual(REAL, (long) floatToRawIntBits(3.3f))), false));

        assertEquals(getDomain(REAL, 10, doubleColumnStats(5L, 3.3, (double) 42.24f)), create(ValueSet.ofRanges(range(REAL, (long) floatToRawIntBits(3.3f), true, (long) floatToRawIntBits(42.24f), true)), true));
        assertEquals(getDomain(REAL, 10, doubleColumnStats(5L, null, (double) 42.24f)), create(ValueSet.ofRanges(lessThanOrEqual(REAL, (long) floatToRawIntBits(42.24f))), true));
        assertEquals(getDomain(REAL, 10, doubleColumnStats(5L, 3.3, null)), create(ValueSet.ofRanges(greaterThanOrEqual(REAL, (long) floatToRawIntBits(3.3f))), true));
    }

    @Test
    public void testString()
    {
        assertEquals(getDomain(VARCHAR, 0, null), Domain.none(VARCHAR));
        assertEquals(getDomain(VARCHAR, 10, null), Domain.all(VARCHAR));

        assertEquals(getDomain(VARCHAR, 0, stringColumnStats(null, null, null)), Domain.none(VARCHAR));
        assertEquals(getDomain(VARCHAR, 0, stringColumnStats(0L, null, null)), Domain.none(VARCHAR));
        assertEquals(getDomain(VARCHAR, 0, stringColumnStats(0L, "taco", "taco")), Domain.none(VARCHAR));

        assertEquals(getDomain(VARCHAR, 10, stringColumnStats(0L, null, null)), onlyNull(VARCHAR));
        assertEquals(getDomain(VARCHAR, 10, stringColumnStats(10L, null, null)), notNull(VARCHAR));

        assertEquals(getDomain(VARCHAR, 10, stringColumnStats(10L, "taco", "taco")), singleValue(VARCHAR, utf8Slice("taco")));

        assertEquals(getDomain(VARCHAR, 10, stringColumnStats(10L, "apple", "taco")), create(ValueSet.ofRanges(range(VARCHAR, utf8Slice("apple"), true, utf8Slice("taco"), true)), false));
        assertEquals(getDomain(VARCHAR, 10, stringColumnStats(10L, null, "taco")), create(ValueSet.ofRanges(lessThanOrEqual(VARCHAR, utf8Slice("taco"))), false));
        assertEquals(getDomain(VARCHAR, 10, stringColumnStats(10L, "apple", null)), create(ValueSet.ofRanges(greaterThanOrEqual(VARCHAR, utf8Slice("apple"))), false));

        assertEquals(getDomain(VARCHAR, 10, stringColumnStats(5L, "apple", "taco")), create(ValueSet.ofRanges(range(VARCHAR, utf8Slice("apple"), true, utf8Slice("taco"), true)), true));
        assertEquals(getDomain(VARCHAR, 10, stringColumnStats(5L, null, "taco")), create(ValueSet.ofRanges(lessThanOrEqual(VARCHAR, utf8Slice("taco"))), true));
        assertEquals(getDomain(VARCHAR, 10, stringColumnStats(5L, "apple", null)), create(ValueSet.ofRanges(greaterThanOrEqual(VARCHAR, utf8Slice("apple"))), true));
    }

    @Test
    public void testChar()
    {
        assertEquals(getDomain(CHAR, 0, null), Domain.none(CHAR));
        assertEquals(getDomain(CHAR, 10, null), Domain.all(CHAR));

        assertEquals(getDomain(CHAR, 0, stringColumnStats(null, null, null)), Domain.none(CHAR));
        assertEquals(getDomain(CHAR, 0, stringColumnStats(0L, null, null)), Domain.none(CHAR));
        assertEquals(getDomain(CHAR, 0, stringColumnStats(0L, "taco      ", "taco      ")), Domain.none(CHAR));
        assertEquals(getDomain(CHAR, 0, stringColumnStats(0L, "taco", "taco      ")), Domain.none(CHAR));

        assertEquals(getDomain(CHAR, 10, stringColumnStats(0L, null, null)), onlyNull(CHAR));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(10L, null, null)), notNull(CHAR));

        assertEquals(getDomain(CHAR, 10, stringColumnStats(10L, "taco      ", "taco      ")), singleValue(CHAR, utf8Slice("taco")));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(10L, "taco", "taco      ")), singleValue(CHAR, utf8Slice("taco")));

        assertEquals(getDomain(CHAR, 10, stringColumnStats(10L, "apple     ", "taco      ")), create(ValueSet.ofRanges(range(CHAR, utf8Slice("apple"), true, utf8Slice("taco"), true)), false));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(10L, "apple     ", "taco")), create(ValueSet.ofRanges(range(CHAR, utf8Slice("apple"), true, utf8Slice("taco"), true)), false));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(10L, null, "taco      ")), create(ValueSet.ofRanges(lessThanOrEqual(CHAR, utf8Slice("taco"))), false));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(10L, null, "taco")), create(ValueSet.ofRanges(lessThanOrEqual(CHAR, utf8Slice("taco"))), false));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(10L, "apple     ", null)), create(ValueSet.ofRanges(greaterThanOrEqual(CHAR, utf8Slice("apple"))), false));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(10L, "apple", null)), create(ValueSet.ofRanges(greaterThanOrEqual(CHAR, utf8Slice("apple"))), false));

        assertEquals(getDomain(CHAR, 10, stringColumnStats(5L, "apple     ", "taco      ")), create(ValueSet.ofRanges(range(CHAR, utf8Slice("apple"), true, utf8Slice("taco"), true)), true));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(5L, "apple     ", "taco")), create(ValueSet.ofRanges(range(CHAR, utf8Slice("apple"), true, utf8Slice("taco"), true)), true));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(5L, null, "taco      ")), create(ValueSet.ofRanges(lessThanOrEqual(CHAR, utf8Slice("taco"))), true));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(5L, null, "taco")), create(ValueSet.ofRanges(lessThanOrEqual(CHAR, utf8Slice("taco"))), true));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(5L, "apple     ", null)), create(ValueSet.ofRanges(greaterThanOrEqual(CHAR, utf8Slice("apple"))), true));
        assertEquals(getDomain(CHAR, 10, stringColumnStats(5L, "apple", null)), create(ValueSet.ofRanges(greaterThanOrEqual(CHAR, utf8Slice("apple"))), true));

        assertEquals(getDomain(CHAR, 10, stringColumnStats(10L, "\0 ", " ")), create(ValueSet.ofRanges(range(CHAR, utf8Slice("\0"), true, utf8Slice(""), true)), false));
    }

    private static ColumnStatistics stringColumnStats(Long numberOfValues, String minimum, String maximum)
    {
        Slice minimumSlice = minimum == null ? null : utf8Slice(minimum);
        Slice maximumSlice = maximum == null ? null : utf8Slice(maximum);
        // sum and minAverageValueSizeInBytes are not used in this test; they could be arbitrary numbers
        return new ColumnStatistics(numberOfValues, 10L, null, null, null, new StringStatistics(minimumSlice, maximumSlice, 100L), null, null, null, null);
    }

    @Test
    public void testDate()
    {
        assertEquals(getDomain(DATE, 0, null), Domain.none(DATE));
        assertEquals(getDomain(DATE, 10, null), Domain.all(DATE));

        assertEquals(getDomain(DATE, 0, dateColumnStats(null, null, null)), Domain.none(DATE));
        assertEquals(getDomain(DATE, 0, dateColumnStats(0L, null, null)), Domain.none(DATE));
        assertEquals(getDomain(DATE, 0, dateColumnStats(0L, 100, 100)), Domain.none(DATE));

        assertEquals(getDomain(DATE, 10, dateColumnStats(0L, null, null)), onlyNull(DATE));
        assertEquals(getDomain(DATE, 10, dateColumnStats(10L, null, null)), notNull(DATE));

        assertEquals(getDomain(DATE, 10, dateColumnStats(10L, 100, 100)), singleValue(DATE, 100L));

        assertEquals(getDomain(DATE, 10, dateColumnStats(10L, 0, 100)), create(ValueSet.ofRanges(range(DATE, 0L, true, 100L, true)), false));
        assertEquals(getDomain(DATE, 10, dateColumnStats(10L, null, 100)), create(ValueSet.ofRanges(lessThanOrEqual(DATE, 100L)), false));
        assertEquals(getDomain(DATE, 10, dateColumnStats(10L, 0, null)), create(ValueSet.ofRanges(greaterThanOrEqual(DATE, 0L)), false));

        assertEquals(getDomain(DATE, 10, dateColumnStats(5L, 0, 100)), create(ValueSet.ofRanges(range(DATE, 0L, true, 100L, true)), true));
        assertEquals(getDomain(DATE, 10, dateColumnStats(5L, null, 100)), create(ValueSet.ofRanges(lessThanOrEqual(DATE, 100L)), true));
        assertEquals(getDomain(DATE, 10, dateColumnStats(5L, 0, null)), create(ValueSet.ofRanges(greaterThanOrEqual(DATE, 0L)), true));
    }

    private static ColumnStatistics dateColumnStats(Long numberOfValues, Integer minimum, Integer maximum)
    {
        return new ColumnStatistics(numberOfValues, 5L, null, null, null, null, new DateStatistics(minimum, maximum), null, null, null);
    }

    @Test
    public void testDecimal()
    {
        assertEquals(getDomain(SHORT_DECIMAL, 0, null), Domain.none(SHORT_DECIMAL));
        assertEquals(getDomain(LONG_DECIMAL, 10, null), Domain.all(LONG_DECIMAL));

        assertEquals(getDomain(SHORT_DECIMAL, 0, decimalColumnStats(null, null, null)), Domain.none(SHORT_DECIMAL));
        assertEquals(getDomain(LONG_DECIMAL, 0, decimalColumnStats(0L, null, null)), Domain.none(LONG_DECIMAL));
        assertEquals(getDomain(SHORT_DECIMAL, 0, decimalColumnStats(0L, "-999.99", "999.99")), Domain.none(SHORT_DECIMAL));

        assertEquals(getDomain(LONG_DECIMAL, 10, decimalColumnStats(0L, null, null)), onlyNull(LONG_DECIMAL));
        assertEquals(getDomain(SHORT_DECIMAL, 10, decimalColumnStats(10L, null, null)), notNull(SHORT_DECIMAL));

        assertEquals(getDomain(SHORT_DECIMAL, 10, decimalColumnStats(10L, "999.99", "999.99")), singleValue(SHORT_DECIMAL, shortDecimal("999.99")));
        assertEquals(getDomain(SHORT_DECIMAL, 10, decimalColumnStats(10L, "999.9", "999.9")), singleValue(SHORT_DECIMAL, shortDecimal("999.90")));
        assertEquals(getDomain(LONG_DECIMAL, 10, decimalColumnStats(10L, "1234567890.0987654321", "1234567890.0987654321")),
                singleValue(LONG_DECIMAL, longDecimal("1234567890.0987654321")));

        assertEquals(getDomain(SHORT_DECIMAL, 10, decimalColumnStats(10L, "-999.99", "999.99")),
                create(ValueSet.ofRanges(range(SHORT_DECIMAL, shortDecimal("-999.99"), true, shortDecimal("999.99"), true)), false));
        assertEquals(getDomain(SHORT_DECIMAL, 10, decimalColumnStats(10L, "10.5", "20")),
                create(ValueSet.ofRanges(range(SHORT_DECIMAL, shortDecimal("10.50"), true, shortDecimal("20.00"), true)), false));
        assertEquals(getDomain(SHORT_DECIMAL, 10, decimalColumnStats(10L, null, "999.99")),
                create(ValueSet.ofRanges(lessThanOrEqual(SHORT_DECIMAL, shortDecimal("999.99"))), false));
        assertEquals(getDomain(SHORT_DECIMAL, 10, decimalColumnStats(10L, "-999.99", null)),
                create(ValueSet.ofRanges(greaterThanOrEqual(SHORT_DECIMAL, shortDecimal("-999.99"))), false));

        assertEquals(getDomain(LONG_DECIMAL, 10, decimalColumnStats(10L, "-1234567890.0987654321", "1234567890.0987654321")),
                create(ValueSet.ofRanges(range(LONG_DECIMAL, longDecimal("-1234567890.0987654321"), true, longDecimal("1234567890.0987654321"), true)), false));
        assertEquals(getDomain(LONG_DECIMAL, 10, decimalColumnStats(10L, null, "1234567890.0987654321")),
                create(ValueSet.ofRanges(lessThanOrEqual(LONG_DECIMAL, longDecimal("1234567890.0987654321"))), false));
        assertEquals(getDomain(LONG_DECIMAL, 10, decimalColumnStats(10L, "-1234567890.0987654321", null)),
                create(ValueSet.ofRanges(greaterThanOrEqual(LONG_DECIMAL, longDecimal("-1234567890.0987654321"))), false));

        assertEquals(getDomain(SHORT_DECIMAL, 10, decimalColumnStats(5L, "-999.99", "999.99")),
                create(ValueSet.ofRanges(range(SHORT_DECIMAL, shortDecimal("-999.99"), true, shortDecimal("999.99"), true)), true));
        assertEquals(getDomain(SHORT_DECIMAL, 10, decimalColumnStats(5L, null, "999.99")),
                create(ValueSet.ofRanges(lessThanOrEqual(SHORT_DECIMAL, shortDecimal("999.99"))), true));
        assertEquals(getDomain(SHORT_DECIMAL, 10, decimalColumnStats(5L, "-999.99", null)),
                create(ValueSet.ofRanges(greaterThanOrEqual(SHORT_DECIMAL, shortDecimal("-999.99"))), true));

        assertEquals(getDomain(LONG_DECIMAL, 10, decimalColumnStats(5L, "-1234567890.0987654321", "1234567890.0987654321")),
                create(ValueSet.ofRanges(range(LONG_DECIMAL, longDecimal("-1234567890.0987654321"), true, longDecimal("1234567890.0987654321"), true)), true));
        assertEquals(getDomain(LONG_DECIMAL, 10, decimalColumnStats(5L, null, "1234567890.0987654321")),
                create(ValueSet.ofRanges(lessThanOrEqual(LONG_DECIMAL, longDecimal("1234567890.0987654321"))), true));
        assertEquals(getDomain(LONG_DECIMAL, 10, decimalColumnStats(5L, "-1234567890.0987654321", null)),
                create(ValueSet.ofRanges(greaterThanOrEqual(LONG_DECIMAL, longDecimal("-1234567890.0987654321"))), true));
    }

    private static ColumnStatistics decimalColumnStats(Long numberOfValues, String minimum, String maximum)
    {
        BigDecimal minimumDecimal = minimum == null ? null : new BigDecimal(minimum);
        BigDecimal maximumDecimal = maximum == null ? null : new BigDecimal(maximum);
        return new ColumnStatistics(numberOfValues, 9L, null, null, null, null, null, new DecimalStatistics(minimumDecimal, maximumDecimal, SHORT_DECIMAL_VALUE_BYTES), null, null);
    }

    @Test
    public void testBinary()
    {
        assertEquals(getDomain(VARBINARY, 0, null), Domain.none(VARBINARY));
        assertEquals(getDomain(VARBINARY, 10, null), Domain.all(VARBINARY));

        assertEquals(getDomain(VARBINARY, 0, binaryColumnStats(null)), Domain.none(VARBINARY));
        assertEquals(getDomain(VARBINARY, 0, binaryColumnStats(0L)), Domain.none(VARBINARY));
        assertEquals(getDomain(VARBINARY, 0, binaryColumnStats(0L)), Domain.none(VARBINARY));

        assertEquals(getDomain(VARBINARY, 10, binaryColumnStats(0L)), onlyNull(VARBINARY));
        assertEquals(getDomain(VARBINARY, 10, binaryColumnStats(10L)), notNull(VARBINARY));

        assertEquals(getDomain(VARBINARY, 20, binaryColumnStats(10L)), Domain.all(VARBINARY));
    }

    private static ColumnStatistics binaryColumnStats(Long numberOfValues)
    {
        // sum and minAverageValueSizeInBytes are not used in this test; they could be arbitrary numbers
        return new ColumnStatistics(numberOfValues, 10L, null, null, null, null, null, null, new BinaryStatistics(100L), null);
    }

    private static Long shortDecimal(String value)
    {
        return new BigDecimal(value).unscaledValue().longValue();
    }

    private static Slice longDecimal(String value)
    {
        return encodeScaledValue(new BigDecimal(value));
    }
}


text:
import com.sammyrulez.ocs.api._
import org.scalatra._
import javax.servlet.ServletContext

class ScalatraBootstrap extends LifeCycle {

    implicit val swagger = new OperationsSwagger

    override def init(context: ServletContext) {
        context.mount(new Operations, "/operations/*","operations")
        //context.mount(new SessionsController, "/sessions/*")
        context.mount (new ResourcesApp, "/api-docs")
    }
}

redpajama_set_name: RedPajamaGithub


text:
(function() {
    function SigninCtrl($scope) {

//        //Get Elements
//const txtEmail = document.getElementById('txtEmail');
//const txtPassword = document.getElementById('txtPassword');
//const btnLogin = document.getElementById('btnLogin');
//const btnSignUp = document.getElementById('btnSignUp');
//const btnLogout = document.getElementById('btnLogout');
//
//        //Add login event
//btnLogin.addEventListener('click', e => {
//        //Get email and pass
//const email = txtEmail.value;
//const pass = txtPassword.value;
//        //Sign in
//firebase.auth().signInWithEmailAndPassword(email, pass);
//
//var user = firebase.auth().currentUser;
//    if (user != null) {
//    window.location = "/dj-signup"
//    }
//        });
//
//
// //Sign out
//   btnLogout.addEventListener('click', e => {
//    firebase.auth().signOut().then(function() {
//        console.log('Signed Out');
//         window.location = "/signin"
//
//    }, function(error) {
//    console.error('Sign Out Error', error);
//    })
//})
//
//
//   //Validate User
//   function ValidateUser() {
//   var pword= new RegExp (/^[a-zA-Z0-9]{4,100}$/)
//   if (pword.test(password)) {
//      return true
//   }
//   else {
//      alert("Incorrect Password or Username")
//   }
//   var email= new RegExp (/^[A-Za-z0-9_.]{2,100}+@[A-Za-z0-9.-]{2,100}+\.[A-Za-z]{2,100}$/)
//   if (email.test(EmailAddress)) {
//      return true
//   }
//   else {
//      alert("Incorrect Password or Username")
//   }
//}
//
//
//
//    //Signup event
//    btnSignUp.addEventListener('click', e=> {
//        //Get email and pass
//    const email = txtEmail.value;
//    const pass = txtPassword.value;
//    const promise = firebase.auth().createUserWithEmailAndPassword(email, pass);
//
//    });
//
//   //Add a realtime listener
//    firebase.auth().onAuthStateChanged(firebaseUser => {
//    if(firebaseUser) {
//    console.log(firebaseUser);
//    } else {
//    console.log('not logged in');
//    }
//});
//}
//
//         //Initialize Firebase
//  var config = {
//    apiKey: "AIzaSyDV7tCzqsqAxlzt1HOauF9Bxe1_G1CdKyQ",
//    authDomain: "partybeats-cc743.firebaseapp.com",
//    databaseURL: "https://partybeats-cc743.firebaseio.com",
//    projectId: "partybeats-cc743",
//    storageBucket: "partybeats-cc743.appspot.com",
//    messagingSenderId: "976147237449"
//  };
//    firebase.initializeApp(config);

    }

angular
    .module('partybeats')
    .controller('SigninCtrl', [ SigninCtrl]);

})();


text:
<?php
  class DaActiveRecordModel extends CActiveRecord {
    protected function afterValidate() {
      if($this->isNewRecord){
        $this->created_at = DaDbWrapper::now();
      }
      $this->modified_at = DaDbWrapper::now();
      return parent::afterValidate();
    }
  }
?>


text:
static void activate(GtkApplication *app){
	GtkWidget *window;

	window = gtk_application_window_new(app);
	gtk_window_set_title(GTK_WINDOW(window), "Libreforge");
	gtk_window_set_default_size(GTK_WINDOW(window), 1024, 768);
	gtk_window_maximize(GTK_WINDOW(window));
	gtk_widget_show_all(window);
}

int app_init(int argc, char *argv[]){
	GtkApplication *app;
	int status;

	gtk_init(&argc, &argv);

	app = gtk_application_new(NULL, G_APPLICATION_FLAGS_NONE);
	g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);
	status = g_application_run (G_APPLICATION(app), argc, argv);
	g_object_unref(app);

	return status;
}


text:
package org.wso2.am.integration.tests.api.lifecycle;

import org.testng.annotations.*;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO;
import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException;
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
import org.wso2.am.integration.test.utils.bean.APILifeCycleAction;
import org.wso2.am.integration.test.utils.bean.APIRequest;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.test.utils.http.client.HttpRequestUtil;
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;

/**
 * "Block an API and check its accessibility in the API Store."
 */
public class AccessibilityOfBlockAPITestCase extends APIManagerLifecycleBaseTest {

    private final String API_NAME = "BlockAPITest";
    private final String API_CONTEXT = "BlockAPI";
    private final String API_END_POINT_METHOD = "/customers/123";
    private final String API_RESPONSE_DATA = "<id>123</id><name>John</name></Customer>";
    private final String API_VERSION_1_0_0 = "1.0.0";
    private final String APPLICATION_NAME = "AccessibilityOfBlockAPITestCase";
    private final String API_END_POINT_POSTFIX_URL = "jaxrs_basic/services/customers/customerservice/";
    private String apiEndPointUrl;
    private Map<String, String> requestHeaders;
    private String apiId;
    private String applicationId;

    @DataProvider
    public static Object[][] userModeDataProvider() {
        return new Object[][]{
                new Object[]{TestUserMode.SUPER_TENANT_ADMIN},
                new Object[]{TestUserMode.TENANT_ADMIN},
        };
    }

    @Factory(dataProvider = "userModeDataProvider")
    public AccessibilityOfBlockAPITestCase(TestUserMode userMode) {
        this.userMode = userMode;
    }

    @BeforeClass(alwaysRun = true)
    public void initialize() throws APIManagerIntegrationTestException {
        super.init(userMode);
        apiEndPointUrl = backEndServerUrl.getWebAppURLHttp() + API_END_POINT_POSTFIX_URL;

        HttpResponse applicationResponse = restAPIStore.createApplication(APPLICATION_NAME,
                "Test Application AccessibilityOfBlockAPITestCase", APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED,
                ApplicationDTO.TokenTypeEnum.JWT);
        applicationId = applicationResponse.getData();
    }

    @Test(groups = {"wso2.am"}, description = "Test invocation of the APi before block")
    public void testInvokeAPIBeforeChangeAPILifecycleToBlock() throws Exception {
        //Create and publish  and subscribe API version 1.0.0

        //Create the api creation request object
        APIRequest apiRequest;
        apiRequest = new APIRequest(API_NAME, API_CONTEXT, new URL(apiEndPointUrl));

        apiRequest.setVersion(API_VERSION_1_0_0);
        apiRequest.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED);
        apiRequest.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED);
        apiRequest.setProvider(user.getUserName());
        //Create, Publish and Subscribe
        apiId = createPublishAndSubscribeToAPIUsingRest(apiRequest, restAPIPublisher, restAPIStore, applicationId,
                APIMIntegrationConstants.API_TIER.UNLIMITED);

        ArrayList grantTypes = new ArrayList();
        grantTypes.add("client_credentials");

        //get access token
        ApplicationKeyDTO applicationKeyDTO = restAPIStore.generateKeys(applicationId, "3600", null,
                ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION, null, grantTypes);
        String accessToken = applicationKeyDTO.getToken().getAccessToken();
        // Create requestHeaders
        requestHeaders = new HashMap<String, String>();
        requestHeaders.put("accept", "text/xml");
        requestHeaders.put("Authorization", "Bearer " + accessToken);
        waitForAPIDeploymentSync(user.getUserName(), API_NAME, API_VERSION_1_0_0,
                APIMIntegrationConstants.IS_API_EXISTS);

        //Invoke  old version
        HttpResponse oldVersionInvokeResponse =
                HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT,
                        API_VERSION_1_0_0) + API_END_POINT_METHOD, requestHeaders);
        assertEquals(oldVersionInvokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_OK,
                "Response code mismatched when invoke api before block");
        assertTrue(oldVersionInvokeResponse.getData().contains(API_RESPONSE_DATA),
                "Response data mismatched when invoke  API  before block" +
                        " Response Data:" + oldVersionInvokeResponse.getData());
    }

    @Test(groups = {"wso2.am"}, description = "Change API lifecycle to block",
            dependsOnMethods = "testInvokeAPIBeforeChangeAPILifecycleToBlock")
    public void testChangeAPILifecycleToBlock() throws Exception {
        //Block the API version 1.0.0
        HttpResponse response = restAPIPublisher
                .changeAPILifeCycleStatus(apiId, APILifeCycleAction.BLOCK.getAction(), null);
        assertEquals(response.getResponseCode(), HTTP_RESPONSE_CODE_OK,
                "API publish Response code is invalid " + apiId);
    }

    @Test(groups = {"wso2.am"}, description = "Invocation og the APi after block",
            dependsOnMethods = "testChangeAPILifecycleToBlock")
    public void testInvokeAPIAfterChangeAPILifecycleToBlock() throws Exception {
        waitForAPIDeployment();

        //Invoke  old version
        HttpResponse oldVersionInvokeResponse =
                HttpRequestUtil.doGet(getAPIInvocationURLHttp(API_CONTEXT, API_VERSION_1_0_0) + API_END_POINT_METHOD,
                        requestHeaders);
        assertEquals(oldVersionInvokeResponse.getResponseCode(), HTTP_RESPONSE_CODE_SERVICE_UNAVAILABLE,
                "Response code mismatched when invoke api after block");
        assertTrue(oldVersionInvokeResponse.getData().contains(HTTP_RESPONSE_DATA_API_BLOCK),
                "Response data mismatched when invoke  API  after block" +
                        " Response Data:" + oldVersionInvokeResponse.getData());
    }

    @AfterClass(alwaysRun = true)
    public void cleanUpArtifacts() throws Exception {
        restAPIStore.deleteApplication(applicationId);
        restAPIPublisher.deleteAPI(apiId);
        super.cleanUp();
    }

}


text:
package net.chrisrichardson.ormunit.hibernate.tests;

public class Address {

    private int id;

    protected String street1;

    protected String street2;

    protected String city;

    protected String state;

    protected String zip;

    Address() {
    }

    public Address(String street1, String street2,
            String city, String state, String zip) {
        this.street1 = street1;
        this.street2 = street2;
        this.city = city;
        this.state = state;
        this.zip = zip;
    }

    public String getCity() {
        return city;
    }

    public String getState() {
        return state;
    }

    public String getStreet1() {
        return street1;
    }

    public String getStreet2() {
        return street2;
    }

    public String getZip() {
        return zip;
    }

}


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

#include <iostream>

#include <keyczar/session.h>

#include <keyczar/aes_key.h>
#include <keyczar/base/base64w.h>
#include <keyczar/base/json_reader.h>
#include <keyczar/base/json_writer.h>
#include <keyczar/base/values.h>
#include <keyczar/crypto_factory.h>
#include <keyczar/rand_impl.h>

namespace keyczar {

const int NONCE_SIZE = 16;

class Session {
 public:
  static Session* Parse(const std::string& json_string);
  static Session* Generate(int session_key_bits);

  const Value* GetValue() const;
  bool Encrypt(const std::string& plaintext, std::string* ciphertext) const;
  bool Decrypt(const std::string& ciphertext, std::string* plaintext) const;
  const std::string& Nonce() const { return nonce_; }

 private:
  Session(Key* session_key, const std::string& nonce)
      : session_key_(session_key), nonce_(nonce) {
  }

  scoped_refptr<Key> session_key_;
  std::string nonce_;
};

Session* Session::Generate(int session_key_bits) {
  scoped_ptr<AESKey> session_key(AESKey::GenerateKey(session_key_bits));
  std::string nonce;
  const RandImpl* rand = CryptoFactory::Rand();
  if (session_key.get()
      && rand != NULL
      && rand->RandBytes(NONCE_SIZE, &nonce))
    return new Session(session_key.release(), nonce);
  return NULL;
}

Session* Session::Parse(const std::string& json_string) {
  std::string error_out;
  scoped_ptr<const Value> session_json(
      base::JSONReader::Read(json_string, false /* allow_trailing_comma */));

  if (session_json.get() == NULL
      || !session_json->IsType(Value::TYPE_DICTIONARY))
    return NULL;

  const DictionaryValue* session_dict
      = static_cast<const DictionaryValue*>(session_json.get());

  std::string encoded_nonce;
  std::string nonce;
  Value* key_json;
  if (!session_dict->GetString("nonce", &encoded_nonce)
      || !base::Base64WDecode(encoded_nonce, &nonce)
      || !session_dict->Get("key", &key_json))
    return NULL;

  scoped_ptr<AESKey> session_key(AESKey::CreateFromValue(*key_json));
  if (session_key.get() == NULL)
    return NULL;

  return new Session(session_key.release(), nonce);
}

const Value* Session::GetValue() const {
  std::string encoded_nonce;
  scoped_ptr<DictionaryValue> dict(new DictionaryValue);
  if (dict.get()
      && dict->Set("key", session_key_->GetValue())
      && base::Base64WEncode(nonce_, &encoded_nonce)
      && dict->SetString("nonce", encoded_nonce))
    return dict.release();
  return NULL;
}

bool Session::Encrypt(const std::string& plaintext,
                      std::string* ciphertext) const {
  return session_key_.get() != NULL
      && session_key_->Encrypt(plaintext, ciphertext);
}

bool Session::Decrypt(const std::string& ciphertext,
                      std::string* plaintext) const {
  return session_key_.get() != NULL
      && session_key_->Decrypt(ciphertext, plaintext);
}

SignedSessionEncrypter::~SignedSessionEncrypter() {
  delete session_;
}

bool SignedSessionEncrypter::EncryptedSessionBlob(
    std::string* session_material) const {
  scoped_ptr<const Value> json_value(session_->GetValue());
  if (json_value.get() == NULL)
    return false;

  std::string json_string;
  base::JSONWriter::Write(json_value.get(), false, &json_string);

  return encrypter_->Encrypt(json_string, session_material);
}

std::string SignedSessionEncrypter::EncryptedSessionBlob() const {
  std::string blob;
  if (!EncryptedSessionBlob(&blob))
    return "";
  return blob;
}

bool SignedSessionEncrypter::SessionEncrypt(
    const std::string& plaintext,
    std::string* signed_ciphertext) const {
  std::string ciphertext;
  if (!session_->Encrypt(plaintext, &ciphertext))
    return false;
  return signer_->AttachedSign(ciphertext, session_->Nonce(),
                               signed_ciphertext);
}

std::string SignedSessionEncrypter::SessionEncrypt(
    const std::string& plaintext) const {
  std::string signed_ciphertext;
  if (!SessionEncrypt(plaintext, &signed_ciphertext))
    return "";
  return signed_ciphertext;
}

// static
SignedSessionEncrypter* SignedSessionEncrypter::NewSessionEncrypter(
    Encrypter* encrypter,
    Signer* signer,
    int session_key_bits) {
  scoped_ptr<Encrypter> encrypter_p(encrypter);
  scoped_ptr<Signer> signer_p(signer);

  scoped_ptr<Session> session(Session::Generate(session_key_bits));
  if (encrypter_p.get() != NULL
      && signer_p.get() != NULL
      && session.get() != NULL) {
    encrypter_p->set_encoding(Keyczar::BASE64W);
    return new SignedSessionEncrypter(encrypter_p.release(),
                                      signer_p.release(),
                                      session.release());
  }
  return NULL;
}

SignedSessionDecrypter::~SignedSessionDecrypter() {
  delete session_;
}

bool SignedSessionDecrypter::SessionDecrypt(const std::string& ciphertext,
                                            std::string* plaintext) const {
  const std::string& nonce = session_->Nonce();
  std::string encrypted_data;
  return verifier_->AttachedVerify(ciphertext, nonce, &encrypted_data)
      && session_->Decrypt(encrypted_data, plaintext);
}

std::string SignedSessionDecrypter::SessionDecrypt(
    const std::string& ciphertext) const {
  std::string plaintext;
  if (!SessionDecrypt(ciphertext, &plaintext))
    return "";
  return plaintext;
}

//static
SignedSessionDecrypter* SignedSessionDecrypter::NewSessionDecrypter(
    Crypter* crypter,
    Verifier* verifier,
    const std::string& session_material) {
  scoped_ptr<Crypter> crypter_p(crypter);
  scoped_ptr<Verifier> verifier_p(verifier);

  if (crypter == NULL || verifier == NULL)
    return NULL;

  std::string decrypted_session;
  crypter_p->set_encoding(Keyczar::BASE64W);
  if (!crypter_p->Decrypt(session_material, &decrypted_session))
    return NULL;

  scoped_ptr<Session> session(Session::Parse(decrypted_session));
  if (session.get() == NULL)
    return NULL;
  return new SignedSessionDecrypter(verifier_p.release(), session.release());
}

} // namespace keyczar


text:
package org.deepjava.comp.hosttest.testClasses.interfaceTest;

public interface I1 {
	int im1();
	void im2();
}


text:
#include "qopenglfunctions_3_3_core.h"
#include "qopenglcontext.h"

QT_BEGIN_NAMESPACE

/*!
    \class QOpenGLFunctions_3_3_Core
    \inmodule QtGui
    \since 5.1
    \wrapper
    \brief The QOpenGLFunctions_3_3_Core class provides all functions for OpenGL 3.3 core profile.

    This class is a wrapper for functions from OpenGL 3.3 core profile.
    See reference pages on \l {http://www.opengl.org/sdk/docs/}{opengl.org}
    for function documentation.

    \sa QAbstractOpenGLFunctions
*/

QOpenGLFunctions_3_3_Core::QOpenGLFunctions_3_3_Core()
 : QAbstractOpenGLFunctions()
 , d_1_0_Core(0)
 , d_1_1_Core(0)
 , d_1_2_Core(0)
 , d_1_3_Core(0)
 , d_1_4_Core(0)
 , d_1_5_Core(0)
 , d_2_0_Core(0)
 , d_2_1_Core(0)
 , d_3_0_Core(0)
 , d_3_1_Core(0)
 , d_3_2_Core(0)
 , d_3_3_Core(0)
{
}

QOpenGLFunctions_3_3_Core::~QOpenGLFunctions_3_3_Core()
{
    if (d_1_0_Core && !d_1_0_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_1_0_Core->context, QOpenGLFunctions_1_0_CoreBackend::versionStatus());
        delete d_1_0_Core;
    }
    if (d_1_1_Core && !d_1_1_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_1_1_Core->context, QOpenGLFunctions_1_1_CoreBackend::versionStatus());
        delete d_1_1_Core;
    }
    if (d_1_2_Core && !d_1_2_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_1_2_Core->context, QOpenGLFunctions_1_2_CoreBackend::versionStatus());
        delete d_1_2_Core;
    }
    if (d_1_3_Core && !d_1_3_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_1_3_Core->context, QOpenGLFunctions_1_3_CoreBackend::versionStatus());
        delete d_1_3_Core;
    }
    if (d_1_4_Core && !d_1_4_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_1_4_Core->context, QOpenGLFunctions_1_4_CoreBackend::versionStatus());
        delete d_1_4_Core;
    }
    if (d_1_5_Core && !d_1_5_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_1_5_Core->context, QOpenGLFunctions_1_5_CoreBackend::versionStatus());
        delete d_1_5_Core;
    }
    if (d_2_0_Core && !d_2_0_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_2_0_Core->context, QOpenGLFunctions_2_0_CoreBackend::versionStatus());
        delete d_2_0_Core;
    }
    if (d_2_1_Core && !d_2_1_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_2_1_Core->context, QOpenGLFunctions_2_1_CoreBackend::versionStatus());
        delete d_2_1_Core;
    }
    if (d_3_0_Core && !d_3_0_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_3_0_Core->context, QOpenGLFunctions_3_0_CoreBackend::versionStatus());
        delete d_3_0_Core;
    }
    if (d_3_1_Core && !d_3_1_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_3_1_Core->context, QOpenGLFunctions_3_1_CoreBackend::versionStatus());
        delete d_3_1_Core;
    }
    if (d_3_2_Core && !d_3_2_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_3_2_Core->context, QOpenGLFunctions_3_2_CoreBackend::versionStatus());
        delete d_3_2_Core;
    }
    if (d_3_3_Core && !d_3_3_Core->refs.deref()) {
        QAbstractOpenGLFunctionsPrivate::removeFunctionsBackend(d_3_3_Core->context, QOpenGLFunctions_3_3_CoreBackend::versionStatus());
        delete d_3_3_Core;
    }
}

bool QOpenGLFunctions_3_3_Core::initializeOpenGLFunctions()
{
    if ( isInitialized() )
        return true;

    QOpenGLContext* context = QOpenGLContext::currentContext();

    // If owned by a context object make sure it is current.
    // Also check that current context is capable of resolving all needed functions
    if (((owningContext() && owningContext() == context) || !owningContext())
        && QOpenGLFunctions_3_3_Core::isContextCompatible(context))
    {
        // Associate with private implementation, creating if necessary
        // Function pointers in the backends are resolved at creation time
        QOpenGLVersionFunctionsBackend* d = 0;
        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_1_0_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_1_0_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_1_0_CoreBackend::versionStatus(), d);
        }
        d_1_0_Core = static_cast<QOpenGLFunctions_1_0_CoreBackend*>(d);
        d->refs.ref();

        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_1_1_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_1_1_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_1_1_CoreBackend::versionStatus(), d);
        }
        d_1_1_Core = static_cast<QOpenGLFunctions_1_1_CoreBackend*>(d);
        d->refs.ref();

        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_1_2_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_1_2_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_1_2_CoreBackend::versionStatus(), d);
        }
        d_1_2_Core = static_cast<QOpenGLFunctions_1_2_CoreBackend*>(d);
        d->refs.ref();

        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_1_3_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_1_3_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_1_3_CoreBackend::versionStatus(), d);
        }
        d_1_3_Core = static_cast<QOpenGLFunctions_1_3_CoreBackend*>(d);
        d->refs.ref();

        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_1_4_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_1_4_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_1_4_CoreBackend::versionStatus(), d);
        }
        d_1_4_Core = static_cast<QOpenGLFunctions_1_4_CoreBackend*>(d);
        d->refs.ref();

        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_1_5_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_1_5_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_1_5_CoreBackend::versionStatus(), d);
        }
        d_1_5_Core = static_cast<QOpenGLFunctions_1_5_CoreBackend*>(d);
        d->refs.ref();

        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_2_0_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_2_0_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_2_0_CoreBackend::versionStatus(), d);
        }
        d_2_0_Core = static_cast<QOpenGLFunctions_2_0_CoreBackend*>(d);
        d->refs.ref();

        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_2_1_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_2_1_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_2_1_CoreBackend::versionStatus(), d);
        }
        d_2_1_Core = static_cast<QOpenGLFunctions_2_1_CoreBackend*>(d);
        d->refs.ref();

        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_3_0_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_3_0_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_3_0_CoreBackend::versionStatus(), d);
        }
        d_3_0_Core = static_cast<QOpenGLFunctions_3_0_CoreBackend*>(d);
        d->refs.ref();

        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_3_1_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_3_1_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_3_1_CoreBackend::versionStatus(), d);
        }
        d_3_1_Core = static_cast<QOpenGLFunctions_3_1_CoreBackend*>(d);
        d->refs.ref();

        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_3_2_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_3_2_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_3_2_CoreBackend::versionStatus(), d);
        }
        d_3_2_Core = static_cast<QOpenGLFunctions_3_2_CoreBackend*>(d);
        d->refs.ref();

        d = QAbstractOpenGLFunctionsPrivate::functionsBackend(context, QOpenGLFunctions_3_3_CoreBackend::versionStatus());
        if (!d) {
            d = new QOpenGLFunctions_3_3_CoreBackend(context);
            QAbstractOpenGLFunctionsPrivate::insertFunctionsBackend(context, QOpenGLFunctions_3_3_CoreBackend::versionStatus(), d);
        }
        d_3_3_Core = static_cast<QOpenGLFunctions_3_3_CoreBackend*>(d);
        d->refs.ref();

        QAbstractOpenGLFunctions::initializeOpenGLFunctions();
    }
    return isInitialized();
}

bool QOpenGLFunctions_3_3_Core::isContextCompatible(QOpenGLContext *context)
{
    Q_ASSERT(context);
    QSurfaceFormat f = context->format();
    const QPair<int, int> v = qMakePair(f.majorVersion(), f.minorVersion());
    if (v < qMakePair(3, 3))
        return false;

    return true;
}

QOpenGLVersionProfile QOpenGLFunctions_3_3_Core::versionProfile()
{
    QOpenGLVersionProfile v;
    v.setVersion(3, 3);
    v.setProfile(QSurfaceFormat::CoreProfile);
    return v;
}

QT_END_NAMESPACE


text:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DaxnetBlog.Web;
using Microsoft.AspNetCore.Routing;
using System.Text;

namespace DaxnetBlog.Web.TagHelpers
{
    [HtmlTargetElement("pager", TagStructure = TagStructure.WithoutEndTag)]
    public class PagerTagHelper : TagHelper
    {
        [HtmlAttributeNotBound]
        [ViewContext]
        public ViewContext ViewContext { get; set; }

        private IUrlHelperFactory UrlHelperFactory { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="PagerTagHelper"/> class.
        /// </summary>
        /// <param name="urlHelperFactory">The URL helper factory.</param>
        public PagerTagHelper(IUrlHelperFactory urlHelperFactory)
        {
            this.UrlHelperFactory = urlHelperFactory;
            this.VisibleNumbers = 5;
            this.ParameterName = "page";
        }

        /// <summary>
        /// Gets or sets the index of current page. This value should
        /// be larger than or equal to 1.
        /// </summary>
        /// <value>
        /// The current page.
        /// </value>
        [HtmlAttributeName("pager-current-page")]
        public int CurrentPage { get; set; }

        /// <summary>
        /// Gets or sets the number of total pages.
        /// </summary>
        /// <value>
        /// The total pages.
        /// </value>
        [HtmlAttributeName("pager-total-pages")]
        public int TotalPages { get; set; }

        /// <summary>
        /// Gets or sets the visible numbers.
        /// </summary>
        /// <value>
        /// The visible numbers.
        /// </value>
        [HtmlAttributeName("pager-visible-numbers")]
        public int VisibleNumbers { get; set; }

        /// <summary>
        /// Gets or sets the controller name
        /// </summary>
        /// <value>
        /// The controller.
        /// </value>
        [HtmlAttributeName("asp-controller")]
        public string Controller { get; set; }

        /// <summary>
        /// Gets or sets the action name
        /// </summary>
        /// <value>
        /// The action.
        /// </value>
        [HtmlAttributeName("asp-action")]
        public string Action { get; set; }

        /// <summary>
        /// Gets or sets the name of the parameter in the controller action.
        /// </summary>
        /// <value>
        /// The name of the parameter.
        /// </value>
        [HtmlAttributeName("pager-parameter-name")]
        public string ParameterName { get; set; }

        /// <summary>
        /// Gets or sets the name of the anchor tag within the HTML document, that when
        /// the link is clicked, just get the updated page and locate the document to the
        /// place where the anchor has been set.
        /// </summary>
        /// <value>
        /// The name of the anchor tag.
        /// </value>
        [HtmlAttributeName("pager-anchor-tag-name")]
        public string AnchorTagName { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (this.TotalPages <= 0)
            {
                return;
            }

            var routeValues = new RouteValueDictionary();

            var divBuilder = new TagBuilder("div");
            divBuilder.AddCssClass("text-center");
            //var pageNumberStringBuilder = new StringBuilder();
            var urlHelper = this.UrlHelperFactory.GetUrlHelper(this.ViewContext);

            var ulTag = new TagBuilder("ul");
            ulTag.AddCssClass("pagination");
            ulTag.AddCssClass("pagination-sm");
            TagBuilder liTag = null;

            TagBuilder firstPageTagBuilder;
            TagBuilder prevPageTagBuilder;
            if (this.CurrentPage > 1)
            {
                firstPageTagBuilder = new TagBuilder("a");
                firstPageTagBuilder.InnerHtml.Append("首页");
                firstPageTagBuilder.Attributes.Add("href",
                    string.IsNullOrEmpty(AnchorTagName)
                        ? urlHelper.Action(new UrlActionContext { Action = this.Action, Controller = this.Controller })
                        : string.Format("{0}#{1}", urlHelper.Action(new UrlActionContext { Action = this.Action, Controller = this.Controller }), AnchorTagName));
                liTag = new TagBuilder("li");
                liTag.InnerHtml.AppendHtml(firstPageTagBuilder.ToHtmlString());
                ulTag.InnerHtml.AppendHtml(liTag.ToHtmlString());

                prevPageTagBuilder = new TagBuilder("a");
                prevPageTagBuilder.InnerHtml.Append("上一页");
                routeValues[ParameterName] = CurrentPage - 1;
                prevPageTagBuilder.Attributes.Add("href",
                    string.IsNullOrEmpty(AnchorTagName)
                        ? urlHelper.Action(new UrlActionContext { Action = this.Action, Controller = this.Controller, Values = routeValues })
                        : string.Format("{0}#{1}", urlHelper.Action(new UrlActionContext { Action = this.Action, Controller = this.Controller, Values = routeValues }), AnchorTagName));
                liTag = new TagBuilder("li");
                liTag.InnerHtml.AppendHtml(prevPageTagBuilder.ToHtmlString());
                ulTag.InnerHtml.AppendHtml(liTag.ToHtmlString());

            }
            else
            {
                firstPageTagBuilder = new TagBuilder("a");
                firstPageTagBuilder.InnerHtml.Append("首页");
                liTag = new TagBuilder("li");
                liTag.AddCssClass("disabled");
                liTag.InnerHtml.AppendHtml(firstPageTagBuilder.ToHtmlString());
                ulTag.InnerHtml.AppendHtml(liTag.ToHtmlString());

                prevPageTagBuilder = new TagBuilder("a");
                prevPageTagBuilder.InnerHtml.Append("上一页");
                liTag = new TagBuilder("li");
                liTag.AddCssClass("disabled");
                liTag.InnerHtml.AppendHtml(prevPageTagBuilder.ToHtmlString());
                ulTag.InnerHtml.AppendHtml(liTag.ToHtmlString());
            }

            var pagerSegments = new List<PagerSegment>();
            if (TotalPages <= VisibleNumbers)
            {
                pagerSegments.Add(new PagerSegment { StartPageIndex = 1, EndPageIndex = TotalPages });
            }
            else
            {
                if (CurrentPage < VisibleNumbers)
                {
                    pagerSegments.Add(new PagerSegment(1, VisibleNumbers));
                    pagerSegments.Add(new PagerSegment(TotalPages, TotalPages));
                }
                else if (CurrentPage > TotalPages - VisibleNumbers)
                {
                    if (TotalPages - VisibleNumbers > 1)
                    {
                        pagerSegments.Add(new PagerSegment(1, 1));
                    }
                    pagerSegments.Add(new PagerSegment(TotalPages - VisibleNumbers, TotalPages));
                }
                else
                {
                    if (CurrentPage - VisibleNumbers / 2 > 1)
                    {
                        pagerSegments.Add(new PagerSegment(1, 1));
                    }
                    pagerSegments.Add(new PagerSegment(CurrentPage - VisibleNumbers / 2, CurrentPage + VisibleNumbers / 2));
                    pagerSegments.Add(new PagerSegment(TotalPages, TotalPages));
                }
            }

            for (var idx = 0; idx < pagerSegments.Count; idx++)
            {
                var pagerSegment = pagerSegments[idx];
                for (var i = pagerSegment.StartPageIndex; i <= pagerSegment.EndPageIndex; i++)
                {
                    //var spanTagBuilder = new TagBuilder("span");
                    liTag = new TagBuilder("li");
                    if (i == CurrentPage)
                    {
                        liTag.AddCssClass("active");
                    }
                    liTag.AddCssClass("pn");
                    var linkBuilder = new TagBuilder("a");

                    routeValues[ParameterName] = i;
                    linkBuilder.Attributes.Add("href",
                        string.IsNullOrEmpty(AnchorTagName)
                            ? urlHelper.Action(new UrlActionContext { Action = this.Action, Controller = this.Controller, Values = routeValues })
                            : string.Format("{0}#{1}", urlHelper.Action(new UrlActionContext { Action = this.Action, Controller = this.Controller, Values = routeValues }),
                                AnchorTagName));
                    linkBuilder.InnerHtml.Append(i.ToString());
                    liTag.InnerHtml.AppendHtml(linkBuilder.ToHtmlString());
                    ulTag.InnerHtml.AppendHtml(liTag.ToHtmlString());
                }
                if (idx != pagerSegments.Count - 1 &&
                    (pagerSegments[idx].EndPageIndex + 1 != pagerSegments[idx + 1].StartPageIndex))
                {
                    liTag = new TagBuilder("li");
                    liTag.AddCssClass("pn");
                    var aTag = new TagBuilder("a");
                    aTag.InnerHtml.Append("......");
                    liTag.AddCssClass("disabled");
                    liTag.InnerHtml.AppendHtml(aTag.ToHtmlString());
                    ulTag.InnerHtml.AppendHtml(liTag.ToHtmlString());
                }
            }

            TagBuilder nextPageTagBuilder;
            TagBuilder lastPageTagBuilder;
            if (CurrentPage < TotalPages)
            {
                nextPageTagBuilder = new TagBuilder("a");
                nextPageTagBuilder.InnerHtml.Append("下一页");
                routeValues[ParameterName] = CurrentPage + 1;
                nextPageTagBuilder.Attributes.Add("href",
                    string.IsNullOrEmpty(AnchorTagName)
                        ? urlHelper.Action(new UrlActionContext { Action = this.Action, Controller = this.Controller, Values = routeValues })
                        : string.Format("{0}#{1}", urlHelper.Action(new UrlActionContext { Action = this.Action, Controller = this.Controller, Values = routeValues }), AnchorTagName));

                liTag = new TagBuilder("li");
                liTag.InnerHtml.AppendHtml(nextPageTagBuilder.ToHtmlString());
                ulTag.InnerHtml.AppendHtml(liTag.ToHtmlString());

                lastPageTagBuilder = new TagBuilder("a");
                lastPageTagBuilder.InnerHtml.Append("末页");
                routeValues[ParameterName] = TotalPages;
                lastPageTagBuilder.Attributes.Add("href",
                    string.IsNullOrEmpty(AnchorTagName)
                        ? urlHelper.Action(new UrlActionContext { Action = this.Action, Controller = this.Controller, Values = routeValues })
                        : string.Format("{0}#{1}", urlHelper.Action(new UrlActionContext { Action = this.Action, Controller = this.Controller, Values = routeValues }), AnchorTagName));
                liTag = new TagBuilder("li");
                liTag.InnerHtml.AppendHtml(lastPageTagBuilder.ToHtmlString());
                ulTag.InnerHtml.AppendHtml(liTag.ToHtmlString());
            }
            else
            {
                nextPageTagBuilder = new TagBuilder("a");
                nextPageTagBuilder.InnerHtml.Append("下一页");
                liTag = new TagBuilder("li");
                liTag.AddCssClass("disabled");
                liTag.InnerHtml.AppendHtml(nextPageTagBuilder.ToHtmlString());
                ulTag.InnerHtml.AppendHtml(liTag.ToHtmlString());

                lastPageTagBuilder = new TagBuilder("a");
                lastPageTagBuilder.InnerHtml.Append("末页");
                liTag = new TagBuilder("li");
                liTag.AddCssClass("disabled");
                liTag.InnerHtml.AppendHtml(lastPageTagBuilder.ToHtmlString());
                ulTag.InnerHtml.AppendHtml(liTag.ToHtmlString());
            }

            divBuilder.InnerHtml.AppendHtml(ulTag.ToHtmlString());
            output.TagMode = TagMode.StartTagAndEndTag;
            output.Content.AppendHtml(divBuilder.ToHtmlString());
        }
    }
}


text:
package joshie.mariculture.core.events;

import joshie.mariculture.core.lib.Modules.Module;
import joshie.mariculture.plugins.Plugins.Plugin.Stage;
import cpw.mods.fml.common.eventhandler.Event;

public class RegistryEvent extends Event {
    public final Module module;
    public final Stage stage;

    public RegistryEvent(Module module, Stage stage) {
        this.module = module;
        this.stage = stage;
    }
}


text: {{rowIndex() + 1}} / {{tableLength()}}


text:
import UserListContainer from './UserCardContainer'
export default UserListContainer


text:
#pragma once

class Random
{
	static const unsigned long int N = 624;
	static const unsigned long int M = 397;
	static const unsigned long int MATRIX_A = 0x9908b0dfUL;   /* constant vector a */
	static const unsigned long int UPPER_MASK = 0x80000000UL; /* most significant w-r bits */
	static const unsigned long int LOWER_MASK = 0x7fffffffUL; /* least significant r bits */

	unsigned long mt[N]; /* the array for the state vector  */
	int mti; /* mti==N+1 means mt[N] is not initialized */
public:
	Random();
	void seed(unsigned long s);
	unsigned int rndu();
	int rnd(int min_val, int max_val);
	float rndf();
	long double rndl();
};


text:
import { Configuration } from 'webpack';
import * as merge from 'webpack-merge';
import { resolve } from 'path';

import { extractSass, shared } from './shared';

export const server: Configuration = merge(shared, {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['css-loader/locals']
            },
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/,
                loader: 'file-loader',
                options: { name: 'media/[name].[ext]', emit: false }
            },
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/,
                loader: 'file-loader',
                options: { name: 'media/[name].[ext]', emit: false }
            }
        ]
    }
});


text:
package com.kendelong.util.jmx.statistics;

import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.jmx.export.annotation.ManagedOperation;

public class StatisticsProviderMBeanBase implements IStatisticsProvider
{
	private IStatisticsProvider provider;

	@Override
	@ManagedAttribute(description="The average number of requests or accesses per second since this object was created")
	public double getAverageRequestsPerSecond()
	{
		return provider.getAverageRequestsPerSecond();
	}

	@Override
	@ManagedAttribute(description="The number of exceptions, or remote return codes indicating exceptions on the remote system")
	public long getNumberOfErrors()
	{
		return provider.getNumberOfErrors();
	}

	@Override
	@ManagedAttribute(description="The number of failed operations - non-exceptions but where the operation failed to have the desired effect")
	public long getNumberOfFailures()
	{
		return provider.getNumberOfFailures();
	}

	@Override
	@ManagedAttribute(description="The number of successful invocations")
	public long getNumberOfSuccesses()
	{
		return provider.getNumberOfSuccesses();
	}

	@Override
	@ManagedAttribute
	public long getTotalNumberOfAccesses()
	{
		return provider.getTotalNumberOfAccesses();
	}

	@Override
	@ManagedOperation(description="Reset statistics to zero")
	public void resetStatistics()
	{
		provider.resetStatistics();
	}

	@ManagedAttribute(description="The table of errors data")
	public String getErrorHistogramAsHtml()
	{
		Map<String, AtomicLong> errorMap = getErrorHistogram();
		String headingTitle = "validation error";
		return convertMapToTable(errorMap, headingTitle);
	}

	protected String convertMapToTable(Map<String, AtomicLong> errorMap, String headingTitle)
	{
		StringBuilder sb = new StringBuilder();
		sb.append("

" + headingTitle + "	count
");
		for (Map.Entry<String, AtomicLong> entry : errorMap.entrySet())
		{
			sb.append("
");
			sb.append(entry.getKey());
			sb.append("	");
			sb.append(entry.getValue());
			sb.append("
");
		}
		sb.append("
");
		return sb.toString();
	}

	public IStatisticsProvider getProvider()
	{
		return provider;
	}

	public void setProvider(IStatisticsProvider provider)
	{
		this.provider = provider;
	}

	@Override
	public Map<String, AtomicLong> getErrorHistogram()
	{
		return provider.getErrorHistogram();
	}
}


text: <?php if(!defined('LS_ROOT_FILE')) { header('HTTP/1.0 403 Forbidden'); exit; } ?>


text:
import { createStore, applyMiddleware, combineReducers } from 'redux';
import * as reducer from '../reducers/index';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
const middleware = [ thunk ];
if(process.env.NODE_ENV != 'production') {
    middleware.push(createLogger());
}
export default function configureStore() {
    return createStore(
        combineReducers(reducer),
        applyMiddleware(thunk)
    );
};


text:
class ConstrainedHtmlDelegateWin : public TabContentsContainer,
                                   public ConstrainedHtmlUIDelegate,
                                   public ConstrainedWindowDelegate,
                                   public HtmlDialogTabContentsDelegate {
 public:
  ConstrainedHtmlDelegateWin(Profile* profile,
                             HtmlDialogUIDelegate* delegate);
  ~ConstrainedHtmlDelegateWin();

  // ConstrainedHtmlUIDelegate interface.
  virtual HtmlDialogUIDelegate* GetHtmlDialogUIDelegate();
  virtual void OnDialogClose();

  // ConstrainedWindowDelegate (aka views::WindowDelegate) interface.
  virtual bool CanResize() const { return true; }
  virtual views::View* GetContentsView() {
    return this;
  }
  virtual void WindowClosing() {
    html_delegate_->OnDialogClosed("");
  }

  // HtmlDialogTabContentsDelegate interface.
  void MoveContents(TabContents* source, const gfx::Rect& pos) {}
  void HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {}

  // Overridden from TabContentsContainer.
  virtual gfx::Size GetPreferredSize() {
    gfx::Size size;
    html_delegate_->GetDialogSize(&size);
    return size;
  }

  virtual void ViewHierarchyChanged(bool is_add,
                                    views::View* parent,
                                    views::View* child) {
    TabContentsContainer::ViewHierarchyChanged(is_add, parent, child);
    if (is_add && child == this) {
      ChangeTabContents(&html_tab_contents_);
    }
  }

  void set_window(ConstrainedWindow* window) {
    window_ = window;
  }

 private:
  TabContents html_tab_contents_;

  HtmlDialogUIDelegate* html_delegate_;

  // The constrained window that owns |this|.  Saved so we can close it later.
  ConstrainedWindow* window_;
};

ConstrainedHtmlDelegateWin::ConstrainedHtmlDelegateWin(
    Profile* profile,
    HtmlDialogUIDelegate* delegate)
    : HtmlDialogTabContentsDelegate(profile),
      html_tab_contents_(profile, NULL, MSG_ROUTING_NONE, NULL, NULL),
      html_delegate_(delegate),
      window_(NULL) {
  CHECK(delegate);
  html_tab_contents_.set_delegate(this);

  // Set |this| as a property so the ConstrainedHtmlUI can retrieve it.
  ConstrainedHtmlUI::GetPropertyAccessor().SetProperty(
      html_tab_contents_.property_bag(), this);
  html_tab_contents_.controller().LoadURL(delegate->GetDialogContentURL(),
                                          GURL(),
                                          PageTransition::START_PAGE);
}

ConstrainedHtmlDelegateWin::~ConstrainedHtmlDelegateWin() {
}

HtmlDialogUIDelegate* ConstrainedHtmlDelegateWin::GetHtmlDialogUIDelegate() {
  return html_delegate_;
}

void ConstrainedHtmlDelegateWin::OnDialogClose() {
  window_->CloseConstrainedWindow();
}

// static
ConstrainedWindow* ConstrainedHtmlUI::CreateConstrainedHtmlDialog(
    Profile* profile,
    HtmlDialogUIDelegate* delegate,
    TabContents* container) {
  ConstrainedHtmlDelegateWin* constrained_delegate =
      new ConstrainedHtmlDelegateWin(profile, delegate);
  ConstrainedWindow* constrained_window =
      container->CreateConstrainedDialog(constrained_delegate);
  constrained_delegate->set_window(constrained_window);
  return constrained_window;
}


text: ./run-service.sh NLPServer


text:
// <copyright file="AssemblyInfo.cs" company="DATALINE GmbH & Co. KG">
// Copyright (c) DATALINE GmbH & Co. KG. All rights reserved.
// </copyright>

using System.Reflection;

[assembly: AssemblyTitle("DGUV-Mitgliedsnummernprüfung")]
[assembly: AssemblyProduct("Dguv.Validator")]


text:
<?php

namespace Igorw\FileServeBundle\Response;

use Symfony\Component\HttpFoundation\Request;

class PhpResponseFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     * @dataProvider provideRequestsAndContentDisposition
     */
    public function createShouldReturnResponseWithRequestSpecificContentDisposition($disposition, $request)
    {
        $factory = new PhpResponseFactory(__DIR__.'/../Fixtures', $request);

        $options = array(
            'serve_filename'    => 'internet.zip',
            'inline'            => false,
        );
        $response = $factory->create('internet.txt', 'application/zip', $options);

        $this->assertSame($disposition, $response->headers->get('Content-Disposition'));
    }

    /** @test */
    public function createWithRelativePath()
    {
        $factory = new PhpResponseFactory(__DIR__.'/../Fixtures', new Request());

        $response = $factory->create('internet.txt', 'text/plain');

        ob_start();
        $response->send();
        $output = ob_get_clean();

        $this->assertSame("the internets\n", $output);
    }

    /** @test */
    public function createWithAbsolutePath()
    {
        $factory = new PhpResponseFactory(__DIR__.'/../Fixtures', new Request());

        $response = $factory->create(__DIR__.'/../Fixtures/internet.txt', 'text/plain', array(
            'absolute_path' => true,
        ));

        ob_start();
        $response->send();
        $output = ob_get_clean();

        $this->assertSame("the internets\n", $output);
    }

    /**
     * @test
     * @expectedException InvalidArgumentException
     */
    public function createWithNonExistentPathShouldThrowException()
    {
        $factory = new PhpResponseFactory(__DIR__.'/../Fixtures', new Request());

        $response = $factory->create(__DIR__.'/../Fixtures/missing.txt', 'text/plain');
    }

    public function provideRequestsAndContentDisposition()
    {
        return array(
            array('attachment; filename=internet.zip', $this->createRequestWithUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Ubuntu/12.04 Chromium/20.0.1132.47 Chrome/20.0.1132.47 Safari/536.11')),
            array('attachment; filename*=UTF-8\'\'internet.zip', $this->createRequestWithUserAgent('Yeti/1.0 (NHN Corp.; http://help.naver.com/robots/)')),
        );
    }

    private function createRequestWithUserAgent($userAgent)
    {
        $request = Request::create('/');
        $request->headers->set('User-Agent', $userAgent);
        return $request;
    }
}


text:
package java.awt.dnd;

import java.util.EventListener;

/**
 * A listener interface for receiving mouse motion events during a drag
 * operation.
 *

 * The class that is interested in processing mouse motion events during
 * a drag operation either implements this interface or extends the abstract
 * {@code DragSourceAdapter} class (overriding only the methods of
 * interest).
 *

 * Create a listener object using that class and then register it with
 * a {@code DragSource}. Whenever the mouse moves during a drag
 * operation initiated with this {@code DragSource}, that object's
 * {@code dragMouseMoved} method is invoked, and the
 * {@code DragSourceDragEvent} is passed to it.
 *
 * @see DragSourceDragEvent
 * @see DragSource
 * @see DragSourceListener
 * @see DragSourceAdapter
 *
 * @since 1.4
 */

public interface DragSourceMotionListener extends EventListener {

    /**
     * Called whenever the mouse is moved during a drag operation.
     *
     * @param dsde the {@code DragSourceDragEvent}
     */
    void dragMouseMoved(DragSourceDragEvent dsde);
}


text:
extern crate lazy_static;
#[macro_use]
extern crate downcast_rs;

mod utils;
mod lib_interfaces;
pub mod ctx;
pub mod frame;
pub mod canvas;

#[no_mangle]
pub extern "C" fn callback(callback_ptr: *mut lib_interfaces::Callback, ret_code: i32) {
    let mut callback: Box<lib_interfaces::Callback> = unsafe { Box::from_raw(callback_ptr) };
    callback.callback(ret_code);
}

#[no_mangle]
pub extern "C" fn animation_frame(timestamp: f64) {
    frame::generate(timestamp);
}

pub fn init() {
    lib!(init_lib());
    test();
}

pub fn main_loop() {
    lib!(emscripten_exit_with_live_runtime());
}

// test
struct CustomCb (i32);
lib_define_callback!(CustomCb {
    fn callback(&mut self, time: i32) {
        println!("{} Date.now: {}", self.0, time);
    }
});
fn test() {
    lib!(timeout(1000, lib_callback!(CustomCb(666))));
}


text:
using Chloe.Infrastructure;
using Chloe.RDBMS;
using System.Data;

namespace Chloe.PostgreSQL
{
    public class PostgreSQLContext : DbContext
    {
        public PostgreSQLContext(IDbConnectionFactory dbConnectionFactory) : base(new DbContextProviderFactory(dbConnectionFactory))
        {

        }
        public PostgreSQLContext(Func<IDbConnection> dbConnectionFactory) : this(new DbConnectionFactory(dbConnectionFactory))
        {
        }

        /// <summary>
        /// 设置方法解析器。
        /// </summary>
        /// <param name="methodName"></param>
        /// <param name="handler"></param>
        public static void SetMethodHandler(string methodName, IMethodHandler handler)
        {
            PostgreSQLContextProvider.SetMethodHandler(methodName, handler);
        }

        /// <summary>
        /// 是否将 sql 中的表名/字段名转成小写。默认为 true。
        /// </summary>
        public bool ConvertToLowercase
        {
            get
            {
                return (this.DefaultDbContextProvider as PostgreSQLContextProvider).ConvertToLowercase;
            }
            set
            {
                (this.DefaultDbContextProvider as PostgreSQLContextProvider).ConvertToLowercase = value;
            }
        }
    }

    class DbContextProviderFactory : IDbContextProviderFactory
    {
        IDbConnectionFactory _dbConnectionFactory;

        public DbContextProviderFactory(IDbConnectionFactory dbConnectionFactory)
        {
            PublicHelper.CheckNull(dbConnectionFactory);
            this._dbConnectionFactory = dbConnectionFactory;
        }

        public IDbContextProvider CreateDbContextProvider()
        {
            return new PostgreSQLContextProvider(this._dbConnectionFactory);
        }
    }
}


text:
|  Branch | Build Status |
| :------------ |:-------------
| master      | [![Build Status](https://wso2.org/jenkins/job/carbon-deployment/badge/icon)](https://wso2.org/jenkins/job/carbon-deployment) |
| release-4.2.x | [![Build Status](https://wso2.org/jenkins/job/carbon-deployment_release-4.2.x/badge/icon)](https://wso2.org/jenkins/job/carbon-deployment_release-4.2.x/) |

---

Latest Released Version v4.5.3.

#### carbon-deployment repo contains the the following deployment components.

* javaee
* monitoring
* service-mgt
* webapp-mgt

Carbon deployment repository contains application hosting and service hosting features and related features for the wso2 platform.

## How to Contribute
* Please report issues at [Carbon JIRA] (https://wso2.org/jira/browse/CARBON).
* Send your bug fixes pull requests to [master branch] (https://github.com/wso2/carbon-deployment/tree/master)

## Contact us
WSO2 Carbon developers can be contacted via the mailing lists:

* Carbon Developers List : dev@wso2.org
* Carbon Architecture List : architecture@wso2.org


text:
// Copyright 2010-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package org.mozc.android.inputmethod.japanese.preference;

import org.mozc.android.inputmethod.japanese.MozcLog;
import org.mozc.android.inputmethod.japanese.keyboard.Keyboard.KeyboardSpecification;
import org.mozc.android.inputmethod.japanese.preference.ClientSidePreference.KeyboardLayout;
import org.mozc.android.inputmethod.japanese.resources.R;
import org.mozc.android.inputmethod.japanese.view.Skin;
import org.mozc.android.inputmethod.japanese.view.SkinType;
import com.google.common.base.Preconditions;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;

/**
 * Preference class for KeyboardLayout.
 *
 */
public class KeyboardLayoutPreference extends Preference {

  static class Item {
    final KeyboardLayout keyboardLayout;
    final KeyboardSpecification specification;
    final int titleResId;
    final int descriptionResId;
    Item(KeyboardLayout keyboardLayout, KeyboardSpecification specification,
         int titleResId, int descriptionResId) {
      this.keyboardLayout = keyboardLayout;
      this.specification = specification;
      this.titleResId = titleResId;
      this.descriptionResId = descriptionResId;
    }
  }

  class ImageAdapter extends BaseAdapter {
    private final EnumMap<KeyboardLayout, KeyboardPreviewDrawable> drawableMap =
        new EnumMap<KeyboardLayout, KeyboardPreviewDrawable>(KeyboardLayout.class);

    ImageAdapter(Resources resources) {
      for (Item item : itemList) {
        drawableMap.put(
            item.keyboardLayout,
            new KeyboardPreviewDrawable(resources, item.keyboardLayout, item.specification));
      }
    }

    @Override
    public int getCount() {
      return itemList.size();
    }

    @Override
    public Object getItem(int item) {
      return itemList.get(item);
    }

    @Override
    public long getItemId(int item) {
      return item;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parentView) {
      if (convertView == null) {
        // No cached view is available. Inflate it.
        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.pref_keyboard_layout_item, parentView, false);
      }

      boolean isEnabled = KeyboardLayoutPreference.this.isEnabled();

      // Needs to set the properties to the view even if a cached view is available,
      // because the cached view might use to be used for another item.
      Item item = itemList.get(position);
      ImageView imageView =
          ImageView.class.cast(convertView.findViewById(R.id.pref_inputstyle_item_image));
      imageView.setImageDrawable(drawableMap.get(item.keyboardLayout));
      imageView.setEnabled(isEnabled);

      TextView titleView =
          TextView.class.cast(convertView.findViewById(R.id.pref_inputstyle_item_title));
      titleView.setText(item.titleResId);
      titleView.setTextColor(getContext().getResources().getColor(isEnabled
          ? R.color.pref_inputstyle_title
          : R.color.pref_inputstyle_title_disabled));
      titleView.setEnabled(parentView.isEnabled());

      updateBackground(convertView, position, getActiveIndex());
      return convertView;
    }

    void setSkin(Skin skin) {
      Preconditions.checkNotNull(skin);
      for (KeyboardPreviewDrawable drawable : drawableMap.values()) {
        drawable.setSkin(skin);
      }
    }
  }

  private class GalleryEventListener implements OnItemSelectedListener, OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // Update the value if necessary.
      KeyboardLayout newValue = itemList.get(position).keyboardLayout;
      if (callChangeListener(newValue)) {
        setValue(newValue);
        updateAllItemBackground(parent, getActiveIndex());
      }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
      // Update the description.
      TextView descriptionView = TextView.class.cast(
          View.class.cast(parent.getParent()).findViewById(R.id.pref_inputstyle_description));
      if (descriptionView != null) {
        Item item = Item.class.cast(parent.getItemAtPosition(position));
        descriptionView.setText(Html.fromHtml(
            descriptionView.getContext().getResources().getString(item.descriptionResId)));
      }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
      // Do nothing.
    }
  }

  static final List<Item> itemList = Collections.unmodifiableList(Arrays.asList(
      new Item(
          KeyboardLayout.TWELVE_KEYS,
          KeyboardSpecification.TWELVE_KEY_TOGGLE_FLICK_KANA,
          R.string.pref_keyboard_layout_title_12keys,
          R.string.pref_keyboard_layout_description_12keys),
      new Item(
          KeyboardLayout.QWERTY,
          KeyboardSpecification.QWERTY_KANA,
          R.string.pref_keyboard_layout_title_qwerty,
          R.string.pref_keyboard_layout_description_qwerty),
      new Item(
          KeyboardLayout.QWERTY123,
          KeyboardSpecification.QWERTY123_KANA,
          R.string.pref_keyboard_layout_title_qwerty123,
          R.string.pref_keyboard_layout_description_qwerty123),
      new Item(
          KeyboardLayout.GODAN,
          KeyboardSpecification.GODAN_KANA,
          R.string.pref_keyboard_layout_title_godan,
          R.string.pref_keyboard_layout_description_godan)));

  private final ImageAdapter imageAdapter = new ImageAdapter(getContext().getResources());
  private final GalleryEventListener galleryEventListener = new GalleryEventListener();
  private final OnSharedPreferenceChangeListener sharedPreferenceChangeListener =
      new OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
          if (key.equals(getContext().getResources().getString(R.string.pref_skin_type_key))) {
            updateSkin();
          }
        }
      };

  private KeyboardLayout value = KeyboardLayout.TWELVE_KEYS;

  public KeyboardLayoutPreference(Context context) {
    super(context);
  }

  public KeyboardLayoutPreference(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public KeyboardLayoutPreference(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  public void setValue(KeyboardLayout value) {
    if (value == null) {
      throw new NullPointerException("value must not be null.");
    }

    if (this.value != value) {
      this.value = value;
      persistString(value.name());
      notifyChanged();
    }
  }

  public KeyboardLayout getValue() {
    return value;
  }

  private int getActiveIndex() {
    for (int i = 0; i < itemList.size(); ++i) {
      if (itemList.get(i).keyboardLayout == value) {
        return i;
      }
    }

    MozcLog.e("Current value is not found in the itemList: " + value);
    return 0;
  }

  @Override
  protected Object onGetDefaultValue(TypedArray a, int index) {
    return toKeyboardLayoutInternal(a.getString(index));
  }

  @Override
  protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
    setValue(restoreValue
        ? toKeyboardLayoutInternal(getPersistedString(null))
        : KeyboardLayout.class.cast(defaultValue));
  }

  /**
   * Parses the name and returns the {@link KeyboardLayout} instance.
   * If invalid name or {@code null} is given, the default value {@code TWELVE_KEYS} will
   * be returned.
   */
  private KeyboardLayout toKeyboardLayoutInternal(String keyboardLayoutName) {
    if (keyboardLayoutName != null) {
      try {
        return KeyboardLayout.valueOf(keyboardLayoutName);
      } catch (IllegalArgumentException e) {
        MozcLog.e("Invalid keyboard layout name: " + keyboardLayoutName, e);
      }
    }

    // Fallback. Use TWELVE_KEYS by default.
    return KeyboardLayout.TWELVE_KEYS;
  }

  @Override
  protected void onBindView(View view) {
    super.onBindView(view);

    TextView descriptionView =
        TextView.class.cast(view.findViewById(R.id.pref_inputstyle_description));
    descriptionView.setMovementMethod(LinkMovementMethod.getInstance());

    @SuppressWarnings("deprecation")
    android.widget.Gallery gallery =
        android.widget.Gallery.class.cast(view.findViewById(R.id.pref_inputstyle_gallery));
    gallery.setAdapter(imageAdapter);
    gallery.setOnItemSelectedListener(galleryEventListener);
    gallery.setOnItemClickListener(galleryEventListener);
    gallery.setSelection(getActiveIndex());

    updateSkin();
  }

  private static void updateAllItemBackground(AdapterView<?> gallery, int activeIndex) {
    for (int i = 0; i < gallery.getChildCount(); ++i) {
      View child = gallery.getChildAt(i);
      int position = gallery.getPositionForView(child);
      updateBackground(child, position, activeIndex);
    }
  }

  @SuppressWarnings("deprecation")
  private static void updateBackground(View view, int position, int activePosition) {
    if (position == activePosition) {
      view.setBackgroundResource(android.R.drawable.dialog_frame);
    } else {
      view.setBackgroundDrawable(null);
    }
  }

  @Override
  protected void onAttachedToHierarchy(PreferenceManager preferenceManager) {
    super.onAttachedToHierarchy(preferenceManager);
    updateSkin();
    getSharedPreferences().registerOnSharedPreferenceChangeListener(
        sharedPreferenceChangeListener);
  }

  @Override
  protected void onPrepareForRemoval() {
    getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
        sharedPreferenceChangeListener);
    super.onPrepareForRemoval();
  }

  void updateSkin() {
    Resources resources = getContext().getResources();
    SkinType skinType = PreferenceUtil.getEnum(
        getSharedPreferences(),
        resources.getString(R.string.pref_skin_type_key),
        SkinType.class, SkinType.valueOf(resources.getString(R.string.pref_skin_type_default)));
    imageAdapter.setSkin(skinType.getSkin(resources));
  }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _promise;

function _load_promise() {
  return _promise = _interopRequireDefault(require('babel-runtime/core-js/promise'));
}

var _asyncToGenerator2;

function _load_asyncToGenerator() {
  return _asyncToGenerator2 = _interopRequireDefault(require('babel-runtime/helpers/asyncToGenerator'));
}

var _errors;

function _load_errors() {
  return _errors = require('../errors.js');
}

var _baseFetcher;

function _load_baseFetcher() {
  return _baseFetcher = _interopRequireDefault(require('./base-fetcher.js'));
}

var _git;

function _load_git() {
  return _git = _interopRequireDefault(require('../util/git.js'));
}

var _fs;

function _load_fs() {
  return _fs = _interopRequireWildcard(require('../util/fs.js'));
}

var _constants;

function _load_constants() {
  return _constants = _interopRequireWildcard(require('../constants.js'));
}

var _crypto;

function _load_crypto() {
  return _crypto = _interopRequireWildcard(require('../util/crypto.js'));
}

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const tarFs = require('tar-fs');
const url = require('url');
const path = require('path');
const fs = require('fs');

const invariant = require('invariant');

class GitFetcher extends (_baseFetcher || _load_baseFetcher()).default {
  getLocalAvailabilityStatus() {
    var _this = this;

    return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
      // Some mirrors might still have files named "./reponame" instead of "./reponame-commit"
      const tarballLegacyMirrorPath = _this.getTarballMirrorPath({ withCommit: false });
      const tarballModernMirrorPath = _this.getTarballMirrorPath();
      const tarballCachePath = _this.getTarballCachePath();

      if (tarballLegacyMirrorPath != null && (yield (_fs || _load_fs()).exists(tarballLegacyMirrorPath))) {
        return true;
      }

      if (tarballModernMirrorPath != null && (yield (_fs || _load_fs()).exists(tarballModernMirrorPath))) {
        return true;
      }

      if (yield (_fs || _load_fs()).exists(tarballCachePath)) {
        return true;
      }

      return false;
    })();
  }

  getTarballMirrorPath() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        _ref$withCommit = _ref.withCommit;

    let withCommit = _ref$withCommit === undefined ? true : _ref$withCommit;

    var _url$parse = url.parse(this.reference);

    const pathname = _url$parse.pathname;

    if (pathname == null) {
      return null;
    }

    const hash = this.hash;

    const packageFilename = withCommit && hash ? `${path.basename(pathname)}-${hash}` : `${path.basename(pathname)}`;

    return this.config.getOfflineMirrorPath(packageFilename);
  }

  getTarballCachePath() {
    return path.join(this.dest, (_constants || _load_constants()).TARBALL_FILENAME);
  }

  fetchFromLocal(override) {
    var _this2 = this;

    return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
      const tarballLegacyMirrorPath = _this2.getTarballMirrorPath({ withCommit: false });
      const tarballModernMirrorPath = _this2.getTarballMirrorPath();
      const tarballCachePath = _this2.getTarballCachePath();

      const tarballMirrorPath = tarballModernMirrorPath && !(yield (_fs || _load_fs()).exists(tarballModernMirrorPath)) && tarballLegacyMirrorPath && (yield (_fs || _load_fs()).exists(tarballLegacyMirrorPath)) ? tarballLegacyMirrorPath : tarballModernMirrorPath;

      const tarballPath = override || tarballMirrorPath || tarballCachePath;

      if (!tarballPath || !(yield (_fs || _load_fs()).exists(tarballPath))) {
        throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('tarballNotInNetworkOrCache', _this2.reference, tarballPath));
      }

      return new (_promise || _load_promise()).default(function (resolve, reject) {
        const untarStream = tarFs.extract(_this2.dest, {
          dmode: 0o555, // all dirs should be readable
          fmode: 0o444, // all files should be readable
          chown: false });

        const hashStream = new (_crypto || _load_crypto()).HashStream();

        const cachedStream = fs.createReadStream(tarballPath);
        cachedStream.pipe(hashStream).pipe(untarStream).on('finish', function () {
          const expectHash = _this2.hash;
          const actualHash = hashStream.getHash();
          if (!expectHash || expectHash === actualHash) {
            resolve({
              hash: actualHash
            });
          } else {
            reject(new (_errors || _load_errors()).SecurityError(_this2.reporter.lang('fetchBadHash', expectHash, actualHash)));
          }
        }).on('error', function (err) {
          reject(new (_errors || _load_errors()).MessageError(this.reporter.lang('fetchErrorCorrupt', err.message, tarballPath)));
        });
      });
    })();
  }

  fetchFromExternal() {
    var _this3 = this;

    return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
      const hash = _this3.hash;
      invariant(hash, 'Commit hash required');

      const gitUrl = (_git || _load_git()).default.npmUrlToGitUrl(_this3.reference);
      const git = new (_git || _load_git()).default(_this3.config, gitUrl, hash);
      yield git.init();
      yield git.clone(_this3.dest);

      const tarballMirrorPath = _this3.getTarballMirrorPath();
      const tarballCachePath = _this3.getTarballCachePath();

      if (tarballMirrorPath) {
        yield git.archive(tarballMirrorPath);
      }

      if (tarballCachePath) {
        yield git.archive(tarballCachePath);
      }

      return {
        hash: hash
      };
    })();
  }

  _fetch() {
    var _this4 = this;

    return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () {
      if (yield _this4.getLocalAvailabilityStatus()) {
        return _this4.fetchFromLocal();
      } else {
        return _this4.fetchFromExternal();
      }
    })();
  }
}
exports.default = GitFetcher;