text:
package org.wso2.siddhi.core.query.join;

import junit.framework.Assert;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.wso2.siddhi.core.ExecutionPlanRuntime;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.query.output.callback.QueryCallback;
import org.wso2.siddhi.core.stream.input.InputHandler;
import org.wso2.siddhi.core.test.util.SiddhiTestHelper;
import org.wso2.siddhi.core.util.EventPrinter;
import org.wso2.siddhi.query.api.exception.ExecutionPlanValidationException;

import java.util.concurrent.atomic.AtomicInteger;

public class JoinTestCase {
    private static final Logger log = Logger.getLogger(JoinTestCase.class);
    private AtomicInteger inEventCount;
    private AtomicInteger removeEventCount;
    private boolean eventArrived;

    @Before
    public void init() {
        inEventCount = new AtomicInteger(0);
        removeEventCount = new AtomicInteger(0);
        eventArrived = false;
    }

    @Test
    public void joinTest1() throws InterruptedException {
        log.info("Join test1");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, company string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream#window.time(1 sec) join twitterStream#window.time(1 sec) " +
                "on cseEventStream.symbol== twitterStream.company " +
                "select cseEventStream.symbol as symbol, twitterStream.tweet, cseEventStream.price " +
                "insert all events into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    if (inEvents != null) {
                        inEventCount.addAndGet(inEvents.length);
                    }
                    if (removeEvents != null) {
                        removeEventCount.addAndGet(removeEvents.length);
                    }
                    eventArrived = true;
                }
            });
            InputHandler cseEventStreamHandler = executionPlanRuntime.getInputHandler("cseEventStream");
            InputHandler twitterStreamHandler = executionPlanRuntime.getInputHandler("twitterStream");
            executionPlanRuntime.start();
            cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100});
            twitterStreamHandler.send(new Object[]{"User1", "Hello World", "WSO2"});
            cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100});
            Thread.sleep(500);
            cseEventStreamHandler.send(new Object[]{"WSO2", 57.6f, 100});

            SiddhiTestHelper.waitForEvents(100, 2, inEventCount, 6000);
            SiddhiTestHelper.waitForEvents(100, 2, removeEventCount, 6000);
            Assert.assertEquals(2, inEventCount.get());
            Assert.assertEquals(2, removeEventCount.get());
            Assert.assertTrue(eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test
    public void joinTest2() throws InterruptedException {
        log.info("Join test2");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, company string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream#window.time(1 sec) as a join twitterStream#window.time(1 sec) as b " +
                "on a.symbol== b.company " +
                "select a.symbol as symbol, b.tweet, a.price " +
                "insert all events into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    if (inEvents != null) {
                        inEventCount.addAndGet(inEvents.length);
                    }
                    if (removeEvents != null) {
                        removeEventCount.addAndGet(removeEvents.length);
                    }
                    eventArrived = true;
                }
            });

            InputHandler cseEventStreamHandler = executionPlanRuntime.getInputHandler("cseEventStream");
            InputHandler twitterStreamHandler = executionPlanRuntime.getInputHandler("twitterStream");
            executionPlanRuntime.start();
            cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100});
            twitterStreamHandler.send(new Object[]{"User1", "Hello World", "WSO2"});
            cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100});
            Thread.sleep(500);
            cseEventStreamHandler.send(new Object[]{"WSO2", 57.6f, 100});

            SiddhiTestHelper.waitForEvents(100, 2, inEventCount, 60000);
            SiddhiTestHelper.waitForEvents(100, 2, removeEventCount, 60000);
            Assert.assertEquals(2, inEventCount.get());
            Assert.assertEquals(2, removeEventCount.get());
            Assert.assertTrue(eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test
    public void joinTest3() throws InterruptedException {
        log.info("Join test3");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream#window.time(500 milliseconds) as a " +
                "join cseEventStream#window.time(500 milliseconds) as b " +
                "on a.symbol== b.symbol " +
                "select a.symbol as symbol, a.price as priceA, b.price as priceB " +
                "insert all events into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    if (inEvents != null) {
                        inEventCount.addAndGet(inEvents.length);
                    }
                    if (removeEvents != null) {
                        removeEventCount.getAndAdd(removeEvents.length);
                    }
                    eventArrived = true;
                }
            });

            InputHandler cseEventStreamHandler = executionPlanRuntime.getInputHandler("cseEventStream");
            executionPlanRuntime.start();
            cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100});
            cseEventStreamHandler.send(new Object[]{"WSO2", 57.6f, 100});

            SiddhiTestHelper.waitForEvents(100, 2, inEventCount, 60000);
            SiddhiTestHelper.waitForEvents(100, 2, removeEventCount, 60000);
            Assert.assertEquals(2, inEventCount.get());
            Assert.assertEquals(2, removeEventCount.get());
            Assert.assertTrue(eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    // TODO : Re-enable below test case, once the TimeWindowProcessor get fixed.
    // Due to a bug in TimeWindowProcessor, below test case was commented out.
    // It will be re-enabled once the bug get fixed.
    // JIRA for the TimeWindowProcessor bug (https://wso2.org/jira/browse/CEP-1413).
    // JIRA for re-enabling the test case (https://wso2.org/jira/browse/CEP-1452).
    @Ignore("Due to a bug in TimeWindowProcessor, below test case was disabled.")
    @Test
    public void joinTest4() throws InterruptedException {
        log.info("Join test4");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, company string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream#window.time(2 sec) join twitterStream#window.time(2 sec) " +
                "on cseEventStream.symbol== twitterStream.company " +
                "within 1 sec " +
                "select cseEventStream.symbol as symbol, twitterStream.tweet, cseEventStream.price " +
                "insert all events into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    if (inEvents != null) {
                        for (Event event : inEvents) {
                            org.junit.Assert.assertTrue("IBM".equals(event.getData(0)) || "WSO2".equals(event.getData(0)));
                        }
                        inEventCount.addAndGet(inEvents.length);
                    }
                    if (removeEvents != null) {
                        for (Event event : removeEvents) {
                            org.junit.Assert.assertTrue("IBM".equals(event.getData(0)) || "WSO2".equals(event.getData(0)));
                        }
                        removeEventCount.getAndAdd(removeEvents.length);
                    }
                    eventArrived = true;
                }
            });

            InputHandler cseEventStreamHandler = executionPlanRuntime.getInputHandler("cseEventStream");
            InputHandler twitterStreamHandler = executionPlanRuntime.getInputHandler("twitterStream");
            executionPlanRuntime.start();
            cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100});
            twitterStreamHandler.send(new Object[]{"User1", "Hello World", "WSO2"});
            cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100});
            Thread.sleep(1300);
            cseEventStreamHandler.send(new Object[]{"WSO2", 57.6f, 100});

            SiddhiTestHelper.waitForEvents(100, 1, inEventCount, 60000);
            SiddhiTestHelper.waitForEvents(100, 1, removeEventCount, 60000);
            Assert.assertEquals(1, inEventCount.get());
            Assert.assertEquals(1, removeEventCount.get());
            Assert.assertTrue(eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test
    public void joinTest5() throws InterruptedException {
        log.info("Join test5");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, company string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream#window.length(1) join twitterStream#window.length(1) " +
                "select cseEventStream.symbol as symbol, twitterStream.tweet, cseEventStream.price " +
                "insert all events into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    eventArrived = true;
                }
            });
            InputHandler cseEventStreamHandler = executionPlanRuntime.getInputHandler("cseEventStream");
            InputHandler twitterStreamHandler = executionPlanRuntime.getInputHandler("twitterStream");
            executionPlanRuntime.start();
            cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100});
            twitterStreamHandler.send(new Object[]{"User1", "Hello World", "WSO2"});
            cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100});
            cseEventStreamHandler.send(new Object[]{"WSO2", 57.6f, 100});
            Thread.sleep(500);
            Assert.assertTrue(eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test(expected = ExecutionPlanValidationException.class)
    public void joinTest6() throws InterruptedException {
        log.info("Join test6");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, symbol string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream join twitterStream " +
                "select symbol, twitterStream.tweet, cseEventStream.price " +
                "insert all events into outputStream ;";
        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        executionPlanRuntime.shutdown();
    }

    @Test(expected = ExecutionPlanValidationException.class)
    public void joinTest7() throws InterruptedException {
        log.info("Join test7");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, symbol string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream as a join twitterStream as b " +
                "select a.symbol, twitterStream.tweet, a.price " +
                "insert all events into outputStream ;";
        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        executionPlanRuntime.shutdown();
    }

    @Test
    public void joinTest8() throws InterruptedException {
        log.info("Join test8");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, company string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream#window.length(1) join twitterStream#window.length(1) " +
                "select cseEventStream.symbol as symbol, tweet, price " +
                "insert all events into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    eventArrived = true;
                }
            });
            InputHandler cseEventStreamHandler = executionPlanRuntime.getInputHandler("cseEventStream");
            InputHandler twitterStreamHandler = executionPlanRuntime.getInputHandler("twitterStream");
            executionPlanRuntime.start();
            cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100});
            twitterStreamHandler.send(new Object[]{"User1", "Hello World", "WSO2"});
            cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100});
            cseEventStreamHandler.send(new Object[]{"WSO2", 57.6f, 100});
            Thread.sleep(500);
            Assert.assertTrue(eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test
    public void joinTest9() throws InterruptedException {
        log.info("Join test9");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, company string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream join twitterStream " +
                "select count() as events, symbol " +
                "insert all events into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    eventArrived = true;
                }
            });
            InputHandler cseEventStreamHandler = executionPlanRuntime.getInputHandler("cseEventStream");
            InputHandler twitterStreamHandler = executionPlanRuntime.getInputHandler("twitterStream");
            executionPlanRuntime.start();
            twitterStreamHandler.send(new Object[]{"User1", "Hello World", "WSO2"});
            cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100});
            cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100});
            cseEventStreamHandler.send(new Object[]{"WSO2", 57.6f, 100});
            Thread.sleep(500);
            Assert.assertFalse(eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test
    public void joinTest10() throws InterruptedException {
        log.info("Join test10");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, company string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream join twitterStream#window.length(1) " +
                "select count() as events, symbol " +
                "insert into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    if (inEvents != null) {
                        inEventCount.getAndAdd(inEvents.length);
                    }
                    if (removeEvents != null) {
                        removeEventCount.getAndAdd(removeEvents.length);
                    }
                    eventArrived = true;
                }
            });
            InputHandler cseEventStreamHandler = executionPlanRuntime.getInputHandler("cseEventStream");
            InputHandler twitterStreamHandler = executionPlanRuntime.getInputHandler("twitterStream");
            executionPlanRuntime.start();
            cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100});
            twitterStreamHandler.send(new Object[]{"User1", "Hello World", "WSO2"});
            cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100});
            cseEventStreamHandler.send(new Object[]{"WSO2", 57.6f, 100});

            SiddhiTestHelper.waitForEvents(100, 2, inEventCount, 60000);
            Assert.assertEquals("inEventCount", 2, inEventCount.get());
            Assert.assertEquals("removeEventCount", 0, removeEventCount.get());
            Assert.assertTrue(eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test
    public void joinTest11() throws InterruptedException {
        log.info("Join test11");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, company string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream unidirectional join twitterStream#window.length(1) " +
                "select count() as events, symbol, tweet " +
                "insert all events into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    if (inEvents != null) {
                        inEventCount.getAndAdd(inEvents.length);
                    }
                    if (removeEvents != null) {
                        removeEventCount.getAndAdd(removeEvents.length);
                    }
                    eventArrived = true;
                }
            });
            InputHandler cseEventStreamHandler = executionPlanRuntime.getInputHandler("cseEventStream");
            InputHandler twitterStreamHandler = executionPlanRuntime.getInputHandler("twitterStream");
            executionPlanRuntime.start();
            cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100});
            twitterStreamHandler.send(new Object[]{"User1", "Hello World", "WSO2"});
            cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100});
            cseEventStreamHandler.send(new Object[]{"WSO2", 57.6f, 100});

            SiddhiTestHelper.waitForEvents(100, 2, inEventCount, 60000);
            SiddhiTestHelper.waitForEvents(100, 2, removeEventCount, 60000);
            Assert.assertEquals("inEventCount", 2, inEventCount.get());
            Assert.assertEquals("removeEventCount", 2, removeEventCount.get());
            Assert.assertTrue(eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test
    public void joinTest12() throws InterruptedException {
        log.info("Join test12");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, company string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream#window.time(1 sec) join twitterStream#window.time(1 sec) " +
                "on cseEventStream.symbol== twitterStream.company " +
                "select * " +
                "insert into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    if (inEvents != null) {
                        inEventCount.getAndAdd(inEvents.length);
                    }
                    if (removeEvents != null) {
                        removeEventCount.getAndAdd(removeEvents.length);
                    }
                    eventArrived = true;
                }
            });
            InputHandler cseEventStreamHandler = executionPlanRuntime.getInputHandler("cseEventStream");
            InputHandler twitterStreamHandler = executionPlanRuntime.getInputHandler("twitterStream");
            executionPlanRuntime.start();
            cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100});
            twitterStreamHandler.send(new Object[]{"User1", "Hello World", "WSO2"});

            SiddhiTestHelper.waitForEvents(100, 1, inEventCount, 60000);
            Assert.assertEquals("inEventCount", 1, inEventCount.get());
            Assert.assertEquals("removeEventCount", 0, removeEventCount.get());
            Assert.assertTrue(eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test(expected = ExecutionPlanValidationException.class)
    public void joinTest13() throws InterruptedException {
        log.info("Join test13");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream cseEventStream (symbol string, price float, volume int); " +
                "define stream twitterStream (user string, tweet string, symbol string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from cseEventStream#window.time(1 sec) join twitterStream#window.time(1 sec) " +
                "on cseEventStream.symbol== twitterStream.symbol " +
                "select * " +
                "insert into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            executionPlanRuntime.start();
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test
    public void joinTest14() throws InterruptedException {
        log.info("Join test14");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream order (billnum string, custid string, items string, dow string, timestamp long); " +
                "define table dow_items (custid string, dow string, item string) ; " +
                "define stream dow_items_stream (custid string, dow string, item string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from order join dow_items \n" +
                "on order.custid == dow_items.custid \n" +
                "select  dow_items.item\n" +
                "having order.items == \"item1\" \n" +
                "insert into recommendationStream ;" +

                "@info(name = 'query2') " +
                "from dow_items_stream " +
                "insert into dow_items ;" +
                "" +
                "";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            InputHandler orderStream = executionPlanRuntime.getInputHandler("order");
            InputHandler itemsStream = executionPlanRuntime.getInputHandler("dow_items_stream");
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    eventArrived = true;
                }
            });
            executionPlanRuntime.start();
            Thread.sleep(100);
            itemsStream.send(new Object[]{"cust1", "bill1", "item1"});
            orderStream.send(new Object[]{"bill1", "cust1", "item1", "dow1", 12323232l});
            Thread.sleep(100);
            Assert.assertEquals("Event Arrived", true, eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test
    public void joinTest15() throws InterruptedException {
        log.info("Join test15");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream order (billnum string, custid string, items string, dow string, timestamp long); " +
                "define table dow_items (custid string, dow string, item string) ; " +
                "define stream dow_items_stream (custid string, dow string, item string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from order join dow_items \n" +
                "on order.custid == dow_items.custid \n" +
                "select  dow_items.item\n" +
                "having dow_items.item == \"item1\" \n" +
                "insert into recommendationStream ;" +

                "@info(name = 'query2') " +
                "from dow_items_stream " +
                "insert into dow_items ;" +
                "" +
                "";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            InputHandler orderStream = executionPlanRuntime.getInputHandler("order");
            InputHandler itemsStream = executionPlanRuntime.getInputHandler("dow_items_stream");
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    eventArrived = true;
                }

            });
            executionPlanRuntime.start();
            Thread.sleep(100);
            itemsStream.send(new Object[]{"cust1", "bill1", "item1"});
            orderStream.send(new Object[]{"bill1", "cust1", "item1", "dow1", 12323232l});
            Thread.sleep(100);
            Assert.assertEquals("Event Arrived", true, eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test
    public void joinTest16() throws InterruptedException {
        log.info("Join test16");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream order (billnum string, custid string, items string, dow string, timestamp long); " +
                "define table dow_items (custid string, dow string, item string) ; " +
                "define stream dow_items_stream (custid string, dow string, item string); ";
        String query = "" +
                "@info(name = 'query1') " +
                "from order join dow_items \n" +
                "on order.custid == dow_items.custid \n" +
                "select  order.custid\n" +
                "having dow_items.item == \"item1\" \n" +
                "insert into recommendationStream ;" +

                "@info(name = 'query2') " +
                "from dow_items_stream " +
                "insert into dow_items ;" +
                "" +
                "";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            InputHandler orderStream = executionPlanRuntime.getInputHandler("order");
            InputHandler itemsStream = executionPlanRuntime.getInputHandler("dow_items_stream");

            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    eventArrived = true;
                }

            });
            executionPlanRuntime.start();
            Thread.sleep(100);
            itemsStream.send(new Object[]{"cust1", "bill1", "item1"});
            orderStream.send(new Object[]{"bill1", "cust1", "item1", "dow1", 12323232l});
            Thread.sleep(100);
            Assert.assertEquals("Event Arrived", true, eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }

    @Test
    public void joinTest17() throws InterruptedException {
        log.info("Join test17");

        SiddhiManager siddhiManager = new SiddhiManager();
        String streams = "" +
                "define stream order (billnum string, custid string, items string, dow string, timestamp long); " +
                "define table dow_items (custid string, dow string, item string) ; " +
                "define stream dow_items_stream (custid string, dow string, item string); ";

        String query = "" +
                "@info(name = 'query1') " +
                "from order join dow_items \n" +
                "select  dow_items.custid\n" +
                "having order.items == \"item1\" \n" +
                "insert into recommendationStream ;" +

                "@info(name = 'query2') " +
                "from dow_items_stream " +
                "insert into dow_items ;" +
                "" +
                "";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(streams + query);
        try {
            InputHandler orderStream = executionPlanRuntime.getInputHandler("order");
            InputHandler itemsStream = executionPlanRuntime.getInputHandler("dow_items_stream");
            executionPlanRuntime.addCallback("query1", new QueryCallback() {
                @Override
                public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                    EventPrinter.print(timeStamp, inEvents, removeEvents);
                    eventArrived = true;
                }
            });
            executionPlanRuntime.start();
            Thread.sleep(100);
            itemsStream.send(new Object[]{"cust1", "bill1", "item1"});
            orderStream.send(new Object[]{"bill1", "cust1", "item1", "dow1", 12323232l});
            Thread.sleep(100);
            Assert.assertEquals("Event Arrived", true, eventArrived);
        } finally {
            executionPlanRuntime.shutdown();
        }
    }
}


text:
"""Base class for ball device handlers."""
import asyncio

from mpf.core.utility_functions import Util

class BallDeviceStateHandler:

    """Base class for ball device handler."""

    __slots__ = ["ball_device", "machine", "_task"]

    def __init__(self, ball_device):
        """Initialise handler.

        Args:
        ----
            ball_device(mpf.devices.ball_device.ball_device.BallDevice): parent ball device
        """
        self.ball_device = ball_device
        self.machine = ball_device.machine
        self._task = None

    def stop(self):
        """Stop handler."""
        if self._task:
            self._task.cancel()
            try:
                self.machine.clock.loop.run_until_complete(self._task)
            except asyncio.CancelledError:
                pass

    def debug_log(self, *args, **kwargs):
        """Debug log."""
        self.ball_device.debug_log(*args, **kwargs)

    def info_log(self, *args, **kwargs):
        """Info log."""
        self.ball_device.info_log(*args, **kwargs)

    def warning_log(self, *args, **kwargs):
        """Warning log."""
        self.ball_device.warning_log(*args, **kwargs)

    async def initialise(self):
        """Initialise handler."""
        self._task = self.machine.clock.loop.create_task(self._run())
        self._task.add_done_callback(Util.raise_exceptions)

    async def _run(self):
        raise NotImplementedError()

redpajama_set_name: RedPajamaGithub


text:
typedef AudioManagerLinux AudioManagerAnyPlatform;
#elif defined(OS_MACOSX)
typedef AudioManagerMac AudioManagerAnyPlatform;
#elif defined(OS_WIN)
typedef AudioManagerWin AudioManagerAnyPlatform;
#elif defined(OS_ANDROID)
typedef AudioManagerAndroid AudioManagerAnyPlatform;
#endif

using base::win::ScopedCOMInitializer;

namespace {
// Limits the number of delay measurements we can store in an array and
// then write to file at end of the WASAPIAudioInputOutputFullDuplex test.
static const size_t kMaxDelayMeasurements = 1000;

// Name of the output text file. The output file will be stored in the
// directory containing media_unittests.exe.
// Example: \src\build\Debug\audio_delay_values_ms.txt.
// See comments for the WASAPIAudioInputOutputFullDuplex test for more details
// about the file format.
static const char* kDelayValuesFileName = "audio_delay_values_ms.txt";

// Contains delay values which are reported during the full-duplex test.
// Total delay = |buffer_delay_ms| + |input_delay_ms| + |output_delay_ms|.
struct AudioDelayState {
  AudioDelayState()
      : delta_time_ms(0),
        buffer_delay_ms(0),
        input_delay_ms(0),
        output_delay_ms(0) {
  }

  // Time in milliseconds since last delay report. Typical value is ~10 [ms].
  int delta_time_ms;

  // Size of internal sync buffer. Typical value is ~0 [ms].
  int buffer_delay_ms;

  // Reported capture/input delay. Typical value is ~10 [ms].
  int input_delay_ms;

  // Reported render/output delay. Typical value is ~40 [ms].
  int output_delay_ms;
};

// This class mocks the platform specific audio manager and overrides
// the GetMessageLoop() method to ensure that we can run our tests on
// the main thread instead of the audio thread.
class MockAudioManager : public AudioManagerAnyPlatform {
 public:
  MockAudioManager() {
    Init();
  }

  virtual ~MockAudioManager() {}

  virtual scoped_refptr<base::MessageLoopProxy> GetMessageLoop() OVERRIDE {
    return MessageLoop::current()->message_loop_proxy();
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(MockAudioManager);
};

// Test fixture class.
class AudioLowLatencyInputOutputTest : public testing::Test {
 protected:
  AudioLowLatencyInputOutputTest() {}

  virtual ~AudioLowLatencyInputOutputTest() {}

  AudioManager* audio_manager() { return &mock_audio_manager_; }
  MessageLoopForUI* message_loop() { return &message_loop_; }

  // Convenience method which ensures that we are not running on the build
  // bots and that at least one valid input and output device can be found.
  bool CanRunAudioTests() {
    bool input = audio_manager()->HasAudioInputDevices();
    bool output = audio_manager()->HasAudioOutputDevices();
    LOG_IF(WARNING, !input) << "No input device detected.";
    LOG_IF(WARNING, !output) << "No output device detected.";
    return input && output;
  }

 private:
  MessageLoopForUI message_loop_;
  MockAudioManager mock_audio_manager_;

  DISALLOW_COPY_AND_ASSIGN(AudioLowLatencyInputOutputTest);
};

}  // namespace

// This audio source/sink implementation should be used for manual tests
// only since delay measurements are stored on an output text file.
// All incoming/recorded audio packets are stored in an intermediate media
// buffer which the renderer reads from when it needs audio for playout.
// The total effect is that recorded audio is played out in loop back using
// a sync buffer as temporary storage.
class FullDuplexAudioSinkSource

    : public AudioInputStream::AudioInputCallback,
      public AudioOutputStream::AudioSourceCallback {
 public:
  FullDuplexAudioSinkSource(int sample_rate,
                            int samples_per_packet,
                            int channels)
    : sample_rate_(sample_rate),
      samples_per_packet_(samples_per_packet),
      channels_(channels),
      input_elements_to_write_(0),
      output_elements_to_write_(0),
      previous_write_time_(base::Time::Now()) {
    // Size in bytes of each audio frame (4 bytes for 16-bit stereo PCM).
    frame_size_ = (16 / 8) * channels_;

    // Start with the smallest possible buffer size. It will be increased
    // dynamically during the test if required.
    buffer_.reset(
        new media::SeekableBuffer(0, samples_per_packet_ * frame_size_));

    frames_to_ms_ = static_cast<double>(1000.0 / sample_rate_);
    delay_states_.reset(new AudioDelayState[kMaxDelayMeasurements]);
  }

  virtual ~FullDuplexAudioSinkSource() {
    // Get complete file path to output file in the directory containing
    // media_unittests.exe. Example: src/build/Debug/audio_delay_values_ms.txt.
    FilePath file_name;
    EXPECT_TRUE(PathService::Get(base::DIR_EXE, &file_name));
    file_name = file_name.AppendASCII(kDelayValuesFileName);

    FILE* text_file = file_util::OpenFile(file_name, "wt");
    DLOG_IF(ERROR, !text_file) << "Failed to open log file.";
    LOG(INFO) << ">> Output file " << file_name.value() << " has been created.";

    // Write the array which contains time-stamps, buffer size and
    // audio delays values to a text file.
    size_t elements_written = 0;
    while (elements_written <
        std::min(input_elements_to_write_, output_elements_to_write_)) {
      const AudioDelayState state = delay_states_[elements_written];
      fprintf(text_file, "%d %d %d %d\n",
              state.delta_time_ms,
              state.buffer_delay_ms,
              state.input_delay_ms,
              state.output_delay_ms);
      ++elements_written;
    }

    file_util::CloseFile(text_file);
  }

  // AudioInputStream::AudioInputCallback.
  virtual void OnData(AudioInputStream* stream,
                      const uint8* src, uint32 size,
                      uint32 hardware_delay_bytes,
                      double volume) OVERRIDE {
    base::AutoLock lock(lock_);

    // Update three components in the AudioDelayState for this recorded
    // audio packet.
    base::Time now_time = base::Time::Now();
    int diff = (now_time - previous_write_time_).InMilliseconds();
    previous_write_time_ = now_time;
    if (input_elements_to_write_ < kMaxDelayMeasurements) {
      delay_states_[input_elements_to_write_].delta_time_ms = diff;
      delay_states_[input_elements_to_write_].buffer_delay_ms =
          BytesToMilliseconds(buffer_->forward_bytes());
      delay_states_[input_elements_to_write_].input_delay_ms =
          BytesToMilliseconds(hardware_delay_bytes);
      ++input_elements_to_write_;
    }

    // Store the captured audio packet in a seekable media buffer.
    if (!buffer_->Append(src, size)) {
      // An attempt to write outside the buffer limits has been made.
      // Double the buffer capacity to ensure that we have a buffer large
      // enough to handle the current sample test scenario.
      buffer_->set_forward_capacity(2 * buffer_->forward_capacity());
      buffer_->Clear();
    }
  }

  virtual void OnClose(AudioInputStream* stream) OVERRIDE {}
  virtual void OnError(AudioInputStream* stream, int code) OVERRIDE {}

  // AudioOutputStream::AudioSourceCallback.
  virtual uint32 OnMoreData(AudioOutputStream* stream,
                            uint8* dest, uint32 max_size,
                            AudioBuffersState buffers_state) OVERRIDE {
    base::AutoLock lock(lock_);

    // Update one component in the AudioDelayState for the packet
    // which is about to be played out.
    if (output_elements_to_write_ < kMaxDelayMeasurements) {
      int output_delay_bytes = buffers_state.hardware_delay_bytes;
#if defined(OS_WIN)
      // Special fix for Windows in combination with Wave where the
      // pending bytes field of the audio buffer state is used to
      // report the delay.
      if (!media::IsWASAPISupported()) {
        output_delay_bytes = buffers_state.pending_bytes;
      }
#endif
      delay_states_[output_elements_to_write_].output_delay_ms =
          BytesToMilliseconds(output_delay_bytes);
      ++output_elements_to_write_;
    }

    // Read the data from the seekable media buffer which contains
    // captured data at the same size and sample rate as the output side.
    return buffer_->Read(dest, max_size);
  }

  virtual void OnError(AudioOutputStream* stream, int code) OVERRIDE {}
  virtual void WaitTillDataReady() OVERRIDE {}

 protected:
  // Converts from bytes to milliseconds taking the sample rate and size
  // of an audio frame into account.
  int BytesToMilliseconds(uint32 delay_bytes) const {
    return static_cast<int>((delay_bytes / frame_size_) * frames_to_ms_ + 0.5);
  }

 private:
  base::Lock lock_;
  scoped_ptr<media::SeekableBuffer> buffer_;
  int sample_rate_;
  int samples_per_packet_;
  int channels_;
  size_t frame_size_;
  double frames_to_ms_;
  scoped_array<AudioDelayState> delay_states_;
  size_t input_elements_to_write_;
  size_t output_elements_to_write_;
  base::Time previous_write_time_;
};

class AudioInputStreamTraits {
 public:
  typedef AudioInputStream StreamType;

  static int HardwareSampleRate() {
    return static_cast<int>(media::GetAudioInputHardwareSampleRate(
        AudioManagerBase::kDefaultDeviceId));
  }

  static StreamType* CreateStream(AudioManager* audio_manager,
      const AudioParameters& params) {
    return audio_manager->MakeAudioInputStream(params,
      AudioManagerBase::kDefaultDeviceId);
  }
};

class AudioOutputStreamTraits {
 public:
  typedef AudioOutputStream StreamType;

  static int HardwareSampleRate() {
    return static_cast<int>(media::GetAudioHardwareSampleRate());
  }

  static StreamType* CreateStream(AudioManager* audio_manager,
      const AudioParameters& params) {
    return audio_manager->MakeAudioOutputStream(params);
  }
};

// Traits template holding a trait of StreamType. It encapsulates
// AudioInputStream and AudioOutputStream stream types.
template <typename StreamTraits>
class StreamWrapper {
 public:
  typedef typename StreamTraits::StreamType StreamType;

  explicit StreamWrapper(AudioManager* audio_manager)
      : com_init_(ScopedCOMInitializer::kMTA),
        audio_manager_(audio_manager),
        format_(AudioParameters::AUDIO_PCM_LOW_LATENCY),
        channel_layout_(CHANNEL_LAYOUT_STEREO),
        bits_per_sample_(16) {
    // Use native/mixing sample rate and N*10ms frame size as default,
    // where N is platform dependent.
    sample_rate_ = StreamTraits::HardwareSampleRate();
#if defined(OS_MACOSX)
    // 10ms buffer size works well for 44.1, 48, 96 and 192kHz.
    samples_per_packet_ = (sample_rate_ / 100);
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
    // 10ms buffer size works well for 44.1, 48, 96 and 192kHz.
    samples_per_packet_ = (sample_rate_ / 100);
#elif defined(OS_WIN)
    if (media::IsWASAPISupported()) {
      // WASAPI is supported for Windows Vista and higher.
      if (sample_rate_ == 44100) {
        // Tests have shown that the shared mode WASAPI implementation
        // works bests for a period size of ~10.15873 ms when the sample
        // rate is 44.1kHz.
        samples_per_packet_ = 448;
      } else {
        // 10ms buffer size works well for 48, 96 and 192kHz.
        samples_per_packet_ = (sample_rate_ / 100);
      }
    } else {
      // Low-latency Wave implementation needs 30ms buffer size to
      // ensure glitch-free output audio.
      samples_per_packet_ = 3 * (sample_rate_ / 100);
    }
#endif
  }

  virtual ~StreamWrapper() {}

  // Creates an Audio[Input|Output]Stream stream object using default
  // parameters.
  StreamType* Create() {
    return CreateStream();
  }

  // Creates Audio[Input|Output]Stream object using non-default
  // parameters where the frame size is modified.
  StreamType* Create(int samples_per_packet) {
    samples_per_packet_ = samples_per_packet;
    return CreateStream();
  }

  AudioParameters::Format format() const { return format_; }
  int channels() const {
    return ChannelLayoutToChannelCount(channel_layout_);
  }
  int bits_per_sample() const { return bits_per_sample_; }
  int sample_rate() const { return sample_rate_; }
  int samples_per_packet() const { return samples_per_packet_; }

 private:
  StreamType* CreateStream() {
    StreamType* stream = StreamTraits::CreateStream(audio_manager_,
        AudioParameters(format_, channel_layout_, sample_rate_,
            bits_per_sample_, samples_per_packet_));
    EXPECT_TRUE(stream);
    return stream;
  }

  ScopedCOMInitializer com_init_;
  AudioManager* audio_manager_;
  AudioParameters::Format format_;
  ChannelLayout channel_layout_;
  int bits_per_sample_;
  int sample_rate_;
  int samples_per_packet_;
};

typedef StreamWrapper<AudioInputStreamTraits> AudioInputStreamWrapper;
typedef StreamWrapper<AudioOutputStreamTraits> AudioOutputStreamWrapper;

// This test is intended for manual tests and should only be enabled
// when it is required to make a real-time test of audio in full duplex and
// at the same time create a text file which contains measured delay values.
// The file can later be analyzed off line using e.g. MATLAB.
// MATLAB example:
//   D=load('audio_delay_values_ms.txt');
//   x=cumsum(D(:,1));
//   plot(x, D(:,2), x, D(:,3), x, D(:,4), x, D(:,2)+D(:,3)+D(:,4));
//   axis([0, max(x), 0, max(D(:,2)+D(:,3)+D(:,4))+10]);
//   legend('buffer delay','input delay','output delay','total delay');
//   xlabel('time [msec]')
//   ylabel('delay [msec]')
//   title('Full-duplex audio delay measurement');
TEST_F(AudioLowLatencyInputOutputTest, DISABLED_FullDuplexDelayMeasurement) {
  if (!CanRunAudioTests())
    return;

  AudioInputStreamWrapper aisw(audio_manager());
  AudioInputStream* ais = aisw.Create();
  EXPECT_TRUE(ais);

  AudioOutputStreamWrapper aosw(audio_manager());
  AudioOutputStream* aos = aosw.Create();
  EXPECT_TRUE(aos);

  // This test only supports identical parameters in both directions.
  // TODO(henrika): it is possible to cut delay here by using different
  // buffer sizes for input and output.
  if (aisw.sample_rate() != aosw.sample_rate() ||
      aisw.samples_per_packet() != aosw.samples_per_packet() ||
      aisw.channels()!= aosw.channels() ||
      aisw.bits_per_sample() != aosw.bits_per_sample()) {
    LOG(ERROR) << "This test requires symmetric input and output parameters. "
        "Ensure that sample rate and number of channels are identical in "
        "both directions";
    aos->Close();
    ais->Close();
    return;
  }

  EXPECT_TRUE(ais->Open());
  EXPECT_TRUE(aos->Open());

  FullDuplexAudioSinkSource full_duplex(
      aisw.sample_rate(), aisw.samples_per_packet(), aisw.channels());

  LOG(INFO) << ">> You should now be able to hear yourself in loopback...";
  DLOG(INFO) << "   sample_rate       : " << aisw.sample_rate();
  DLOG(INFO) << "   samples_per_packet: " << aisw.samples_per_packet();
  DLOG(INFO) << "   channels          : " << aisw.channels();

  ais->Start(&full_duplex);
  aos->Start(&full_duplex);

  // Wait for approximately 10 seconds. The user shall hear his own voice
  // in loop back during this time. At the same time, delay recordings are
  // performed and stored in the output text file.
  message_loop()->PostDelayedTask(FROM_HERE,
      MessageLoop::QuitClosure(), TestTimeouts::action_timeout());
  message_loop()->Run();

  aos->Stop();
  ais->Stop();

  // All Close() operations that run on the mocked audio thread,
  // should be synchronous and not post additional close tasks to
  // mocked the audio thread. Hence, there is no need to call
  // message_loop()->RunAllPending() after the Close() methods.
  aos->Close();
  ais->Close();
}


text:
import re
import sys
import pywikibot
from pywikibot import pagegenerators
import hewiktionary

"""
This bot looks for audio recordings of words in Wikicommon and ads a link
to them in the corresponding Hebrew Wiktionary page
"""
class TEMPLATE_STATE:
    BEFORE_START = 1
    START = 2
    END = 3
    NEXT_PART = 4

class HebrewWordsRecordsLinkerBot(pywikibot.CurrentPageBot):

    def treat_page(self):

        """Load the given page, do some changes, and save it."""
        s = re.compile(u'^File:He-(.+)\.ogg$').match(self.current_page.title())
        if s:
            word = s.group(1)
            site = pywikibot.Site('he','wiktionary')
            word_without_nikud  = re.sub('[\u0590-\u05c7\u05f0-\u05f4\u200f]','',word)

            wikt_page = pywikibot.Page(site,title = word_without_nikud)
            print(word)
            print(word_without_nikud)

            if wikt_page.exists():
                parts_gen = hewiktionary.split_parts(wikt_page.text)

                # the first part will always be either an empty string or a string before the first definition (like {{לשכתוב}})
                final = []
                first  = parts_gen.__next__()[0]

                if first.strip() != '':
                    final += [first]
                state = TEMPLATE_STATE.BEFORE_START
                for part in parts_gen:
                    sec_word = hewiktionary.lexeme_title_regex_grouped.search(part[0]).group(1).strip()
                    sec_word = re.sub('\u200f','',sec_word)

                    if sec_word == word:
                        final += [part[0]]
                        print("   FOUND MATCH: "+word)
                        if re.compile("{{נגן").search(part[1]):
                            print("ALREADY HAVE NAGAN")
                            return
                        lines = part[1].splitlines()
                        line_idx = 0
                        for line in lines:
                            line_idx += 1
                            final += [line+'\n']

                            if state == TEMPLATE_STATE.BEFORE_START and (re.compile(hewiktionary.template_regex).search(line) or re.compile(hewiktionary.verb_template_regex).search(line)):
                                state = TEMPLATE_STATE.START

                            elif state == TEMPLATE_STATE.START:
                                if re.search("}}",line) and not re.search("{{",line):

                                    state = TEMPLATE_STATE.END
                                    break
                        if state != TEMPLATE_STATE.END:
                            print('PROBLEM 1: seems like problems in page '+word_without_nikud)
                            return
                        mediafile_name = re.compile(u'^File:(He-.*.ogg)$').match(self.current_page.title()).group(1)
                        final += ["{{נגן|קובץ=%s|כתובית=הגיה}}\n" % mediafile_name]
                        final += ['\n'.join(lines[line_idx:])]
                    else:
                        if state == TEMPLATE_STATE.END:
                            final += ['\n']
                            state = TEMPLATE_STATE.NEXT_PART

                        final += [part[0],part[1]]

                new_page_text = ''.join(final)

                if new_page_text != wikt_page.text:
                    print('saving %s' % wikt_page.title())
                    wikt_page.text = new_page_text
                    wikt_page.save('בוט שמוסיף תבנית "נגן"')

def main(args):

    site = pywikibot.Site('commons', 'commons')
    cat = pywikibot.Category(site,'Category:Hebrew_pronunciation')
    gen = pagegenerators.CategorizedPageGenerator(cat)
    global_args  = []

    article = None

    local_args = pywikibot.handle_args(global_args)
    for arg in args:
        a = re.compile('^-article:(.+)$').match(arg)
        if a:
            article = a.group(1)
        else:
            global_args.append(arg)

    if article:
        gen = [pywikibot.Page(site, article)]
        gen = pagegenerators.PreloadingGenerator(gen)

    bot = HebrewWordsRecordsLinkerBot(generator = gen)
    bot.run()

    print('_____________________DONE____________________')

if __name__ == "__main__":
    main(sys.argv)


text:
<?php

namespace ZfcUser\Service;

use Zend\Authentication\AuthenticationService;
use Zend\Form\Form;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\Crypt\Password\Bcrypt;
use Zend\Stdlib\Hydrator;
use ZfcBase\EventManager\EventProvider;
use ZfcUser\Mapper\UserInterface as UserMapperInterface;
use ZfcUser\Options\UserServiceOptionsInterface;
use ZfcUser\Entity\UserInterface;

class User extends EventProvider implements ServiceManagerAwareInterface
{

    /**
     * @var UserMapperInterface
     */
    protected $userMapper;

    /**
     * @var AuthenticationService
     */
    protected $authService;

    /**
     * @var Form
     */
    protected $loginForm;

    /**
     * @var Form
     */
    protected $registerForm;

    /**
     * @var Form
     */
    protected $changePasswordForm;

    /**
     * @var ServiceManager
     */
    protected $serviceManager;

    /**
     * @var UserServiceOptionsInterface
     */
    protected $options;

    /**
     * @var Hydrator\ClassMethods
     */
    protected $formHydrator;

    /**
     * createFromForm
     *
     * @param array $data
     * @return \ZfcUser\Entity\UserInterface
     * @throws Exception\InvalidArgumentException
     */
    public function register(array $data)
    {
        $class = $this->getOptions()->getUserEntityClass();
        $user  = new $class;
        $form  = $this->getRegisterForm();
        $form->setHydrator($this->getFormHydrator());
        $form->bind($user);
        $form->setData($data);
        if (!$form->isValid()) {
            return false;
        }

        $user = $form->getData();
        /* @var $user \ZfcUser\Entity\UserInterface */

        $bcrypt = new Bcrypt;
        $bcrypt->setCost($this->getOptions()->getPasswordCost());
        $user->setPassword($bcrypt->create($user->getPassword()));

        if ($this->getOptions()->getEnableUsername()) {
            $user->setUsername($data['username']);
        }
        if ($this->getOptions()->getEnableDisplayName()) {
            $user->setDisplayName($data['display_name']);
        }

        // If user state is enabled, set the default state value
        if ($this->getOptions()->getEnableUserState()) {
            if ($this->getOptions()->getDefaultUserState()) {
                $user->setState($this->getOptions()->getDefaultUserState());
            }
        }
        $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user, 'form' => $form));
        $this->getUserMapper()->insert($user);
        $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $user, 'form' => $form));
        return $user;
    }

    /**
     * change the current users password
     *
     * @param array $data
     * @return boolean
     */
    public function changePassword(array $data)
    {
        $currentUser = $this->getAuthService()->getIdentity();

        $oldPass = $data['credential'];
        $newPass = $data['newCredential'];

        $bcrypt = new Bcrypt;
        $bcrypt->setCost($this->getOptions()->getPasswordCost());

        if (!$bcrypt->verify($oldPass, $currentUser->getPassword())) {
            return false;
        }

        $pass = $bcrypt->create($newPass);
        $currentUser->setPassword($pass);

        $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $currentUser));
        $this->getUserMapper()->update($currentUser);
        $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $currentUser));

        return true;
    }

    public function changeEmail(array $data)
    {
        $currentUser = $this->getAuthService()->getIdentity();

        $bcrypt = new Bcrypt;
        $bcrypt->setCost($this->getOptions()->getPasswordCost());

        if (!$bcrypt->verify($data['credential'], $currentUser->getPassword())) {
            return false;
        }

        $currentUser->setEmail($data['newIdentity']);

        $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $currentUser));
        $this->getUserMapper()->update($currentUser);
        $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $currentUser));

        return true;
    }

   /**
     * @param Form $form
     * @param array $data
     * @param UserInterface $user
     * @return UserInterface
     */
    public function edit(Form $form, array $data, UserInterface $user)
    {
        foreach ($data as $key => $value) {
            if ($key == 'contrasena') continue;

            $setter = $this->getAccessorName($key);
            if (method_exists($user, $setter)) call_user_func(array($user, $setter), $value);
        }

        $argv = array();

        $argv += array('user' => $user, 'form' => $form, 'data' => $data);
        $this->getEventManager()->trigger(__FUNCTION__, $this, $argv);
        $this->getUserMapper()->update($user);
        $this->getEventManager()->trigger(__FUNCTION__ . '.post', $this, $argv);
        return $user;
    }

    /**
     * getUserMapper
     *
     * @return UserMapperInterface
     */
    public function getUserMapper()
    {
        if (null === $this->userMapper) {
            $this->userMapper = $this->getServiceManager()->get('zfcuser_user_mapper');
        }
        return $this->userMapper;
    }

    /**
     * setUserMapper
     *
     * @param UserMapperInterface $userMapper
     * @return User
     */
    public function setUserMapper(UserMapperInterface $userMapper)
    {
        $this->userMapper = $userMapper;
        return $this;
    }

    /**
     * getAuthService
     *
     * @return AuthenticationService
     */
    public function getAuthService()
    {
        if (null === $this->authService) {
            $this->authService = $this->getServiceManager()->get('zfcuser_auth_service');
        }
        return $this->authService;
    }

    /**
     * setAuthenticationService
     *
     * @param AuthenticationService $authService
     * @return User
     */
    public function setAuthService(AuthenticationService $authService)
    {
        $this->authService = $authService;
        return $this;
    }

    /**
     * @return Form
     */
    public function getRegisterForm()
    {
        if (null === $this->registerForm) {
            $this->registerForm = $this->getServiceManager()->get('zfcuser_register_form');
        }
        return $this->registerForm;
    }

    /**
     * @param Form $registerForm
     * @return User
     */
    public function setRegisterForm(Form $registerForm)
    {
        $this->registerForm = $registerForm;
        return $this;
    }

    /**
     * @return Form
     */
    public function getChangePasswordForm()
    {
        if (null === $this->changePasswordForm) {
            $this->changePasswordForm = $this->getServiceManager()->get('zfcuser_change_password_form');
        }
        return $this->changePasswordForm;
    }

    /**
     * @param Form $changePasswordForm
     * @return User
     */
    public function setChangePasswordForm(Form $changePasswordForm)
    {
        $this->changePasswordForm = $changePasswordForm;
        return $this;
    }

    /**
     * get service options
     *
     * @return UserServiceOptionsInterface
     */
    public function getOptions()
    {
        if (!$this->options instanceof UserServiceOptionsInterface) {
            $this->setOptions($this->getServiceManager()->get('zfcuser_module_options'));
        }
        return $this->options;
    }

    /**
     * set service options
     *
     * @param UserServiceOptionsInterface $options
     */
    public function setOptions(UserServiceOptionsInterface $options)
    {
        $this->options = $options;
    }

    /**
     * Retrieve service manager instance
     *
     * @return ServiceManager
     */
    public function getServiceManager()
    {
        return $this->serviceManager;
    }

    /**
     * Set service manager instance
     *
     * @param ServiceManager $serviceManager
     * @return User
     */
    public function setServiceManager(ServiceManager $serviceManager)
    {
        $this->serviceManager = $serviceManager;
        return $this;
    }

    /**
     * Return the Form Hydrator
     *
     * @return \Zend\Stdlib\Hydrator\ClassMethods
     */
    public function getFormHydrator()
    {
        if (!$this->formHydrator instanceof Hydrator\HydratorInterface) {
            $this->setFormHydrator($this->getServiceManager()->get('zfcuser_register_form_hydrator'));
        }

        return $this->formHydrator;
    }

    /**
     * Set the Form Hydrator to use
     *
     * @param Hydrator\HydratorInterface $formHydrator
     * @return User
     */
    public function setFormHydrator(Hydrator\HydratorInterface $formHydrator)
    {
        $this->formHydrator = $formHydrator;
        return $this;
    }

    protected function getAccessorName($property, $set = true)
    {
        $parts = explode('_', $property);
        array_walk($parts, function (&$val) {
            $val = ucfirst($val);
        });
        return (($set ? 'set' : 'get') . implode('', $parts));
    }
}


text:
module.exports = (dependencies, context, nextState, handleError) => {
  nextState(context.board.moveDown())
}


text:
package org.globus.gsi.bc.test;

import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.io.StringWriter;
import java.io.ByteArrayInputStream;

import org.globus.gsi.CertUtil;
import org.globus.gsi.OpenSSLKey;
import org.globus.gsi.bc.BouncyCastleOpenSSLKey;

import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.framework.Test;

public class BouncyCastleOpenSSLKeyTest extends TestCase {

    private static final String pwd = "testpwd";

    public BouncyCastleOpenSSLKeyTest(String name) {
	super(name);
    }

    public static void main (String[] args) {
	junit.textui.TestRunner.run (suite());
    }

    public static Test suite() {
	return new TestSuite(BouncyCastleOpenSSLKeyTest.class);
    }

    private KeyPair getKeyPair() throws Exception {
        CertUtil.init();

	int bits = 512;

	KeyPairGenerator keyGen = null;
	keyGen = KeyPairGenerator.getInstance("RSA", "BC");
	keyGen.initialize(bits);

        return keyGen.genKeyPair();
    }

    public void testEncrypt() throws Exception {
        KeyPair keyPair = getKeyPair();

	OpenSSLKey key = new BouncyCastleOpenSSLKey(keyPair.getPrivate());

	assertTrue(!key.isEncrypted());

	key.encrypt(pwd);

	assertTrue(key.isEncrypted());
    }

    public void testEncryptAES() throws Exception {
        KeyPair keyPair = getKeyPair();

	OpenSSLKey key = new BouncyCastleOpenSSLKey(keyPair.getPrivate());

	assertTrue(!key.isEncrypted());

        key.setEncryptionAlgorithm("AES-128-CBC");

	key.encrypt(pwd);

	assertTrue(key.isEncrypted());

        key.writeTo(System.out);
    }

    private String toString(OpenSSLKey key) throws Exception {
        StringWriter writer = new StringWriter();
        key.writeTo(writer);
        writer.close();
        String s = writer.toString();
        System.out.println(s);
        return s;
    }

    public void testDecryptedToString() throws Exception {
        KeyPair keyPair = getKeyPair();
	OpenSSLKey inKey = new BouncyCastleOpenSSLKey(keyPair.getPrivate());
	assertTrue(!inKey.isEncrypted());

        ByteArrayInputStream in = null;
        in = new ByteArrayInputStream(toString(inKey).getBytes());
        OpenSSLKey outKey = new BouncyCastleOpenSSLKey(in);
        assertTrue(!outKey.isEncrypted());

        in = new ByteArrayInputStream(toString(outKey).getBytes());
        OpenSSLKey outKey2 = new BouncyCastleOpenSSLKey(in);
        assertTrue(!outKey2.isEncrypted());
    }

    public void testEcryptedToString() throws Exception {
        KeyPair keyPair = getKeyPair();
	OpenSSLKey inKey = new BouncyCastleOpenSSLKey(keyPair.getPrivate());
	assertTrue(!inKey.isEncrypted());
	inKey.encrypt(pwd);
	assertTrue(inKey.isEncrypted());

        ByteArrayInputStream in = null;
        in = new ByteArrayInputStream(toString(inKey).getBytes());
        OpenSSLKey outKey = new BouncyCastleOpenSSLKey(in);
        assertTrue(outKey.isEncrypted());

        in = new ByteArrayInputStream(toString(outKey).getBytes());
        OpenSSLKey outKey2 = new BouncyCastleOpenSSLKey(in);
        assertTrue(outKey2.isEncrypted());
    }

}


text:
define("dojox/gfx/move",["dojo/_base/lang","./Mover","./Moveable"],function(a){return a.getObject("dojox.gfx.move",!0)});
//# sourceMappingURL=move.js.map


text:
#pragma once

#include <functional>
#include <vector>
#include <string>

#include "CUtilJson.h"
#include "SCueSheet.h"

class CDbDiscogsElem : protected CUtilJson
{
    friend class CDbDiscogs;
public:
    CDbDiscogsElem(const std::string &data, const int disc=1, const int offset=0);
    CDbDiscogsElem(const std::string &data, const int disc, const std::vector<int> &tracklengths);
    virtual ~CDbDiscogsElem() {}

    /**
     * @brief Exchanges the content with another CDbDiscogsElem object
     * @param Another CDbDiscogsElem object
     */
    void Swap(CDbDiscogsElem &other);

    /** Return a unique release ID string
     *
     *  @return id string if Query was successful.
     */
    std::string ReleaseId() const;

    /** Get album title
     *
     *  @return    Title string (empty if title not available)
     */
    std::string AlbumTitle() const;

    /** Get album artist
     *
     *  @return    Artist string (empty if artist not available)
     */
    SCueArtists AlbumArtist() const;

    /** Get album composer
     *
     *  @return    Composer/songwriter string (empty if artist not available)
     */
    SCueArtists AlbumComposer() const;

    /** Get genre
     *
     *  @return    Genre string (empty if genre not available)
     */
    std::string Genre() const;

    /** Get release date
     *
     *  @return    Date string (empty if genre not available)
     */
    std::string Date() const;

    /** Get release country
     *
     *  @return    Countery string (empty if genre not available)
     */
    std::string Country() const;

    /**
     * @brief Get disc number
     * @return    Disc number or -1 if unknown
     */
    int DiscNumber() const;

    /**
     * @brief Get total number of discs in the release
     * @return    Number of discs or -1 if unknown
     */
    int TotalDiscs() const;

    /** Get label name
     *
     *  @return    Label string (empty if label not available)
     */
    std::string AlbumLabel() const;

    /** Get catalog number
     *
     *  @return    Catalog Number string (empty if not available)
     */
    std::string AlbumCatNo() const;

    /** Get album UPC
     *
     *  @return    UPC string (empty if UPC not available)
     */
    std::string AlbumUPC() const;

    /** Get number of tracks
     *
     *  @return    number of tracks
     *  @throw     runtime_error if CD record id is invalid
     */
    int NumberOfTracks() const;

    /** Get track title
     *
     *  Track title is intelligently obtained.
     *  Case 1. main track - track title
     *  Case 2. sub_track - parent index track title + ": " + [index#] + ". " sub_track title
     *     Exception 1. If only 1 sub_track is given under an index track, index# and sub_track
     *     title are omitted.
     *     Exception 2. If sub_track index# is found in its title (either as an Arabic or Roman number)
     *     [index#] is omitted. Note that inclusion of movement # is discouraged by Discogs.
     *  Case Unaccounted: Some submitters use heading track to provide the main title of the
     *     work and subsequent toplevel tracks for its movements. This function ignores all the heading
     *     tracks, thus only movement names will be added to the cuesheet. Discogs entry must be fixed
     *     to fix this case.
     *
     *  @param[in] Track number (1-99)
     *  @return    Title string (empty if title not available)
     *  @throw     runtime_error if track number is invalid
     */
    std::string TrackTitle(int tracknum) const;

    /** Get track artist
     *
     *  @param[in] Track number (1-99)
     *  @return    Artist string (empty if artist not available)
     *  @throw     runtime_error if track number is invalid
     */
    SCueArtists TrackArtist(int tracknum) const;

    /** Get track composer
     *
     *  @param[in] Track number (1-99)
     *  @return    Composer string (empty if artist not available)
     *  @throw     runtime_error if track number is invalid
     */
    SCueArtists TrackComposer(int tracknum) const;

    /** Get track ISRC
     *
     *  @param[in] Track number (1-99)
     *  @return    ISRC string
     *  @throw     runtime_error if track number is invalid
     */
    std::string TrackISRC(int tracknum) const;

    std::string Identifier(const std::string type) const;

private:
    int disc; // in the case of multi-disc set, indicate the disc # (zero-based)
    int track_offset; // starting track of the CD (always 0 if single disc release)
    int number_of_tracks; // number of tracks on the CD (-1 to use all tracks of the release)

    bool various_performers;    // false if album has unique set of performing artists
    bool various_composers;     // false if album has a single composer
    json_t *album_credits;      // fixed link to the release's extraartists

    /**
     * @brief Traverses tracklist array and calls Callback() for every track-type element
     * @param[in] Callback function
     *
     * Callback (lambda) function:
     * - Called on every JSON object under tracklist" with its "type_"=="track"
     * - Input arguments:
     *   track: Pointer to the current JSON "track" object
     *   parent: Pointer to the parent JSON "index track" object if track is a sub_track. Or
     *           NULL if track is not a sub_track
     *   pidx: sub_track index if parent is not NULL. Otherwise, unknown
     *   heading: Pointer to the last seen JSON "heading track" object. NULL if there has been none.
     *   hidx: track index (only counting the main tracks) w.r.t. heading. Unknonwn if heading is NULL,
     */
    void TraverseTracks_(
            std::function<bool (const json_t *track,
                                const json_t *parent, size_t pidx,
                                const json_t *heading, size_t hidx)> Callback) const;

    /**
     * @brief Find JSON object for the specified track
     * @param[in] track number counting over multiple discs
     * @param[out] if not NULL and track is found in sub_tracks listing, returns its parent index track JSON object
     * @return pointer to a track JSON object
     */
    const json_t* FindTrack_(const size_t trackno, const json_t **index=NULL, size_t *suboffset=NULL,
                             const json_t **header=NULL, size_t *headoffset=NULL) const;

    /**
     * @brief Determine track offset for multi-disc release
     *
     * This function fills track_offset & number_of_tracks member variables.
     *
     * @param[in] vector of lengths of CD tracks in seconds
     * @return false if Discogs release is invalid
     */
    bool SetDiscOffset_(const std::vector<int> &tracklengths);

    /**
     * @brief Fill number_of_tracks
     */
    void SetDiscSize_();

    /**
     * @brief return the total number of sub_tracks listed under an index track
     * @param[in] pointer to the index track JSON object
     * @return number of sub_tracks or 0 if failed
     */
    static size_t NumberOfSubTracks_(const json_t *track);

    /**
     * @brief Get title of album/track
     * @param[in] pointer to either album or track JSON object
     * @return the title of album or track
     */
    static std::string Title_(const json_t* data); // maybe release or track json_t

    /**
     * @brief Get a string of performer names associated with album or track. It excludes
     *        composer names
     * @param[in] pointer to album or track JSON object
     * @return string of performers
     */
    static SCueArtists Performer_(const json_t* data); // maybe release or track json_t

    /**
     * @brief Get a string of performer names associated with album or track. It excludes
     *        composer names
     * @param[in] pointer to album or track JSON object
     * @return composer
     */
    SCueArtists Composer_(const json_t* data) const; // maybe release or track json_t

    /**
     * @brief Analyze Artists lists to fill various_performers, various_composers, and album_credits
     */
    void AnalyzeArtists_();

    static bool IsComposer_(const json_t* artist, const json_t* extraartists,
                            const std::vector<std::string> &keywords
                            = {"Composed", "Written", "Adapted",
                               "Arranged", "Lyrics", "Music", "Songwriter",
                               "Words", "Orchestrated"});

    /**
     * @brief Get artist's Discogs ID
     * @param artist JSON object (an element of artists or extraartists arrays)
     * @return integer ID
     */
    static json_int_t ArtistId_(const json_t* artist);

    /**
     * @brief Look for the artist with the ID in the array of artists
     * @param id
     * @param artists
     * @return JSON object corresponds to the artist under search or NULL if not found
     */
    static json_t *FindArtist_(const json_int_t id, const json_t* artists);
};


text:
package http3

import (
	"bytes"
	"context"
	"crypto/tls"
	"errors"
	"io"
	"net/http"
	"time"

	"github.com/golang/mock/gomock"
	"github.com/lucas-clemente/quic-go"
	mockquic "github.com/lucas-clemente/quic-go/internal/mocks/quic"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
)

type mockClient struct {
	closed bool
}

func (m *mockClient) RoundTripOpt(req *http.Request, _ RoundTripOpt) (*http.Response, error) {
	return &http.Response{Request: req}, nil
}

func (m *mockClient) Close() error {
	m.closed = true
	return nil
}

var _ roundTripCloser = &mockClient{}

type mockBody struct {
	reader   bytes.Reader
	readErr  error
	closeErr error
	closed   bool
}

// make sure the mockBody can be used as a http.Request.Body
var _ io.ReadCloser = &mockBody{}

func (m *mockBody) Read(p []byte) (int, error) {
	if m.readErr != nil {
		return 0, m.readErr
	}
	return m.reader.Read(p)
}

func (m *mockBody) SetData(data []byte) {
	m.reader = *bytes.NewReader(data)
}

func (m *mockBody) Close() error {
	m.closed = true
	return m.closeErr
}

var _ = Describe("RoundTripper", func() {
	var (
		rt           *RoundTripper
		req1         *http.Request
		conn         *mockquic.MockEarlyConnection
		handshakeCtx context.Context // an already canceled context
	)

	BeforeEach(func() {
		rt = &RoundTripper{}
		var err error
		req1, err = http.NewRequest("GET", "https://www.example.org/file1.html", nil)
		Expect(err).ToNot(HaveOccurred())

		ctx, cancel := context.WithCancel(context.Background())
		cancel()
		handshakeCtx = ctx
	})

	Context("dialing hosts", func() {
		origDialAddr := dialAddr

		BeforeEach(func() {
			conn = mockquic.NewMockEarlyConnection(mockCtrl)
			origDialAddr = dialAddr
			dialAddr = func(context.Context, string, *tls.Config, *quic.Config) (quic.EarlyConnection, error) {
				// return an error when trying to open a stream
				// we don't want to test all the dial logic here, just that dialing happens at all
				return conn, nil
			}
		})

		AfterEach(func() {
			dialAddr = origDialAddr
		})

		It("creates new clients", func() {
			closed := make(chan struct{})
			testErr := errors.New("test err")
			req, err := http.NewRequest("GET", "https://quic.clemente.io/foobar.html", nil)
			Expect(err).ToNot(HaveOccurred())
			conn.EXPECT().OpenUniStream().AnyTimes().Return(nil, testErr)
			conn.EXPECT().HandshakeComplete().Return(handshakeCtx)
			conn.EXPECT().OpenStreamSync(context.Background()).Return(nil, testErr)
			conn.EXPECT().AcceptUniStream(gomock.Any()).DoAndReturn(func(context.Context) (quic.ReceiveStream, error) {
				<-closed
				return nil, errors.New("test done")
			}).MaxTimes(1)
			conn.EXPECT().CloseWithError(gomock.Any(), gomock.Any()).Do(func(quic.ApplicationErrorCode, string) { close(closed) })
			_, err = rt.RoundTrip(req)
			Expect(err).To(MatchError(testErr))
			Expect(rt.clients).To(HaveLen(1))
			Eventually(closed).Should(BeClosed())
		})

		It("uses the quic.Config, if provided", func() {
			config := &quic.Config{HandshakeIdleTimeout: time.Millisecond}
			var receivedConfig *quic.Config
			dialAddr = func(_ context.Context, _ string, _ *tls.Config, config *quic.Config) (quic.EarlyConnection, error) {
				receivedConfig = config
				return nil, errors.New("handshake error")
			}
			rt.QuicConfig = config
			_, err := rt.RoundTrip(req1)
			Expect(err).To(MatchError("handshake error"))
			Expect(receivedConfig.HandshakeIdleTimeout).To(Equal(config.HandshakeIdleTimeout))
		})

		It("uses the custom dialer, if provided", func() {
			var dialed bool
			dialer := func(_ context.Context, _ string, tlsCfgP *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error) {
				dialed = true
				return nil, errors.New("handshake error")
			}
			rt.Dial = dialer
			_, err := rt.RoundTrip(req1)
			Expect(err).To(MatchError("handshake error"))
			Expect(dialed).To(BeTrue())
		})

		It("reuses existing clients", func() {
			closed := make(chan struct{})
			testErr := errors.New("test err")
			conn.EXPECT().OpenUniStream().AnyTimes().Return(nil, testErr)
			conn.EXPECT().HandshakeComplete().Return(handshakeCtx).Times(2)
			conn.EXPECT().OpenStreamSync(context.Background()).Return(nil, testErr).Times(2)
			conn.EXPECT().AcceptUniStream(gomock.Any()).DoAndReturn(func(context.Context) (quic.ReceiveStream, error) {
				<-closed
				return nil, errors.New("test done")
			}).MaxTimes(1)
			conn.EXPECT().CloseWithError(gomock.Any(), gomock.Any()).Do(func(quic.ApplicationErrorCode, string) { close(closed) })
			req, err := http.NewRequest("GET", "https://quic.clemente.io/file1.html", nil)
			Expect(err).ToNot(HaveOccurred())
			_, err = rt.RoundTrip(req)
			Expect(err).To(MatchError(testErr))
			Expect(rt.clients).To(HaveLen(1))
			req2, err := http.NewRequest("GET", "https://quic.clemente.io/file2.html", nil)
			Expect(err).ToNot(HaveOccurred())
			_, err = rt.RoundTrip(req2)
			Expect(err).To(MatchError(testErr))
			Expect(rt.clients).To(HaveLen(1))
			Eventually(closed).Should(BeClosed())
		})

		It("doesn't create new clients if RoundTripOpt.OnlyCachedConn is set", func() {
			req, err := http.NewRequest("GET", "https://quic.clemente.io/foobar.html", nil)
			Expect(err).ToNot(HaveOccurred())
			_, err = rt.RoundTripOpt(req, RoundTripOpt{OnlyCachedConn: true})
			Expect(err).To(MatchError(ErrNoCachedConn))
		})
	})

	Context("validating request", func() {
		It("rejects plain HTTP requests", func() {
			req, err := http.NewRequest("GET", "http://www.example.org/", nil)
			req.Body = &mockBody{}
			Expect(err).ToNot(HaveOccurred())
			_, err = rt.RoundTrip(req)
			Expect(err).To(MatchError("http3: unsupported protocol scheme: http"))
			Expect(req.Body.(*mockBody).closed).To(BeTrue())
		})

		It("rejects requests without a URL", func() {
			req1.URL = nil
			req1.Body = &mockBody{}
			_, err := rt.RoundTrip(req1)
			Expect(err).To(MatchError("http3: nil Request.URL"))
			Expect(req1.Body.(*mockBody).closed).To(BeTrue())
		})

		It("rejects request without a URL Host", func() {
			req1.URL.Host = ""
			req1.Body = &mockBody{}
			_, err := rt.RoundTrip(req1)
			Expect(err).To(MatchError("http3: no Host in request URL"))
			Expect(req1.Body.(*mockBody).closed).To(BeTrue())
		})

		It("doesn't try to close the body if the request doesn't have one", func() {
			req1.URL = nil
			Expect(req1.Body).To(BeNil())
			_, err := rt.RoundTrip(req1)
			Expect(err).To(MatchError("http3: nil Request.URL"))
		})

		It("rejects requests without a header", func() {
			req1.Header = nil
			req1.Body = &mockBody{}
			_, err := rt.RoundTrip(req1)
			Expect(err).To(MatchError("http3: nil Request.Header"))
			Expect(req1.Body.(*mockBody).closed).To(BeTrue())
		})

		It("rejects requests with invalid header name fields", func() {
			req1.Header.Add("foobär", "value")
			_, err := rt.RoundTrip(req1)
			Expect(err).To(MatchError("http3: invalid http header field name \"foobär\""))
		})

		It("rejects requests with invalid header name values", func() {
			req1.Header.Add("foo", string([]byte{0x7}))
			_, err := rt.RoundTrip(req1)
			Expect(err.Error()).To(ContainSubstring("http3: invalid http header field value"))
		})

		It("rejects requests with an invalid request method", func() {
			req1.Method = "foobär"
			req1.Body = &mockBody{}
			_, err := rt.RoundTrip(req1)
			Expect(err).To(MatchError("http3: invalid method \"foobär\""))
			Expect(req1.Body.(*mockBody).closed).To(BeTrue())
		})
	})

	Context("closing", func() {
		It("closes", func() {
			rt.clients = make(map[string]roundTripCloser)
			cl := &mockClient{}
			rt.clients["foo.bar"] = cl
			err := rt.Close()
			Expect(err).ToNot(HaveOccurred())
			Expect(len(rt.clients)).To(BeZero())
			Expect(cl.closed).To(BeTrue())
		})

		It("closes a RoundTripper that has never been used", func() {
			Expect(len(rt.clients)).To(BeZero())
			err := rt.Close()
			Expect(err).ToNot(HaveOccurred())
			Expect(len(rt.clients)).To(BeZero())
		})
	})
})


text:
<?php

return [
    'plugin' => [
        'name' => 'Metin Editörleri',
        'description' => 'Metin Editorünüzü CMS ve diğer Kod Editörüne ekleyin'
    ],
    'settings' => [
        'label' => 'Metin Editörleri',
        'description' => 'Metin editör tercihlerini bu bölümden yapılandırabilirsiniz.'
    ],
    'widget' => [
        'label' => 'Wysiwyg',
        'name' => 'Metin Editörleri',
        'description' => 'Kullanıcının seçtiği bir metin editörü oluşturur'
    ],
    'form' => [
        'settings' => [
            'select_editor' => 'Editör seç',
            'editor_width' => 'Editör Genişliği',
            'editor_height' => 'Editör Yüksekliği',
            'toolbar_label' => 'Araç Çubuğu özelleştirme',
            'toolbar_label_lg' => 'Araç Çubuğu özelleştirme (büyük)',
            'toolbar_label_md' => 'Araç Çubuğu özelleştirme (orta)',
            'toolbar_label_sm' => 'Araç Çubuğu özelleştirme (küçük)',
            'toolbar_label_xs' => 'Araç Çubuğu özelleştirme (hareketli)',
            'toolbar_tinymce' => 'Belgeleme: http://www.tinymce.com/docs/advanced/editor-control-identifiers/#toolbarcontrols',
            'toolbar_ckeditor' => 'Belgeleme: http://docs.ckeditor.com/#!/guide/dev_toolbar',
            'toolbar_froala_lg' => 'Belgeleme: https://www.froala.com/wysiwyg-editor/docs/options#toolbarButtons',
            'toolbar_froala_md' => 'Belgeleme: https://www.froala.com/wysiwyg-editor/docs/options#toolbarButtonsMD',
            'toolbar_froala_sm' => 'Belgeleme: https://www.froala.com/wysiwyg-editor/docs/options#toolbarButtonsSM',
            'toolbar_froala_xs' => 'Belgeleme: https://www.froala.com/wysiwyg-editor/docs/options#toolbarButtonsXS'
        ],
        'page' => [
            'label' => 'Sayfa için kullanım',
            'comment' => 'Sayfa düzenleme bölümünde Metin editörü kullanın'
        ],
        'content' => [
            'label' => 'İçerik için kullanım',
            'comment' => 'İçerik düzenleme bölümünde Metin editörü kullanın'
        ],
        'partial' => [
            'label' => 'Parça metinler için kullanım',
            'comment' => 'Parça metinler için Metin editörü kullanın'
        ],
        'layout' => [
            'label' => 'Şablonlar için kullanım',
            'comment' => 'Şablon düzenleme bölümünde Metin editörü kullanın'
        ],
        'others' => [
            'label' => 'Diğer modüller için kullanım',
            'comment' => '(Sayfa, Parça metinler, Şablonlar, İçerik) dışındaki tüm eklentiler için de seçilen Metin Editörünü kullan'
        ],
        'spages' => [
            'label' => 'Sabit sayfalar için kullanım',
            'comment' => 'Sabit sayfalar modülünde gönderi editörü olarak seçilen Metin editörünü kullan'
        ],
        'blog' => [
            'label' => 'Blog için kullanım',
            'comment' => 'Blog modülünde gönderi editörü olarak seçilen Metin editörünü kullan'
        ],
        'problog' => [
            'label' => 'Radiantweb Problog için kullanım',
            'comment' => 'Radientweb Problog modülünde gönderi editörü olarak seçilen Metin editörünü kullan'
        ],
        'proevent' => [
            'label' => 'Radiantweb ProEvents için kullanım',
            'comment' => 'Radiantweb ProEvents modülünde gönderi editörü olarak seçilen Metin editörünü kullan'
        ],
        'apages' => [
            'label' => 'Autumn Sayfalar için kullanım',
            'comment' => 'Autumn Sayfalar modülünde gönderi editörü olarak seçilen Metin editörünü kullan'
        ],
        'cplus' => [
            'label' => 'Indikator Content Plus için kullanım',
            'comment' => 'Indikator Content Plus modülünde gönderi editörü olarak seçilen Metin editörünü kullan'
        ],
        'news' => [
            'label' => 'Indikator News & Newsletter için kullanım',
            'comment' => 'Indikator News & Newsletter modülünde gönderi editörü olarak seçilen Metin editörünü kullan'
        ],
        'tab' => [
            'settings' => 'Ayarlar',
            'content' => 'İçerik',
            'section' => 'Eklentiler'
        ]
    ]
];


text:
using System;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;

namespace AsyncDolls.Pipeline.Incoming
{
    public class DeadLetterMessagesWhenRetryCountIsReachedStep : IIncomingLogicalStep
    {
        private readonly IDeadLetterMessages deadLetter;

        public DeadLetterMessagesWhenRetryCountIsReachedStep(IDeadLetterMessages deadLetter)
        {
            this.deadLetter = deadLetter;
        }

        public async Task Invoke(IncomingLogicalContext context, IBusForHandler bus, Func<Task> next)
        {
            try
            {
                await next()
                    .ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                var message = context.TransportMessage;
                if (IsRetryCountReached(context))
                {
                    message.SetFailureHeaders(exception, "Max number of retries has been reached!");

                    // C# 6 can do this!
                    await deadLetter.DeadLetterAsync(message).ConfigureAwait(false);
                }
                else
                {
                    message.DeliveryCount++;
                    throw;
                }
            }
        }

        static bool IsRetryCountReached(IncomingLogicalContext context)
        {
            const int HardcodedMaxRetryOfServiceBusLibrary = 10;
            return context.TransportMessage.DeliveryCount > HardcodedMaxRetryOfServiceBusLibrary - 1;
        }
    }
}


text:
/*jslint node: true*/
"use strict";

exports.map = function (schemaName, routes) {
};

exports.selectMaps = function (callback) {
};

exports.updateOn = function () {
};


text:
<Record>
<Term>Increlex</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<Synonym>Mecasermin recombinant</Synonym>
<Synonym>Increlex</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
window.goinstant = window.goinstant || {};
window.goinstant.MapDemo = (function(){

/*jshint browser:true, node:false */

"use strict";

/**
 * @fileoverview
 * Contains the MapDemo class, which connects to platform, initializes
 * components, loads the synchronized Google map and initializes map addons.
 */

/**
 * Dependencies
 */
var goinstant = window.goinstant;
var AutoComplete = goinstant.AutoComplete;
var SendInvite = goinstant.SendInvite;
var Marker = goinstant.Marker;
var MultiplayerMap = goinstant.MultiplayerMap;
var async = window.async;
var _ = window._;
var UserColors = window.goinstant.widgets.UserColors;
var UserList = window.goinstant.widgets.UserList;
var Form = window.goinstant.widgets.Form;
var Chat = window.goinstant.widgets.Chat;

/**
 * @constructor
 */
function MapDemo(config) {
  this._room = null;
  this._multiplayerMap = null;

  this._sessionId = config.sessionId;
  this._connectUrl = config.connectUrl;
  this._token = config.token;
  this._index = config.index;

  this._mapOptions = {
    container: config.container,
    scrollEnabled: config.scrollEnabled,
    streetEnabled: config.streetEnabled,
    throttle: config.throttle || 0,
    chatEnabled: config.chatEnabled
  };
}

/**
 * Initialize
 * @public
 */
MapDemo.prototype.initialize = function(cb) {

  var tasks = [
    _.bind(this._platformConnect, this),
    _.bind(this._initializeComponents, this),
    _.bind(this._initializeMap, this)
  ];

  async.series(tasks, cb);
};

/**
 * Platform Connect
 * @private
 * @param {function} cb A callback function.
 */
MapDemo.prototype._platformConnect = function(cb) {
  var self = this;

  var options = null;

  if (this._index) {
    options = {
      sessionId: '',
      guestId: this._index
    };
  }

  var connection = new goinstant.Connection(this._connectUrl, options);

  connection.connect(this._token, function(err) {
    if (err) {
      return cb(err);
    }

    self._room = connection.room(self._sessionId);

    self._room.join(function(err) {
      if (err) {
        return cb(err);
      }

      return cb();
    });
  });
};

/**
 * Initialize Components
 * @private
 * @param {function} cb A callback function.
 */
MapDemo.prototype._initializeComponents = function(cb) {
  var self = this;

  var userColors = new UserColors({ room: self._room });
  userColors.choose(function(err) {
    if (err) {
      return cb(err);
    }

    var userList = new UserList({ room: self._room });

    var formOptions = {
      key: self._room.key('goinstant/demo/map/form'),
      el: document.getElementById('search-form'),
      room: self._room
    };

    var form = new Form(formOptions);

    var tasks = [
      _.bind(userList.initialize, userList),
      _.bind(form.initialize, form)
    ];

    if (self._mapOptions.chatEnabled) {
      var chat = new Chat({ room: self._room, position: 'left' });
      tasks.push(_.bind(chat.initialize, chat));
    }

    async.parallel(tasks, cb);
  });
};

/**
 * Initialize Map
 * @private
 */
MapDemo.prototype._initializeMap = function(cb) {
  var self = this;

  this._mapOptions.room = this._room;

  this._multiplayerMap = new MultiplayerMap(this._mapOptions);
  this._multiplayerMap.initialize(function(err, map) {
    if (err) {
      return cb(err);
    }

    // Setup marker addon
    var marker = new Marker(map, self._room);
    marker.initialize(function(err) {
      if (err) {
        return cb(err);
      }

      // Setup auto-complete addon
      var autoComplete = new AutoComplete(map, marker);
      autoComplete.initialize();
    });

    // Setup invite addon
    if (!self._index) {
      var sendInvite = new SendInvite();
      sendInvite.initialize();
    }

    return cb();
  });
};

return MapDemo;

})();


text:
/*! cpus. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
var os = require('os')

module.exports = function cpus () {
  return os.cpus()
}