text:
package org.apache.pig.spark;

import static org.apache.pig.builtin.mock.Storage.bag;
import static org.apache.pig.builtin.mock.Storage.tuple;
import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Level;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.backend.executionengine.ExecJob;
import org.apache.pig.builtin.mock.Storage;
import org.apache.pig.builtin.mock.Storage.Data;
import org.apache.pig.data.Tuple;
import org.junit.Assert;
import org.junit.Test;

public class TestSpark {

    private static final ExecType MODE = ExecType.SPARK;
    private static final Log LOG = LogFactory.getLog(TestSpark.class);

    static {
        org.apache.log4j.Logger.getLogger("org.apache.pig.backend.hadoop.executionengine.spark").setLevel(Level.DEBUG);
    }

    private PigServer newPigServer() throws ExecException {
        Properties properties = new Properties();
        // to avoid pig running out of memory in LOCAL mode
        properties.put("io.sort.mb", "1");

        PigServer pigServer = new PigServer(MODE, properties);
        return pigServer;
    }

    @Test
    public void testLoadStore() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("test1"),
                tuple("test2"));
        pigServer.setBatchOn();
        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("STORE A INTO 'output' using mock.Storage;");
        List<ExecJob> executeBatch = pigServer.executeBatch();
        // TODO: good stats
        //      assertEquals(1, executeBatch.size());
        //      assertTrue(executeBatch.get(0).hasCompleted());

        assertEquals(
                Arrays.asList(tuple("test1"), tuple("test2")),
                data.get("output"));
        pigServer.shutdown();
    }

    @Test
    public void testDump() throws Exception {
        PigServer pigServer = new PigServer(MODE);
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("test1"),
                tuple("test2"));

        pigServer.setBatchOn();
        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        Iterator<Tuple> result = pigServer.openIterator("A");

        List<Tuple> resultList = new ArrayList<Tuple>();
        while (result.hasNext()) {
            resultList.add(result.next());
        }

        assertEquals(Arrays.asList(tuple("test1"), tuple("test2")), resultList);
        pigServer.shutdown();
    }

    @Test
    public void testGroupBy() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("foo", "key1", "test1"),
                tuple("bar", "key1", "test2"),
                tuple("baz", "key2", "test3"));

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = GROUP A BY $1;");
        pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(
                        tuple("key1", bag(tuple("foo", "key1", "test1"), tuple("bar", "key1", "test2"))),
                        tuple("key2", bag(tuple("baz", "key2", "test3")))),
                        sortByIndex(data.get("output"), 0));

        pigServer.shutdown();
    }

    @Test
    public void testMultiJobGroupBy() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("foo", "key1", "test1"),
                tuple("bar", "key1", "test2"),
                tuple("baz", "key2", "test3"));

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = GROUP A BY $1;");
        pigServer.registerQuery("C = FOREACH B GENERATE group, FLATTEN(A.$0), COUNT(A);");
        pigServer.registerQuery("D = GROUP C BY StringSize($1);");
        pigServer.registerQuery("STORE D INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(
                        tuple(3l,bag(tuple("key1","foo",2l),tuple("key1","bar",2l),tuple("key2","baz",1l)))),
                sortByIndex(data.get("output"), 0));

        pigServer.shutdown();
    }

    private List<Tuple> sortByIndex(List<Tuple> out, final int i) {
        List<Tuple> result = new ArrayList<Tuple>(out);
        Collections.sort(result, new Comparator<Tuple>() {
            @Override
            public int compare(Tuple o1, Tuple o2) {
                try {
                    Comparable c1 = (Comparable)o1.get(i);
                    Comparable c2 = (Comparable)o2.get(i);
                    return c1.compareTo(c2);
                } catch (ExecException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        return result;
    }

    @Test
    public void testGroupByFlatten() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("test1"),
                tuple("test1"),
                tuple("test2"));

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = GROUP A BY $0;");
        pigServer.registerQuery("C = FOREACH B GENERATE FLATTEN(A);");
        pigServer.registerQuery("STORE C INTO 'output' using mock.Storage;");

        List<Tuple> sortedOutput = data.get("output");
        Collections.sort(sortedOutput);

        assertEquals(
                Arrays.asList(tuple("test1"), tuple("test1"), tuple("test2")),
                sortedOutput);

        pigServer.shutdown();
    }

    @Test
    public void testCount() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("test1"),
                tuple("test1"),
                tuple("test2"));

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = GROUP A BY $0;");
        pigServer.registerQuery("C = FOREACH B GENERATE COUNT(A);");
        pigServer.registerQuery("STORE C INTO 'output' using mock.Storage;");

        List<Tuple> sortedOutput = data.get("output");
        Collections.sort(sortedOutput);

        assertEquals(
                Arrays.asList(tuple(1l), tuple(2l)),
                sortedOutput);

        pigServer.shutdown();
    }

    @Test
    public void testCountWithNoData() throws Exception {
        PigServer pigServer = new PigServer(ExecType.SPARK);
        Data data = Storage.resetData(pigServer);
        data.set("input");

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = GROUP A BY $0;");
        pigServer.registerQuery("C = FOREACH B GENERATE COUNT(A);");
        pigServer.registerQuery("STORE C INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(),
                data.get("output"));

        pigServer.shutdown();
    }

    @Test
    public void testForEach() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("1"),
                tuple("12"),
                tuple("123"));

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = FOREACH A GENERATE StringSize($0);");
        pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(tuple(1l), tuple(2l), tuple(3l)),
                data.get("output"));

        pigServer.shutdown();
    }

    @Test
    public void testForEachFlatten() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple(bag(tuple("1"), tuple("2"), tuple("3"))),
                tuple(bag(tuple("4"), tuple("5"), tuple("6"))));

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = FOREACH A GENERATE FLATTEN($0);");
        pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(tuple("1"), tuple("2"), tuple("3"), tuple("4"), tuple("5"), tuple("6")),
                data.get("output"));

        pigServer.shutdown();
    }

    @Test
    public void testSimpleUDF() throws Exception {
        PigServer pigServer = new PigServer(ExecType.SPARK);
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("Foo"),
                tuple("BAR"),
                tuple("baT"));

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = FOREACH A GENERATE org.apache.pig.spark.LowercaseUDF($0);");
        pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(tuple("foo"), tuple("bar"), tuple("bat")),
                data.get("output"));

        pigServer.shutdown();
    }

    @Test
    public void testFilter() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("1"),
                tuple("2"),
                tuple("3"),
                tuple("1"));

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = FILTER A BY $0 == '1';");
        pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(tuple("1"), tuple("1")),
                data.get("output"));

        pigServer.shutdown();
    }

    @Test
    public void testDistinct() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("1"),
                tuple("2"),
                tuple("3"),
                tuple("1"));

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = DISTINCT A;");
        pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(tuple("1"), tuple("2"), tuple("3")),
                sortByIndex(data.get("output"), 0));

        pigServer.shutdown();
    }

    @Test
    public void testExplicitSPLIT() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("1", 2, "foo"),
                tuple("2", 3, "bar"),
                tuple("2", 1, "bar"),
                tuple("1", 4, "foo"));

        pigServer.setBatchOn();
        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("SPLIT A INTO B IF $0 == '1', C IF $0 == '2';");
        pigServer.registerQuery("STORE B INTO 'output1' using mock.Storage;");
        pigServer.registerQuery("STORE C INTO 'output2' using mock.Storage;");
        pigServer.executeBatch();

        assertEquals(
                Arrays.asList(
                        tuple("1", 2, "foo"),
                        tuple("1", 4, "foo")
                        ),
                sortByIndex(data.get("output1"), 0));
        assertEquals(
                Arrays.asList(
                        tuple("2", 3, "bar"),
                        tuple("2", 1, "bar")
                        ),
                sortByIndex(data.get("output2"), 0));

        pigServer.shutdown();
    }

    @Test
    public void testExplicitSPLITWithDistinct() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("1", 2, "foo"),
                tuple("2", 3, "bar"),
                tuple("2", 1, "bar"),
                tuple("1", 4, "foo"));

        pigServer.setBatchOn();
        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = DISTINCT A;");
        pigServer.registerQuery("SPLIT B INTO C IF $0 == '1', D IF $0 == '2';");
        pigServer.registerQuery("E = DISTINCT C;");
        pigServer.registerQuery("F = DISTINCT D;");
        pigServer.registerQuery("STORE E INTO 'output1' using mock.Storage;");
        pigServer.registerQuery("STORE F INTO 'output2' using mock.Storage;");
        pigServer.executeBatch();

        assertEquals(
                Arrays.asList(
                        tuple("1", 2, "foo"),
                        tuple("1", 4, "foo")
                        ),
                sortByIndex(data.get("output1"), 1));
        assertEquals(
                Arrays.asList(
                        tuple("2", 1, "bar"),
                        tuple("2", 3, "bar")
                        ),
                sortByIndex(data.get("output2"),1));
        pigServer.shutdown();
    }

    @Test
    public void testImplicitSPLIT() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("1", 2, "foo"),
                tuple("2", 3, "bar"),
                tuple("2", 1, "bar"),
                tuple("1", 4, "foo"));

        pigServer.setBatchOn();
        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = FILTER A BY $0 == '1';");
        pigServer.registerQuery("C = FILTER A BY $0 == '2';");
        pigServer.registerQuery("STORE B INTO 'output1' using mock.Storage;");
        pigServer.registerQuery("STORE C INTO 'output2' using mock.Storage;");
        pigServer.executeBatch();

        assertEquals(
                Arrays.asList(
                        tuple("1", 2, "foo"),
                        tuple("1", 4, "foo")
                        ),
                sortByIndex(data.get("output1"), 0));
        assertEquals(
                Arrays.asList(
                        tuple("2", 3, "bar"),
                        tuple("2", 1, "bar")
                        ),
                sortByIndex(data.get("output2"), 0));

        pigServer.shutdown();
    }

    @Test
    public void testOrderBy() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("1", 2, "foo"),
                tuple("2", 3, "foo"),
                tuple("3", 1, "foo"),
                tuple("1", 4, "foo"));

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = ORDER A BY $1;");
        pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(
                        tuple("3", 1, "foo"),
                        tuple("1", 2, "foo"),
                        tuple("2", 3, "foo"),
                        tuple("1", 4, "foo")
                        ),
                data.get("output"));

        pigServer.shutdown();
    }

    @Test
    public void testLimit() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("1"),
                tuple("2"),
                tuple("3"),
                tuple("4"));

        pigServer.registerQuery("A = LOAD 'input' using mock.Storage;");
        pigServer.registerQuery("B = LIMIT A 2;");
        pigServer.registerQuery("STORE B INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(tuple("1"), tuple("2")),
                data.get("output"));

        pigServer.shutdown();
    }

    @Test
    public void testUnion() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input1",
                tuple("1"),
                tuple("2"),
                tuple("3"),
                tuple("4"));
        data.set("input2",
                tuple("5"),
                tuple("6"),
                tuple("7"),
                tuple("8"));

        pigServer.registerQuery("A = LOAD 'input1' using mock.Storage;");
        pigServer.registerQuery("B = LOAD 'input2' using mock.Storage;");
        pigServer.registerQuery("C = UNION A, B;");
        pigServer.registerQuery("STORE C INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(
                        tuple("1"),
                        tuple("2"),
                        tuple("3"),
                        tuple("4"),
                        tuple("5"),
                        tuple("6"),
                        tuple("7"),
                        tuple("8")),
                data.get("output"));

        pigServer.shutdown();
    }

    @Test
    public void testDistinctUnion() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input1",
                tuple("1"),
                tuple("2"),
                tuple("3"),
                tuple("4"),
                tuple("2"),
                tuple("3"));
        data.set("input2",
                tuple("5"),
                tuple("6"),
                tuple("7"),
                tuple("8"));

        pigServer.registerQuery("A = LOAD 'input1' using mock.Storage;");
        pigServer.registerQuery("B = LOAD 'input2' using mock.Storage;");
        pigServer.registerQuery("C = DISTINCT A;");
        pigServer.registerQuery("D = UNION C, B;");
        pigServer.registerQuery("STORE D INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(
                        tuple("1"),
                        tuple("2"),
                        tuple("3"),
                        tuple("4"),
                        tuple("5"),
                        tuple("6"),
                        tuple("7"),
                        tuple("8")),
                sortByIndex(data.get("output"),0));

        pigServer.shutdown();
    }

    @Test
    public void testCoGroup() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input1",
                tuple("foo", 1, "a"),
                tuple("foo", 2, "b"),
                tuple("foo", 3, "c"),
                tuple("foo", 1, "d"));
        data.set("input2",
                tuple("bar", 1, "e"),
                tuple("bar", 2, "f"),
                tuple("bar", 1, "g"));

        pigServer.registerQuery("A = LOAD 'input1' using mock.Storage;");
        pigServer.registerQuery("B = LOAD 'input2' using mock.Storage;");
        pigServer.registerQuery("C = COGROUP A BY $1, B BY $1;");
        pigServer.registerQuery("STORE C INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(
                        tuple(1,bag(tuple("foo", 1,"a"),tuple("foo", 1,"d")),bag(tuple("bar", 1,"e"),tuple("bar", 1,"g"))),
                        tuple(2,bag(tuple("foo", 2,"b")),bag(tuple("bar", 2,"f"))),
                        tuple(3,bag(tuple("foo", 3,"c")),bag())
                        ),
                        sortByIndex(data.get("output"), 0));

        pigServer.shutdown();
    }

    @Test
    public void testCoGroup2() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input1",
                tuple("foo", 1, "a"),
                tuple("foo", 2, "b"),
                tuple("foo", 3, "c"),
                tuple("foo", 1, "d"));
        data.set("input2",
                tuple("bar", 1, "e"),
                tuple("bar", 2, "f"),
                tuple("bar", 1, "g"));
        data.set("input3",
                tuple("baz", 3, "h"));
        data.set("input4",
                tuple("boz", 4, "i"));

        pigServer.registerQuery("A = LOAD 'input1' using mock.Storage;");
        pigServer.registerQuery("B = LOAD 'input2' using mock.Storage;");
        pigServer.registerQuery("C = LOAD 'input3' using mock.Storage;");
        pigServer.registerQuery("D = LOAD 'input4' using mock.Storage;");
        pigServer.registerQuery("E = COGROUP A BY $1, B BY $1, C BY $1, D BY $1;");
        pigServer.registerQuery("STORE E INTO 'output' using mock.Storage;");

        assertEquals(
                Arrays.asList(
                        tuple(1,bag(tuple("foo", 1,"a"),tuple("foo", 1,"d")),bag(tuple("bar", 1,"e"),tuple("bar", 1,"g")),bag(),bag()),
                        tuple(2,bag(tuple("foo", 2,"b")),bag(tuple("bar", 2,"f")),bag(),bag()),
                        tuple(3,bag(tuple("foo", 3,"c")),bag(),bag(tuple("baz", 3, "h")),bag()),
                        tuple(4,bag(),bag(),bag(),bag(tuple("boz", 4, "i")))
                        ),
                sortByIndex(data.get("output"), 0));

        pigServer.shutdown();
    }

    @Test
    public void testJoin() throws Exception {
        PigServer pigServer = newPigServer();
        Data data = Storage.resetData(pigServer);
        data.set("input1",
                tuple(1, "a"),
                tuple(2, "b"),
                tuple(3, "c"),
                tuple(1, "d"));
        data.set("input2",
                tuple(1, "e"),
                tuple(2, "f"),
                tuple(1, "g"));

        pigServer.registerQuery("A = LOAD 'input1' using mock.Storage;");
        pigServer.registerQuery("B = LOAD 'input2' using mock.Storage;");
        pigServer.registerQuery("C = JOIN A BY $0, B BY $0;");
        pigServer.registerQuery("STORE C INTO 'output' using mock.Storage;");

        List<Tuple> sortedOutput = data.get("output");
        Collections.sort(sortedOutput);

        assertEquals(
                Arrays.asList(
                        tuple(1, "a", 1, "e"),
                        tuple(1, "a", 1, "g"),
                        tuple(1, "d", 1, "e"),
                        tuple(1, "d", 1, "g"),
                        tuple(2, "b", 2, "f")
                        ),
                        sortedOutput);

        pigServer.shutdown();
    }

    @Test
    public void testCachingLoad() throws Exception {

        testCaching("A = LOAD 'input' using mock.Storage;" +
                "CACHE A;" +
                "STORE A INTO 'output' using mock.Storage;");
    }

    @Test
    public void testCachingLoadCast() throws Exception {

        testCaching("A = LOAD 'input' using mock.Storage as (foo:chararray);" +
                "CACHE A;" +
                "STORE A INTO 'output' using mock.Storage;");
    }

    @Test
    public void testCachingWithFilter() throws Exception {
        testCaching("A = LOAD 'input' using mock.Storage; " +
                "B = FILTER A by $0 == $0;" + // useless filter
                "A = FOREACH B GENERATE (chararray) $0;" +
                "CACHE A;" +
                "STORE A INTO 'output' using mock.Storage;");
    }

    @Test
    public void testCachingJoin() throws Exception {
        testCaching("A = LOAD 'input' using mock.Storage; " +
                "B = LOAD 'input' using mock.Storage; " +
                "A = JOIN A by $0, B by LOWER($0); " +
                "CACHE A; " +
                "STORE A INTO 'output' using mock.Storage;");
    }

    @Test
    public void testCachingGroup() throws Exception {
        testCaching("A = LOAD 'input' using mock.Storage; " +
                "A = GROUP A by LOWER($0); " +
                "CACHE A; " +
                "STORE A INTO 'output' using mock.Storage;");
    }

    @Test
    public void testIgnoreWrongUDFCache() throws Exception {
        testIgnoreCache(
                "A = LOAD 'input' using mock.Storage; " +
                "B = LOAD 'input' using mock.Storage; " +
                "A = JOIN A by $0, B by LOWER($0); " +
                "CACHE A; " +
                "STORE A INTO 'output' using mock.Storage;",
                "A = LOAD 'input' using mock.Storage; " +
                "B = LOAD 'input' using mock.Storage; " +
                "A = JOIN A by $0, B by UPPER($0); " +
                "CACHE A; " +
                "STORE A INTO 'output' using mock.Storage;");
    }

    @Test
    public void testIgnoreDiffFilterCache() throws Exception {
        testIgnoreCache("A = LOAD 'input' using mock.Storage;" +
                "A = FILTER A by $0 == 'test1';" +
                "CACHE A;" +
                "STORE A INTO 'output' using mock.Storage;",
                "A = LOAD 'input' using mock.Storage;" +
                "A = FILTER A by $0 == 'test2';" +
                "CACHE A;" +
                "STORE A INTO 'output' using mock.Storage;");

    }

    public void testIgnoreCache(String query1, String query2) throws Exception {
        PigServer pigServer = newPigServer();

        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("test1"),
                tuple("test2"));

        pigServer.setBatchOn();
        pigServer.registerQuery(query1);
        pigServer.executeBatch();

        List<Tuple> originalOutput = data.get("output");
        LOG.debug("After first query: " + originalOutput);

        data = Storage.resetData(pigServer);
        data.set("input",
                tuple("test3"),
                tuple("test4"));
        pigServer.registerQuery(query2);
        pigServer.executeBatch();

        LOG.debug("After second query: " + data.get("output"));

        Assert.assertFalse(
                originalOutput.equals(
                        data.get("output")));

        pigServer.shutdown();
    }

    /**
     * Kind of a hack: To test whether caching is happening, we modify a file on disk after caching
     * it in Spark.
     */
    private void testCaching(String query) throws Exception {
        PigServer pigServer = newPigServer();

        Data data = Storage.resetData(pigServer);
        data.set("input",
                tuple("test1"),
                tuple("test2"));

        pigServer.setBatchOn();
        pigServer.registerQuery(query);
        pigServer.executeBatch();

        LOG.debug("After first query: " + data.get("output"));
        List<Tuple> originalOutput = data.get("output");

        data = Storage.resetData(pigServer);
        data.set("input",
                tuple("test3"),
                tuple("test4"));

        pigServer.registerQuery("STORE A INTO 'output' using mock.Storage;");
        pigServer.executeBatch();

        LOG.debug("After second query: " + data.get("output"));

        assertEquals(
                originalOutput,
                data.get("output"));

        pigServer.shutdown();
    }
}


text:
package org.lewis.fs;

public class FSException extends Exception{

	private static final long serialVersionUID = 1L;

	public FSException(){}

	public FSException(Throwable cause) {
        super(cause);
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Rubex
  module AST
    module Expression
      module Literal
        class Double < Base
          def initialize(name)
            super
            @type = Rubex::DataType::F64.new
          end
        end
      end
    end
  end
end


text:
Need Music?

Use the angular spotify app to browse new releases and find your favorite songs.
 All you get is this text and a mostly barebones HTML document.

<form>

    <input type="text" class="form-control" placeholder="Search Artists..."
    [(ngModel)]="searchStr" name="searchStr" (keyup)="searchMusic()">

</form>

{{artist.name}}

            Genres:
            {{genre}}


text:
You and Marshmallow are toasted.
You can't stop laughing as Marshmallow rants about alien conspiracy theories.
The grumbling of your stomach announces the arrival of the munchies.
Converstation fades and in a moment your gaze connect.
Marshmallow leerily backs away, noticing the yearning in your eyes.


text:
function result = normt_rnd(mu,sigma2,left,right)
% PURPOSE: random draws from a normal truncated to (left,right) interval
% ------------------------------------------------------
% USAGE: y = normt_rnd(mu,sigma2,left,right)
% where:   mu = mean (nobs x 1)
%      sigma2 = variance (nobs x 1)
%        left = left truncation points (nobs x 1),   999 for +Infinity
%       right = right truncation points (nobs x 1), -999 for -Infinity
% ------------------------------------------------------
% RETURNS: y = (nobs x 1) vector
% ------------------------------------------------------
% NOTES: use y = normt_rnd(mu,sigma2,left,999)
%        to produce a left-truncated draw
%        use y = normt_rnd(mu_vector,sigma2_vector,-999*ones(nobs,1),right_vector)
%        to produce a vector of right-truncated draws
% ------------------------------------------------------
% SEE ALSO: normlt_rnd (left truncated draws), normrt_rnd (right truncated)
%

% adopted from truncnorm3.m file by
% Justin Tobias
% James P. LeSage, Dept of Finance & Economics
% Texas State Univeristy-San Marcos
% 601 University Drive
% San Marcos, TX 78666
% jlesage@spatial-econometrics.com
% last updated 10/2007
%
% For information on Bayesian Econometric Methods:
% Volume 7 of Econometric Exercises Series
% Cambridge University Press by Gary Koop, Dale Poirer and Justin Tobias
% see:
% www.econ.iastate.edu/faculty/tobias/Bayesian_exercises.html

if nargin ~= 4
error('normt_rnd: wrong # of input arguments');
end;

stderrs = sqrt(sigma2);

points_left = find(left==-999);
points_right = find(right==999);

a_term = norm_cdf( (left-mu)./stderrs);
a_term(points_left) = 0;

b_term = norm_cdf( (right-mu)./stderrs);
b_term(points_right) = 1;

uniforms = rand(length(mu),1);

p = a_term + uniforms.*(b_term - a_term);

result = mu + stderrs.*norm_inv(p);


text:
package views

import (
	"sync"

	"github.com/gdamore/tcell/v2"
)

// Widget is the base object that all onscreen elements implement.
type Widget interface {
	// Draw is called to inform the widget to draw itself.  A containing
	// Widget will generally call this during the application draw loop.
	Draw()

	// Resize is called in response to a resize of the View.  Unlike with
	// other events, Resize performed by parents first, and they must
	// then call their children.  This is because the children need to
	// see the updated sizes from the parents before they are called.
	// In general this is done *after* the views have updated.
	Resize()

	// HandleEvent is called to ask the widget to handle any events.
	// If the widget has consumed the event, it should return true.
	// Generally, events are handled by the lower layers first, that
	// is for example, a button may have a chance to handle an event
	// before the enclosing window or panel.
	//
	// Its expected that Resize events are consumed by the outermost
	// Widget, and the turned into a Resize() call.
	HandleEvent(ev tcell.Event) bool

	// SetView is used by callers to set the visual context of the
	// Widget.  The Widget should use the View as a context for
	// drawing.
	SetView(view View)

	// Size returns the size of the widget (content size) as width, height
	// in columns.  Layout managers should attempt to ensure that at least
	// this much space is made available to the View for this Widget.  Extra
	// space may be allocated on as an needed basis.
	Size() (int, int)

	// Watch is used to register an interest in this widget's events.
	// The handler will receive EventWidget events for this widget.
	// The order of event delivery when there are multiple watchers is
	// not specified, and may change from one event to the next.
	Watch(handler tcell.EventHandler)

	// Unwatch is used to urnegister an interest in this widget's events.
	Unwatch(handler tcell.EventHandler)
}

// EventWidget is an event delivered by a specific widget.
type EventWidget interface {
	Widget() Widget
	tcell.Event
}

type widgetEvent struct {
	widget Widget
	tcell.EventTime
}

func (wev *widgetEvent) Widget() Widget {
	return wev.widget
}

func (wev *widgetEvent) SetWidget(widget Widget) {
	wev.widget = widget
}

// WidgetWatchers provides a common implementation for base Widget Watch and
// Unwatch interfaces, suitable for embedding in more concrete widget
// implementations. This implementation is thread-safe, meaning an embedder can
// expect safety when calling WidgetWatcher methods from separate goroutines.
// In general, the views package does not support thread safety.
type WidgetWatchers struct {
	sync.Mutex
	watchers map[tcell.EventHandler]struct{}
}

// Watch monitors this WidgetWatcher, causing the handler to be fired
// with EventWidget as they are occur on the watched Widget.
func (ww *WidgetWatchers) Watch(handler tcell.EventHandler) {
	ww.Lock()
	defer ww.Unlock()
	if ww.watchers == nil {
		ww.watchers = make(map[tcell.EventHandler]struct{})
	}
	ww.watchers[handler] = struct{}{}
}

// Unwatch stops monitoring this WidgetWatcher. The handler will no longer
// be fired for Widget events.
func (ww *WidgetWatchers) Unwatch(handler tcell.EventHandler) {
	ww.Lock()
	defer ww.Unlock()
	if ww.watchers != nil {
		delete(ww.watchers, handler)
	}
}

// PostEvent delivers the EventWidget to all registered watchers.  It is
// to be called by the Widget implementation.
func (ww *WidgetWatchers) PostEvent(wev EventWidget) {
	ww.Lock()
	watcherCopy := make(map[tcell.EventHandler]struct{}, len(ww.watchers))
	for k := range ww.watchers {
		watcherCopy[k] = struct{}{}
	}
	ww.Unlock()
	for watcher := range watcherCopy {
		// Deliver events to all listeners, ignoring return value.
		watcher.HandleEvent(wev)
	}
}

// PostEventWidgetContent is called by the Widget when its content is
// changed, delivering EventWidgetContent to all watchers.
func (ww *WidgetWatchers) PostEventWidgetContent(w Widget) {
	ev := &EventWidgetContent{}
	ev.SetWidget(w)
	ev.SetEventNow()
	ww.PostEvent(ev)
}

// PostEventWidgetResize is called by the Widget when the underlying View
// has resized, delivering EventWidgetResize to all watchers.
func (ww *WidgetWatchers) PostEventWidgetResize(w Widget) {
	ev := &EventWidgetResize{}
	ev.SetWidget(w)
	ev.SetEventNow()
	ww.PostEvent(ev)
}

// PostEventWidgetMove is called by the Widget when it is moved to a new
// location, delivering EventWidgetMove to all watchers.
func (ww *WidgetWatchers) PostEventWidgetMove(w Widget) {
	ev := &EventWidgetMove{}
	ev.SetWidget(w)
	ev.SetEventNow()
	ww.PostEvent(ev)
}

// XXX: WidgetExposed, Hidden?
// XXX: WidgetExposed, Hidden?

// EventWidgetContent is fired whenever a widget's content changes.
type EventWidgetContent struct {
	widgetEvent
}

// EventWidgetResize is fired whenever a widget is resized.
type EventWidgetResize struct {
	widgetEvent
}

// EventWidgetMove is fired whenver a widget changes location.
type EventWidgetMove struct {
	widgetEvent
}


text:
package org.apache.cassandra.db;

import java.util.Collection;

import org.apache.cassandra.db.partitions.PartitionUpdate;
import org.apache.cassandra.schema.TableId;

public interface IMutation
{
    public void apply();
    public String getKeyspaceName();
    public Collection<TableId> getTableIds();
    public DecoratedKey key();
    public long getTimeout();
    public String toString(boolean shallow);
    public Collection<PartitionUpdate> getPartitionUpdates();

    public default void validateIndexedColumns()
    {
        for (PartitionUpdate pu : getPartitionUpdates())
            pu.validateIndexedColumns();
    }

    /**
     * Computes the total data size of the specified mutations.
     * @param mutations the mutations
     * @return the total data size of the specified mutations
     */
    public static long dataSize(Collection<? extends IMutation> mutations)
    {
        long size = 0;
        for (IMutation mutation : mutations)
        {
            for (PartitionUpdate update : mutation.getPartitionUpdates())
                size += update.dataSize();
        }
        return size;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
Uses of Class org.apache.commons.collections.collection.SynchronizedCollection (Commons Collections 3.2.1 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.commons.collections.collection.SynchronizedCollection

Packages that use SynchronizedCollection

org.apache.commons.collections.bag

This package contains implementations of the
Bag and
SortedBag interfaces.

org.apache.commons.collections.buffer

This package contains implementations of the
Buffer interface.

org.apache.commons.collections.list

This package contains implementations of the
List interface.

org.apache.commons.collections.set

This package contains implementations of the
Set and
SortedSet interfaces.

Uses of SynchronizedCollection in org.apache.commons.collections.bag

Subclasses of SynchronizedCollection in org.apache.commons.collections.bag

 class
SynchronizedBag

          Decorates another Bag to synchronize its behaviour
 for a multi-threaded environment.

 class
SynchronizedSortedBag

          Decorates another SortedBag to synchronize its behaviour
 for a multi-threaded environment.

Uses of SynchronizedCollection in org.apache.commons.collections.buffer

Subclasses of SynchronizedCollection in org.apache.commons.collections.buffer

 class
BlockingBuffer

          Decorates another Buffer to make BlockingBuffer.get() and
 BlockingBuffer.remove() block when the Buffer is empty.

 class
BoundedBuffer

          Decorates another Buffer to ensure a fixed maximum size.

 class
SynchronizedBuffer

          Decorates another Buffer to synchronize its behaviour
 for a multi-threaded environment.

Uses of SynchronizedCollection in org.apache.commons.collections.list

Subclasses of SynchronizedCollection in org.apache.commons.collections.list

 class
SynchronizedList

          Decorates another List to synchronize its behaviour
 for a multi-threaded environment.

Uses of SynchronizedCollection in org.apache.commons.collections.set

Subclasses of SynchronizedCollection in org.apache.commons.collections.set

 class
SynchronizedSet

          Decorates another Set to synchronize its behaviour for a
 multi-threaded environment.

 class
SynchronizedSortedSet

          Decorates another SortedSet to synchronize its behaviour
 for a multi-threaded environment.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2001-2008 The Apache Software Foundation. All Rights Reserved.


text:
define(['../system', '../viewModel', '../app'], function (system, viewModel, app) {

    //NOTE: Sammy.js is not required by the core of Durandal.
    //However, this plugin leverages it to enable navigation.

    var routesByPath = {},
        allRoutes = ko.observableArray([]),
        visibleRoutes = ko.observableArray([]),
        ready = ko.observable(false),
        isNavigating = ko.observable(false),
        sammy,
        router,
        previousRoute,
        previousModule,
        cancelling = false,
        activeItem = viewModel.activator(),
        activeRoute = ko.observable(),
        navigationDefaultRoute,
        queue = [],
        skipRouteUrl;

    var tryActivateRouter = function () {
        tryActivateRouter = system.noop;
        ready(true);
        router.dfd.resolve();
        delete router.dfd;
    };

    activeItem.settings.areSameItem = function (currentItem, newItem, activationData) {
        return false;
    };

    function redirect(url) {
        isNavigating(false);
        system.log('Redirecting');
        router.navigateTo(url);
    }

    function cancelNavigation() {
        cancelling = true;
        system.log('Cancelling Navigation');

        if (previousRoute) {
            sammy.setLocation(previousRoute);
        }

        cancelling = false;
        isNavigating(false);

        var routeAttempted = sammy.last_location[1].split('#/')[1];

        if (previousRoute || !routeAttempted) {
            tryActivateRouter();
        } else if (routeAttempted != navigationDefaultRoute) {
            window.location.replace("#/" + navigationDefaultRoute);
        } else {
            tryActivateRouter();
        }
    }

    function completeNavigation(routeInfo, params, module) {
        activeRoute(routeInfo);
        router.onNavigationComplete(routeInfo, params, module);
        previousModule = module;
        previousRoute = sammy.last_location[1].replace('/', '');
        tryActivateRouter();
    }

    function activateRoute(routeInfo, params, module) {
        system.log('Activating Route', routeInfo, module, params);

        activeItem.activateItem(module, params).then(function (succeeded) {
            if (succeeded) {
                completeNavigation(routeInfo, params, module);
            } else {
                cancelNavigation();
            }
        });
    }

    function shouldStopNavigation() {
        return cancelling || (sammy.last_location[1].replace('/', '') == previousRoute);
    }

    function handleGuardedRoute(routeInfo, params, instance) {
        var resultOrPromise = router.guardRoute(routeInfo, params, instance);
        if (resultOrPromise) {
            if (resultOrPromise.then) {
                resultOrPromise.then(function(result) {
                    if (result) {
                        if (typeof result == 'string') {
                            redirect(result);
                        } else {
                            activateRoute(routeInfo, params, instance);
                        }
                    } else {
                        cancelNavigation();
                    }
                });
            } else {
                if (typeof resultOrPromise == 'string') {
                    redirect(resultOrPromise);
                } else {
                    activateRoute(routeInfo, params, instance);
                }
            }
        } else {
            cancelNavigation();
        }
    }

    function dequeueRoute() {
        if (isNavigating()) {
            return;
        }

        var next = queue.shift();
        queue = [];

        if (!next) {
            return;
        }

        isNavigating(true);

        system.acquire(next.routeInfo.moduleId).then(function(module) {
            next.params.routeInfo = next.routeInfo;
            next.params.router = router;

            var instance = router.getActivatableInstance(next.routeInfo, next.params, module);

            if (router.guardRoute) {
                handleGuardedRoute(next.routeInfo, next.params, instance);
            } else {
                activateRoute(next.routeInfo, next.params, instance);
            }
        });
    }

    function queueRoute(routeInfo, params) {
        queue.unshift({
            routeInfo: routeInfo,
            params: params
        });

        dequeueRoute();
    }

    function ensureRoute(route, params) {
        var routeInfo = routesByPath[route];

        if (shouldStopNavigation()) {
            return;
        }

        if (!routeInfo) {
            if (!router.autoConvertRouteToModuleId) {
                router.handleInvalidRoute(route, params);
                return;
            }

            routeInfo = {
                moduleId: router.autoConvertRouteToModuleId(route, params),
                name: router.convertRouteToName(route)
            };
        }

        queueRoute(routeInfo, params);
    }

    function handleDefaultRoute() {
        ensureRoute(navigationDefaultRoute, this.params || {});
    }

    function handleMappedRoute() {
        ensureRoute(this.app.last_route.path.toString(), this.params || {});
    }

    function handleWildCardRoute() {
        var params = this.params || {}, route;

        if (router.autoConvertRouteToModuleId) {
            var fragment = this.path.split('#/');

            if (fragment.length == 2) {
                var parts = fragment[1].split('/');
                route = parts[0];
                params.splat = parts.splice(1);
                ensureRoute(route, params);
                return;
            }
        }

        router.handleInvalidRoute(this.app.last_location[1], params);
    }

    function configureRoute(routeInfo) {
        router.prepareRouteInfo(routeInfo);

        routesByPath[routeInfo.url.toString()] = routeInfo;
        allRoutes.push(routeInfo);

        if (routeInfo.visible) {
            routeInfo.isActive = ko.computed(function () {
                return ready() && activeItem() && activeItem().__moduleId__ == routeInfo.moduleId;
            });

            visibleRoutes.push(routeInfo);
        }

        return routeInfo;
    }

    return router = {
        ready: ready,
        allRoutes: allRoutes,
        visibleRoutes: visibleRoutes,
        isNavigating: isNavigating,
        activeItem: activeItem,
        activeRoute: activeRoute,
        afterCompose: function () {
            setTimeout(function () {
                isNavigating(false);
                dequeueRoute();
            }, 10);
        },
        getActivatableInstance: function (routeInfo, params, module) {
            if (typeof module == 'function') {
                return new module();
            } else {
                return module;
            }
        },
        useConvention: function (rootPath) {
            rootPath = rootPath == null ? 'viewmodels' : rootPath;
            if (rootPath) {
                rootPath += '/';
            }
            router.convertRouteToModuleId = function (url) {
                return rootPath + router.stripParameter(url);
            };
        },
        stripParameter: function (val) {
            var colonIndex = val.indexOf(':');
            var length = colonIndex > 0 ? colonIndex - 1 : val.length;
            return val.substring(0, length);
        },
        handleInvalidRoute: function (route, params) {
            system.log('No Route Found', route, params);
        },
        onNavigationComplete: function (routeInfo, params, module) {
            if (app.title) {
                document.title = routeInfo.caption + " | " + app.title;
            } else {
                document.title = routeInfo.caption;
            }
        },
        navigateBack: function () {
            window.history.back();
        },
        navigateTo: function (url, option) {
            option = option || 'trigger';

            switch (option.toLowerCase()) {
                case 'skip':
                    skipRouteUrl = url;
                    sammy.setLocation(url);
                    break;
                case 'replace':
                    window.location.replace(url);
                    break;
                default:
                    if (sammy.lookupRoute('get', url)) {
                        sammy.setLocation(url);
                    } else {
                        window.location.href = url;
                    }
                    break;
            }
        },
        replaceLocation: function (url) {
            this.navigateTo(url, 'replace');
        },
        convertRouteToName: function (route) {
            var value = router.stripParameter(route);
            return value.substring(0, 1).toUpperCase() + value.substring(1);
        },
        convertRouteToModuleId: function (route) {
            return router.stripParameter(route);
        },
        prepareRouteInfo: function (info) {
            if (!(info.url instanceof RegExp)) {
                info.name = info.name || router.convertRouteToName(info.url);
                info.moduleId = info.moduleId || router.convertRouteToModuleId(info.url);
                info.hash = info.hash || '#/' + info.url;
            }

            info.caption = info.caption || info.name;
            info.settings = info.settings || {};
        },
        mapAuto: function (path) {
            path = path || 'viewmodels';
            path += '/';

            router.autoConvertRouteToModuleId = function (url, params) {
                return path + router.stripParameter(url);
            };
        },
        mapNav: function (urlOrConfig, moduleId, name) {
            if (typeof urlOrConfig == "string") {
                return this.mapRoute(urlOrConfig, moduleId, name, true);
            }

            urlOrConfig.visible = true;
            return configureRoute(urlOrConfig);
        },
        mapRoute: function (urlOrConfig, moduleId, name, visible) {
            if (typeof urlOrConfig == "string") {
                return configureRoute({
                    url: urlOrConfig,
                    moduleId: moduleId,
                    name: name,
                    visible: visible
                });
            } else {
                return configureRoute(urlOrConfig);
            }
        },
        map: function (routeOrRouteArray) {
            if (!system.isArray(routeOrRouteArray)) {
                return configureRoute(routeOrRouteArray);
            }

            var configured = [];
            for (var i = 0; i < routeOrRouteArray.length; i++) {
                configured.push(configureRoute(routeOrRouteArray[i]));
            }
            return configured;
        },
        activate: function (defaultRoute) {
            return system.defer(function (dfd) {
                var processedRoute;

                router.dfd = dfd;
                navigationDefaultRoute = defaultRoute;

                sammy = Sammy(function (route) {
                    var unwrapped = allRoutes();

                    for (var i = 0; i < unwrapped.length; i++) {
                        var current = unwrapped[i];
                        route.get(current.url, handleMappedRoute);
                        processedRoute = this.routes.get[i];
                        routesByPath[processedRoute.path.toString()] = current;
                    }

                    route.get('#/', handleDefaultRoute);
                    route.get(/\#\/(.*)/, handleWildCardRoute);
                });

                sammy._checkFormSubmission = function () {
                    return false;
                };

                sammy.before(null, function(context) {
                    if (!skipRouteUrl) {
                        return true;
                    } else if (context.path === "/" + skipRouteUrl) {
                        skipRouteUrl = null;
                        return false;
                    } else {
                        throw new Error("Expected to skip url '" + skipRouteUrl + "', but found url '" + context.path + "'");
                    }
                });

                sammy.log = function () {
                    var args = Array.prototype.slice.call(arguments, 0);
                    args.unshift('Sammy');
                    system.log.apply(system, args);
                };

                sammy.run('#/');
            }).promise();
        }
    };
});


text:
package org.axonframework.config;

import org.axonframework.commandhandling.CommandBus;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.eventsourcing.eventstore.EventStore;
import org.axonframework.eventsourcing.eventstore.inmemory.InMemoryEventStorageEngine;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;

import javax.inject.Inject;

import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;

public class ConfigurationResourceInjectorTest {

    private Configuration configuration;
    private ConfigurationResourceInjector testSubject;

    @BeforeEach
    void setUp() {
        configuration = DefaultConfigurer.defaultConfiguration()
                .configureEmbeddedEventStore(c -> new InMemoryEventStorageEngine())
                .buildConfiguration();
        testSubject = new ConfigurationResourceInjector(configuration);
    }

    @Test
    void injectorHasResource() {
        Saga saga = new Saga();
        testSubject.injectResources(saga);

        assertSame(configuration.commandBus(), saga.commandBus);
        assertSame(configuration.commandGateway(), saga.commandGateway);
        assertSame(configuration.eventStore(), saga.eventStore);
        assertNull(saga.inexistent);
    }

    public static class Saga {

        @Inject
        private CommandBus commandBus;

        @Inject
        private String inexistent;

        private CommandGateway commandGateway;
        private EventStore eventStore;

        @Inject
        public void setCommandGateway(CommandGateway commandGateway) {
            this.commandGateway = commandGateway;
        }

        @Inject
        public void setEventStore(EventStore eventStore) {
            this.eventStore = eventStore;
        }
    }
}


text:
<?php

namespace KaLLoSz\Twig\Extension\Cache;

use Doctrine\Common\Cache\Cache;

/**
 * Class DoctrineCacheBridge
 */
class DoctrineCacheBridge implements CacheInterface
{
    /**
     * @var Cache
     */
    private $cache;

    /**
     * @param Cache $cache
     */
    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }

    /**
     * {@inheritdoc}
     */
    public function get($id)
    {
        return $this->has($id) ? $this->cache->fetch($id) : false;
    }

    /**
     * {@inheritdoc}
     */
    public function has($id)
    {
        return $this->cache->contains($id);
    }

    /**
     * {@inheritdoc}
     */
    public function save($id, $data, $lifeTime = 0)
    {
        return $this->cache->save($id, $data, $lifeTime);
    }

    /**
     * {@inheritdoc}
     */
    public function delete($id)
    {
        return $this->cache->delete($id);
    }
}


text:
Flask-Uploads
-------------
Flask-Uploads provides flexible upload handling for Flask applications. It
lets you divide your uploads into sets that the application user can publish
separately.

Links
`````
* `documentation <http://flask-uploads.readthedocs.io/en/latest/>`_
* `development version
  <https://github.com/maxcountryman/flask-uploads>`_


text:
<?php
/**
 * OfficialArtistWebpageTest.php
 *
 * Creation date: 2014-09-27
 * Creation time: 20:35
 *
 * @author Arkadiusz Moskwa <a.moskwa@gmail.com>
 */

namespace Nakard\MusicFormats\Tests\Media\Id3v2\Frame\UrlLink;

use Nakard\MusicFormats\Media\Id3v2\Frame\UrlLink\OfficialArtistWebpage;

/**
 * Class OfficialArtistWebpageTest
 *
 * @package Nakard\MusicFormats\Tests\Media\Id3v2\Frame\UrlLink
 */
class OfficialArtistWebpageTest extends AbstractFrameTestCase
{
    /**
     * @var OfficialArtistWebpage
     */
    protected $frame;

    protected function setUp()
    {
        parent::setUp();
        $this->frame = new OfficialArtistWebpage();
    }

    public function testGetIdentifier()
    {
        $this->assertSame('WOAR', $this->frame->getIdentifier());
    }
}


text:
package cityBomber.logic;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Writer;

import android.content.SharedPreferences;

import Model.LanguageRecord;
import Model.Session;

public class FileReader {

	public static void SwitchLanguage(InputStream in )
	{
		try {
			if(in != null)
			{
				String line = "";
				InputStreamReader input = new InputStreamReader(in);
				BufferedReader buffreader = new BufferedReader(input);
				while((line = buffreader.readLine()) != null)
				{
					String[] s = line.split("=");
					Session.addLanguageElement(s[0], s[1]);
				}
				in.close();

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/*public static void LoadSettings(String filename )
	{

		try {
			if(in != null)
			{
				String line = "";
				InputStreamReader input = new InputStreamReader(in);
				BufferedReader buffreader = new BufferedReader(input);
				while((line = buffreader.readLine()) != null)
				{
					String[] s = line.split("=");
					if(s[0].equals("SOUND"))
					{
						Session.setSound(Boolean.parseBoolean(s[1]));
					}
					else if(s[0].equals("ANIMATIONS "))
					{
						Session.setAnimations(Boolean.parseBoolean(s[1]));
					}
					else if(s[0].equals("SATELLITEIMG"))
					{
						Session.setSatellite(Boolean.parseBoolean(s[1]));
					}
					else if(s[0].equals("LANGUAGE"))
					{
						System.out.println("LANGUAGE " +s[1]);
						Session.setLanguage(s[1]);
					}
				}
				in.close();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}*/

	public static void LoadLanguages(InputStream in )
	{
		try {
			Session.addLanguageRecordElement(new LanguageRecord("English", "en.jpg", ""));
			if(in != null)
			{
				String line = "";
				InputStreamReader input = new InputStreamReader(in);
				BufferedReader buffreader = new BufferedReader(input);
				while((line = buffreader.readLine()) != null)
				{
					String[] s = line.split("\" \"|\"");
					Session.addLanguageRecordElement(new LanguageRecord(s[1], s[2], s[3]));
				}
				in.close();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}


text:
package com.ansorgit.plugins.bash.lang;

/**
 * Enumeration of the supported Bash versions.
 * The plugin has a Bash v4 mode and a Bash v3 mode. The parser and lexer
 * can be configured to also support the v4 features / changes.
 * <p/>
 * User: jansorg
 * Date: Dec 1, 2009
 * Time: 7:47:20 PM
 */
@Deprecated //TODO [VISTALL] rewrite to use LanguageVersion
public enum BashVersion {
    Bash_v3, Bash_v4
}


text:
package ru.job4j.start;
/**
*
* interface.
* auhtor Sergey
* version 0.1
*/

public interface UserAction {
/**
* method key.
* @return int
*/
	int key();
/**
* method execute.
* @param input first
* @param tracker second
*/
	void execute(Input input, Tracker tracker);
/**
* method key.
* @return String
*/
	String info();
}


text:
package scott.com.workhard.data.sourse.rest.response;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

import scott.com.workhard.entities.Workout;

/**
 * Created by androiddev3 on 10/21/16.
 */
public class ResponseWorkout {
    @SerializedName("workouts")
    @Expose
    private List<Workout> workouts;

    public List<Workout> getWorkouts() {
        return workouts;
    }

    public void setWorkouts(List<Workout> workouts) {
        this.workouts = workouts;
    }
}


text:
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm Inc.
//
// 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.
//
////////////////////////////////////////////////////////////////////////////

using System;
using System.IO;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Bogus;
using Realms;

namespace PerformanceTests
{
    public abstract class BenchmarkBase
    {
        protected readonly Faker _faker = new Faker();

        protected Realm _realm;

        static BenchmarkBase()
        {
            Randomizer.Seed = new Random(12345);
        }

        [GlobalSetup]
        public void Setup()
        {
            _realm = Realm.GetInstance(Path.GetTempFileName());
            SeedData();
        }

        [GlobalCleanup]
        public void Cleanup()
        {
            CleanupCore();

            _realm.Dispose();

            for (var i = 0; i < 10; i++)
            {
                try
                {
                    Realm.DeleteRealm(_realm.Config);
                    break;
                }
                catch
                {
                    Task.Delay(10).Wait();
                }
            }
        }

        protected virtual void SeedData()
        {
        }

        protected virtual void CleanupCore()
        {
        }
    }
}


text:
using System.Collections.Generic;

namespace AecCloud.WebAPI.Models.DataAnnotations
{
    public class MfilesClientConfig
    {
        public string Guid { set; get; }
        public string Host { set; get; }
        public string Name { set; get; }
    }
    //public enum NotificationTypeEnum
    //{
    //    NewTask = 1, WorkFlowAssigned = 2, Other = 3, NewDoc = 4, UpdateDoc = 5, DelDoc = 6, NewOtherObj = 7, UpdateOtherObj = 8, DelOtherObj = 9, UpdateTask = 10, TaskDone = 11
    //}
    //public class MfTask
    //{
    //    public MfTask()
    //    {
    //        ClientType = 0;//0:mfiles事件请求,1:客户端请求

    //        Id = -1;
    //        Type = -1;
    //        Version = -1;

    //        ClientName = string.Empty;
    //        VaultGuid = string.Empty;
    //        UserId = string.Empty;
    //        IsDeleted = false;
    //        Name = string.Empty;
    //        Desc = string.Empty;
    //        Time = string.Empty;
    //        LastModifiedTime = string.Empty;
    //        NotificationType = NotificationTypeEnum.Other;

    //        Date = string.Empty;
    //        Monitor = string.Empty;
    //        Createby = string.Empty;
    //        Url = string.Empty;
    //        IsNoticed = 0;//0:未通知,1:已通知
    //    }
    //    public int ClientType;
    //    public string ClientName;
    //    public string VaultGuid;
    //    public NotificationTypeEnum NotificationType;
    //    public List<string> UserIds = new List<string>();
    //    public int Id;
    //    public int Type;
    //    public int Version;

    //    public string UserId;
    //    public bool IsDeleted;
    //    public string Name;
    //    public string Desc;
    //    public string Time;
    //    public string LastModifiedTime;

    //    public string Date;
    //    public string Monitor;
    //    public string Createby;
    //    public string Url;
    //    public int IsNoticed;
    //}
}


text:
import 'chrome://webui-test/mojo_webui_test_support.js';

import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {InfiniteList, TabData, TabItemType, TabSearchItem, TitleItem} from 'chrome://tab-search.top-chrome/tab_search.js';
import {assertEquals, assertGT, assertNotEquals, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {flushTasks, waitAfterNextRender} from 'chrome://webui-test/polymer_test_util.js';

import {generateSampleTabsFromSiteNames, sampleSiteNames} from './tab_search_test_data.js';
import {assertTabItemAndNeighborsInViewBounds, disableAnimationBehavior} from './tab_search_test_helper.js';

const SAMPLE_AVAIL_HEIGHT = 336;
const SAMPLE_HEIGHT_VIEWPORT_ITEM_COUNT = 6;
const SAMPLE_SECTION_CLASS = 'section-title';

class TestApp extends PolymerElement {
  static get properties() {
    return {
      maxHeight_: {
        type: Number,
        value: SAMPLE_AVAIL_HEIGHT,
      },
    };
  }

  static get template() {
    return html`
    <infinite-list max-height="[[maxHeight_]]">
      <template data-type="TitleItem">

[[item.title]]

      </template>
      <template data-type="TabData" data-selectable>
        <tab-search-item id="[[item.tab.tabId]]"
            style="display: flex;height: 56px" data="[[item]]" tabindex="0"
            role="option">
        </tab-search-item>
      </template>
    </infinite-list>`;
  }
}

customElements.define('test-app', TestApp);

suite('InfiniteListTest', () => {
  let infiniteList: InfiniteList;

  disableAnimationBehavior(InfiniteList, 'scrollTo');
  disableAnimationBehavior(TabSearchItem, 'scrollIntoView');

  async function setupTest(sampleData: Array<TabData|TitleItem>) {
    const testApp = document.createElement('test-app');
    document.body.innerHTML = window.trustedTypes!.emptyHTML;
    document.body.appendChild(testApp);

    infiniteList = testApp.shadowRoot!.querySelector('infinite-list')!;
    infiniteList.items = sampleData;
    await flushTasks();
  }

  function queryRows(): NodeListOf<HTMLElement> {
    return infiniteList.querySelectorAll('tab-search-item');
  }

  function queryClassElements(className: string): NodeListOf<HTMLElement> {
    return infiniteList.querySelectorAll('.' + className);
  }

  function sampleTabItems(siteNames: string[]): TabData[] {
    return generateSampleTabsFromSiteNames(siteNames).map(tab => {
      return new TabData(
          tab, TabItemType.OPEN_TAB, new URL(tab.url.url).hostname);
    });
  }

  test('ScrollHeight', async () => {
    const tabItems = sampleTabItems(sampleSiteNames(5));
    await setupTest(tabItems);
    await waitAfterNextRender(infiniteList);

    assertEquals(0, infiniteList.scrollTop);

    const itemHeightStyle =
        getComputedStyle(document.head).getPropertyValue('--mwb-item-height');
    assertTrue(itemHeightStyle.endsWith('px'));

    const tabItemHeight = Number.parseInt(
        itemHeightStyle.substring(0, itemHeightStyle.length - 2), 10);
    assertEquals(tabItemHeight * tabItems.length, infiniteList.scrollHeight);
  });

  test('ListUpdates', async () => {
    await setupTest(sampleTabItems(sampleSiteNames(1)));
    assertEquals(1, queryRows().length);

    // Ensure that on updating the list with an array smaller in size
    // than the viewport item count, all the array items are rendered.
    infiniteList.items = sampleTabItems(sampleSiteNames(3));
    await waitAfterNextRender(infiniteList);
    assertEquals(3, queryRows().length);

    // Ensure that on updating the list with an array greater in size than
    // the viewport item count, only a chunk of array items are rendered.
    const tabItems =
        sampleTabItems(sampleSiteNames(2 * SAMPLE_HEIGHT_VIEWPORT_ITEM_COUNT));
    infiniteList.items = tabItems;
    await waitAfterNextRender(infiniteList);
    assertGT(tabItems.length, queryRows().length);
  });

  test('SelectedIndex', async () => {
    const itemCount = 25;
    const tabItems = sampleTabItems(sampleSiteNames(itemCount));
    await setupTest(tabItems);

    assertEquals(0, infiniteList.scrollTop);

    // Assert that upon changing the selected index to a non previously rendered
    // item, this one is rendered on the view.
    infiniteList.selected = itemCount - 1;
    await waitAfterNextRender(infiniteList);
    let domTabItems = queryRows();
    const selectedTabItem = domTabItems[infiniteList.selected];
    assertNotEquals(null, selectedTabItem);
    assertEquals(25, domTabItems.length);

    // Assert that the view scrolled to show the selected item.
    const afterSelectionScrollTop = infiniteList.scrollTop;
    assertNotEquals(0, afterSelectionScrollTop);

    // Assert that on replacing the list items, the currently selected index
    // value is still rendered on the view.
    infiniteList.items = sampleTabItems(sampleSiteNames(itemCount));
    await waitAfterNextRender(infiniteList);
    domTabItems = queryRows();
    const theSelectedTabItem = domTabItems[infiniteList.selected];
    assertNotEquals(null, theSelectedTabItem);

    // Assert the selected item is still visible in the view.
    assertEquals(afterSelectionScrollTop, infiniteList.scrollTop);
  });

  test('SelectedIndexValidAfterItemRemoval', async () => {
    const numTabItems = 5;
    const tabItems = sampleTabItems(sampleSiteNames(numTabItems));
    await setupTest(tabItems);
    infiniteList.selected = numTabItems - 1;

    // Assert that on having the last item selected and removing this last item
    // the selected index moves up to the last item available and that in
    // the case there are no more items, the selected index is -1.
    for (let i = numTabItems - 1; i >= 0; i--) {
      infiniteList.items = tabItems.slice(0, i);
      await waitAfterNextRender(infiniteList);
      assertEquals(i, queryRows().length);
      assertEquals(i - 1, infiniteList.selected);
    }
  });

  test('NavigateDownShowsPreviousAndFollowingListItems', async () => {
    const tabItems = sampleTabItems(sampleSiteNames(10));
    await setupTest(tabItems);

    // Assert that the tabs are in a overflowing state.
    assertGT(infiniteList.scrollHeight, infiniteList.clientHeight);

    infiniteList.selected = 0;
    for (let i = 0; i < tabItems.length; i++) {
      infiniteList.navigate('ArrowDown');
      await waitAfterNextRender(infiniteList);

      const selectedIndex = ((i + 1) % tabItems.length);
      assertEquals(selectedIndex, infiniteList.selected);
      assertTabItemAndNeighborsInViewBounds(
          infiniteList, queryRows(), selectedIndex);
    }
  });

  test('NavigateUpShowsPreviousAndFollowingListItems', async () => {
    const tabItems = sampleTabItems(sampleSiteNames(10));
    await setupTest(tabItems);

    // Assert that the tabs are in a overflowing state.
    assertGT(infiniteList.scrollHeight, infiniteList.clientHeight);

    infiniteList.selected = 0;
    for (let i = tabItems.length; i > 0; i--) {
      infiniteList.navigate('ArrowUp');
      await waitAfterNextRender(infiniteList);

      const selectIndex = (i - 1 + tabItems.length) % tabItems.length;
      assertEquals(selectIndex, infiniteList.selected);
      assertTabItemAndNeighborsInViewBounds(
          infiniteList, queryRows(), selectIndex);
    }
  });

  test('ListSelection', async () => {
    const tabItems = sampleTabItems(sampleSiteNames(2));
    const listItems = [
      new TitleItem('Title 1'),
      ...tabItems,
      new TitleItem('Title 2'),
      ...tabItems,
    ];

    setupTest(listItems);
    assertEquals(2, queryClassElements(SAMPLE_SECTION_CLASS).length);
    assertEquals(4, queryRows().length);

    infiniteList.selected = 0;
    await waitAfterNextRender(infiniteList);

    const selectableItemCount = 2 * tabItems.length;
    for (let i = 0; i < selectableItemCount; i++) {
      infiniteList.navigate('ArrowDown');
      await waitAfterNextRender(infiniteList);

      assertEquals((i + 1) % selectableItemCount, infiniteList.selected);
      assertTrue(infiniteList.selectedItem instanceof TabData);
    }

    infiniteList.items = [];
    await waitAfterNextRender(infiniteList);
    assertEquals(0, queryClassElements(SAMPLE_SECTION_CLASS).length);
    assertEquals(0, queryRows().length);
  });
});


text:
/**
 * curl style! plugin
 */

window['vtex']['define']([], function () {

	var nonRelUrlRe, findUrlRx, undef, doc, head;

	if (typeof window != 'undefined') {
		doc = window.document;
		head = doc.head || doc.getElementsByTagName('head')[0];
	}

	// tests for absolute urls and root-relative urls
	nonRelUrlRe = /^\/|^[^:]*:\/\//;
	// Note: this will fail if there are parentheses in the url
	findUrlRx = /url\s*\(['"]?([^'"\)]*)['"]?\)/g;

	function translateUrls (cssText, baseUrl) {
		return cssText.replace(findUrlRx, function (all, url) {
			return 'url("' + translateUrl(url, baseUrl) + '")';
		});
	}

	function translateUrl (url, parentPath) {
		// if this is a relative url
		if (!nonRelUrlRe.test(url)) {
			// append path onto it
			url = parentPath + url;
		}
		return url;
	}

	/***** style element functions *****/

	var currentStyle, callbacks = [];

	function createStyle (cssText, callback, errback) {

		try {
			clearTimeout(createStyle.debouncer);
			if (createStyle.accum) {
				createStyle.accum.push(cssText);
			}
			else {
				createStyle.accum = [cssText];
				currentStyle = doc.createStyleSheet ? doc.createStyleSheet() :
					head.appendChild(doc.createElement('style'));
			}

			callbacks.push({
				callback: callback,
				errback: errback,
				sheet: currentStyle
			});

			createStyle.debouncer = setTimeout(function () {
				var style, allCssText;

				try {
					style = currentStyle;
					currentStyle = undef;

					allCssText = createStyle.accum.join('\n');
					createStyle.accum = undef;

					// for safari which chokes on @charset "UTF-8";
					// TODO: see if Safari 5.x and up still complain
					allCssText = allCssText.replace(/.+charset[^;]+;/g, '');

					// IE 6-8 won't accept the W3C method for inserting css text
					'cssText' in style ? style.cssText = allCssText :
						style.appendChild(doc.createTextNode(allCssText));

					waitForDocumentComplete(notify);
				}
				catch (ex) {
					// just notify most recent errback. no need to spam
					errback(ex);
				}

			}, 0);

		}
		catch (ex) {
			errback(ex);
		}

	}

	function notify () {
		var list = callbacks;
		callbacks = [];
		for (var i = 0, len = list.length; i < len; i++) {
			list[i].callback(list[i].sheet);
		}
	}

	/**
	 * Keep checking for the document readyState to be "complete" since
	 * Chrome doesn't apply the styles to the document until that time.
	 * If we return before readyState == 'complete', Chrome may not have
	 * applied the styles, yet.
	 * Chrome only.
	 * @private
	 * @param cb
	 */
	function waitForDocumentComplete (cb) {
		// this isn't exactly the same as domReady (when dom can be
		// manipulated). it's later (when styles are applied).
		// chrome needs this (and opera?)
		function complete () {
			if (isDocumentComplete()) {
				cb();
			}
			else {
				setTimeout(complete, 10);
			}
		}
		complete();
	}

	/**
	 * Returns true if the documents' readyState == 'complete' or the
	 * document doesn't implement readyState.
	 * Chrome only.
	 * @private
	 * @return {Boolean}
	 */
	function isDocumentComplete () {
		return !doc.readyState || doc.readyState == 'complete';
	}

	createStyle.load = function (absId, req, loaded, config) {
		// get css text
		req([absId], function (cssText) {
			// TODO: translate urls?
			createStyle(cssText, loaded, loaded.error);
		});
	};

	createStyle.translateUrls = translateUrls;

	return createStyle;
});


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:background="@color/bg_less_bright"
    android:paddingBottom="3dp"
    android:paddingLeft="@dimen/list_entry_padding_horizontal"
    android:paddingRight="@dimen/list_entry_padding_horizontal"
    android:paddingTop="3dp"
    android:textColor="@color/fg_less_significant"
    android:textSize="@dimen/font_size_small"
    android:textStyle="bold" />


text: © Redice Inc. All rights reserved. Powered by GitHub Pages.


text:
from django.conf.urls import patterns, url  # Django >1.4

from django.http import HttpResponse

from .app.models import Item

def _view(request):
    return HttpResponse('Item count: %d' % Item.objects.count())

urlpatterns = patterns(
    '',
    url(r'^item_count/$', _view)
)


text:
import RestStore from '../core/store/RestStore';

export default class RTorrentApi extends RestStore {
  constructor(){
    super('/rtorrent/api');
  }
  delete(hash){
    super.delete({
      action : 'multicall',
      call: 'd.erase',
      hash: hash
    });
  }
  loadAll(){
    super.load({
      action : 'getAll'
    });
  }
}


text:
Luau
====

Simplifies the loading and calling of Lua script in Redis. Allows you to call a script via a human-readable alias, rather than bothering with LOAD and EVALSHA in Redis.

Initialization
--------------

```
var lua = new Luau({
	password	: 'your password', // only if you have protected Redis
	folder		: './scripts', // './scripts' is the default
	redisPort	: 6379 // 6379 is the default
})
```

The following Lua script will set some key to some value, then return the set value:

```
local key = KEYS[1]
redis.call("set", key, ARGV[1])
return redis.call("get", key)
```

The file name of the script will be its command name. Let's name the above script `./scripts/setget.lua`.

To run the above script:

```
var response = lua.run('setget', 1, 'keyname', 'somevalue');
```

`response` is a `Promise` -- see below.

The argument ordering for `run` follows the argument ordering for Redis `EVALSHA`. The difference is that you replace a SHA with your custom command name (the file name).

See
* [Redis EVAL](http://redis.io/commands/eval)
* [Redis EVALSHA](http://redis.io/commands/evalsha)

Loading of the script into Redis' script cache is done automatically for you. Just call `run` -- if the script does not exist it will be lazy loaded for you (and return the result).

Promises
--------

The return value of `run` is a `Promise`. So the pattern of usage resembles the following:

```
var first 	= lua.run('setget', 1, 'first', '1st');
var second	= lua.run('setget', 1, 'second', '2nd');

first.then(function(result) { console.log(result); } // 1st
second.then(function(result) { console.log(result); } // 2nd

foo(first) // #foo has a thennable which it can use as per above.
bar(first), baz(second) // ditto for #bar and #baz
```

Luau uses the [Bluebird Promise library](https://github.com/petkaantonov/bluebird), so the `Promise` returned has access to the [Bluebird API](https://github.com/petkaantonov/bluebird/blob/master/API.md)


text:
#region Licence

#endregion

using System;

namespace WmcSoft
{
    /// <summary>
    /// Returns values from a predefined set.
    /// </summary>
    /// <remarks>This class is usefull for tests. Also, unlike Random, all methods call Sample</remarks>
    public class DeterministicRandom : RandomBase
    {
        readonly double[] _values;
        int _index;

        public DeterministicRandom(params double[] values)
        {
            _values = values;
        }

        protected override double Sample()
        {
            double result = _values[_index];
            _index = (_index + 1) % _values.Length;
            return result;
        }
    }
}


text:
using Aspose.Slides.Export;

/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Slides for .NET API reference
when the project is build. Please check https://docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Slides for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/

namespace Aspose.Slides.Examples.CSharp.Presentations
{
    public class ExtractFlashFromPresentation
    {
        public static void Run()
        {
            //ExStart:ExtractFlashFromPresentation
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_PresentationProperties();

            using (Presentation pres = new Presentation(dataDir+"withFlash.pptm"))
            {
                IControlCollection controls = pres.Slides[0].Controls;
                Control flashControl = null;
                foreach (IControl control in controls)
                {
                    if (control.Name == "ShockwaveFlash1")
                    {
                        flashControl = (Control)control;
                    }
                }
            }
            //ExEnd:ExtractFlashFromPresentation
        }
    }
}


text:
<?php

namespace Doctrine\DBAL\Driver\IBMDB2;

use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\Driver\ServerInfoAwareConnection;

class DB2Connection implements Connection, ServerInfoAwareConnection
{

    /**
     * @var resource
     */
    private $_conn = null;

    /**
     * @param array  $params
     * @param string $username
     * @param string $password
     * @param array  $driverOptions
     *
     * @throws \Doctrine\DBAL\Driver\IBMDB2\DB2Exception
     */
    public function __construct(array $params, $username, $password, $driverOptions = array())
    {

        $isPersistant = ( isset( $params['persistent'] ) && $params['persistent'] == true );

        if ($isPersistant) {
            $this->_conn = db2_pconnect($params['dbname'], $username, $password, $driverOptions);
        } else {
            $this->_conn = db2_connect($params['dbname'], $username, $password, $driverOptions);
        }
        if (!$this->_conn) {
            throw new DB2Exception(db2_conn_errormsg());
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getServerVersion()
    {

        $serverInfo = db2_server_info($this->_conn);

        return $serverInfo->DBMS_VER;
    }

    /**
     * {@inheritdoc}
     */
    public function requiresQueryForServerVersion()
    {

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function query()
    {

        $args = func_get_args();
        $sql = $args[0];
        $stmt = $this->prepare($sql);
        $stmt->execute();
        return $stmt;
    }

    /**
     * {@inheritdoc}
     */
    public function prepare($sql)
    {

        $stmt = @db2_prepare($this->_conn, $sql);
        if (!$stmt) {
            throw new DB2Exception(db2_stmt_errormsg());
        }
        return new DB2Statement($stmt);
    }

    /**
     * {@inheritdoc}
     */
    public function quote($input, $type = \PDO::PARAM_STR)
    {

        $input = db2_escape_string($input);
        if ($type == \PDO::PARAM_INT) {
            return $input;
        } else {
            return "'".$input."'";
        }
    }

    /**
     * {@inheritdoc}
     */
    public function exec($statement)
    {

        $stmt = $this->prepare($statement);
        $stmt->execute();
        return $stmt->rowCount();
    }

    /**
     * {@inheritdoc}
     */
    public function lastInsertId($name = null)
    {

        return db2_last_insert_id($this->_conn);
    }

    /**
     * {@inheritdoc}
     */
    public function beginTransaction()
    {

        db2_autocommit($this->_conn, DB2_AUTOCOMMIT_OFF);
    }

    /**
     * {@inheritdoc}
     */
    public function commit()
    {

        if (!db2_commit($this->_conn)) {
            throw new DB2Exception(db2_conn_errormsg($this->_conn));
        }
        db2_autocommit($this->_conn, DB2_AUTOCOMMIT_ON);
    }

    /**
     * {@inheritdoc}
     */
    public function rollBack()
    {

        if (!db2_rollback($this->_conn)) {
            throw new DB2Exception(db2_conn_errormsg($this->_conn));
        }
        db2_autocommit($this->_conn, DB2_AUTOCOMMIT_ON);
    }

    /**
     * {@inheritdoc}
     */
    public function errorInfo()
    {

        return array(
            0 => db2_conn_errormsg($this->_conn),
            1 => $this->errorCode(),
        );
    }

    /**
     * {@inheritdoc}
     */
    public function errorCode()
    {

        return db2_conn_error($this->_conn);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _08.Events
{
    class TestEvent : EventArgs
    {
        private string testMessage;

        public TestEvent(string text)
        {
            this.TestMessage = text;
        }

        public string TestMessage
        {
            get { return this.testMessage; }
            set { this.testMessage = value; }
        }
    }
}


text:
package dungeonBuilder.space;

/**
 *
 * @author Andrew
 */
public class CompositeSpace extends AbstractSpace implements ICompositeSpace {
    private final ISpace[] spaces;

    public CompositeSpace(ISpace... spaces) {
        super(0, 0, null, null, null);
        this.spaces = spaces;
    }

    @Override
    public ISpace[] getSpaces() {
        return spaces;
    }

    @Override
    public void move(int x, int y) {
        for(ISpace space : spaces) {
            space.move(x, y);
        }
    }
}


text:
<include file="Public/basehead"/>

<link rel="stylesheet" type="text/css" href="__STATIC__/audioplayer/css/miniplayer.css" title="style" media="screen"/>

        <?php
                                if ($type!='my'){
        ?>
        <if condition="$type eq 'icon'">
'icon'))}">图标
</if>
        <if condition="$type eq 'focus'">
'focus'))}">幻灯片
</if>
        <if condition="$type eq 'background'">
'background'))}">背景图
</if>
        <if condition="$type eq 'music'">
'music'))}">音乐
</if>
        <?php
                                }else{
        ?>

'icon'))}">图标

'focus'))}">幻灯片

'background'))}">背景图

'music'))}">音乐

        <?php
                                }
        ?>
        <li class="<if condition="$type eq 'my'">current</if> tabli" id="tab0">'my'))}">我的素材

        <?php
                                if ($type!='my'){
        ?>

 请选择类别:
<select class="form-control"  onchange="changeFolder(this.value)"><volist name="folders" id="f"><option value="{gr-$f.folder}" <if condition="$f.folder eq $folder">selected</if>>{gr-$f.name}</option></volist></select>

        <if condition="$type neq 'music'">

            <volist name="files" id="item">

            </volist>

        <else/>

                    播放
                    选择

点击歌名即可

            <volist name="files" id="item">

{gr-$item.name}	  {gr-$item.name}

            </volist>

        </if>
        <?php
                                }else{
        ?>

                    文件
                    时间
                    选择

            <volist name="list" id="item">

                <?php
                                                        $classStr="audio {skin:'blue'}";
                                                        if (strpos($item['url'],'.mp3')){
                                                        echo ''.$item['name'].'';
                                                        }else {
                                                        echo '';
                                                        }
                ?>
                	{gr-$item.time|date='Y-m-d',###}	  选中 $item['id']))}">删除

                </volist>

{gr-$page}

            <?php
                                            }
            ?>

    <include file="Public/basefooter"/>