text:
package org.auraframework.impl;

import org.apache.commons.lang3.StringUtils;
import org.auraframework.Aura;
import org.auraframework.def.ApplicationDef;
import org.auraframework.def.ComponentDef;
import org.auraframework.def.ControllerDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.EventDef;
import org.auraframework.def.HelperDef;
import org.auraframework.def.IncludeDef;
import org.auraframework.def.InterfaceDef;
import org.auraframework.def.LayoutsDef;
import org.auraframework.def.LibraryDef;
import org.auraframework.def.NamespaceDef;
import org.auraframework.def.ProviderDef;
import org.auraframework.def.RendererDef;
import org.auraframework.def.StyleDef;
import org.auraframework.def.TokensDef;
import org.auraframework.test.util.WebDriverTestCase;
import org.auraframework.test.util.WebDriverTestCase.ExcludeBrowsers;
import org.auraframework.test.util.WebDriverUtil.BrowserType;
import org.auraframework.util.test.annotation.ThreadHostileTest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;

import com.google.common.base.Function;

/**
 * Tests to verify that the client gets updated when we want it to get updated.
 */
@ExcludeBrowsers({ BrowserType.IPAD })
// W-2572170: exclude from IPAD for now, there are issues in autobuild
public class ClientOutOfSyncUITest extends WebDriverTestCase {

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

    @Override
    public void perBrowserSetUp() {
        super.perBrowserSetUp();
        // these tests trigger server recompilation which can take a bit of time
        auraUITestingUtil.setTimeoutInSecs(60);
    }

    private DefDescriptor<ComponentDef> setupTriggerComponent(String attrs, String body) {
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(
                ComponentDef.class,
                String.format(
                        baseComponentTag,
                        "controller='java://org.auraframework.components.test.java.controller.JavaTestController' "
                                + attrs,
                        "<button onclick='{!c.post}'>post</button>" + body));
        DefDescriptor<?> controllerDesc = Aura.getDefinitionService()
                .getDefDescriptor(cmpDesc, DefDescriptor.JAVASCRIPT_PREFIX,
                        ControllerDef.class);
        addSourceAutoCleanup(
                controllerDesc,
                "{post:function(c){var a=c.get('c.getString');a.setParams({param:'dummy'});$A.enqueueAction(a);}}");
        return cmpDesc;
    }

    private boolean isIE() {
        switch (getBrowserType()) {
        case IE7:
        case IE8:
        case IE9:
        case IE10:
        case IE11:
            return true;
        default:
            break;
        }
        return false;
    }

    /**
     * Trigger a server action and wait for the browser to begin refreshing.
     */
    private void triggerServerAction() {
        // Careful. Android doesn't like more than one statement.
        auraUITestingUtil.getRawEval("document._waitingForReload = true;");

        // This test flaps on slower environments in IE. Give it a little more time to process the javascript.
        if (isIE()) {
            waitFor(3);
        }
        auraUITestingUtil.findDomElement(By.cssSelector("button")).click();
        if (isIE()) {
            waitFor(3);
        }
        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver d) {
                Object ret = auraUITestingUtil.getRawEval("return !document._waitingForReload");
                if (ret != null && ((Boolean) ret).booleanValue()) {
                    return true;
                }
                return false;
            }
        }, "Page failed to refresh after server action triggered.");
        auraUITestingUtil.waitForDocumentReady();
        waitForAuraFrameworkReady();
    }

    public void testGetServerRenderingAfterMarkupChange() throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(ComponentDef.class,
                String.format(baseComponentTag, "", "hi"));
        String url = getUrl(cmpDesc);
        openNoAura(url);
        assertEquals("hi", getText(By.cssSelector("body")));
        updateStringSource(cmpDesc, String.format(baseComponentTag, "", "bye"));
        // Firefox caches the response so we need to manually include a nonce to effect a reload
        openNoAura(url + "?nonce=" + System.nanoTime());
        auraUITestingUtil.waitForElementText(By.cssSelector("body"), "bye", true);
    }

    @ThreadHostileTest("NamespaceDef modification affects namespace")
    public void testGetClientRenderingAfterStyleChange() throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(ComponentDef.class,
                String.format(baseComponentTag, "", "
hi
"));
        String className = cmpDesc.getNamespace() + StringUtils.capitalize(cmpDesc.getName());
        DefDescriptor<?> styleDesc = Aura.getDefinitionService().getDefDescriptor(cmpDesc, DefDescriptor.CSS_PREFIX,
                StyleDef.class);
        addSourceAutoCleanup(styleDesc, String.format(".%s {font-style:italic;}", className));
        addSourceAutoCleanup(
                Aura.getDefinitionService().getDefDescriptor(
                        String.format("%s://%s", DefDescriptor.MARKUP_PREFIX, styleDesc.getNamespace()),
                        NamespaceDef.class), "<aura:namespace/>");
        open(cmpDesc);
        assertEquals("italic",
                auraUITestingUtil.findDomElement(By.cssSelector("." + className)).getCssValue("font-style"));
        updateStringSource(styleDesc, String.format(".%s {font-style:normal;}", className));
        open(cmpDesc);
        assertEquals("normal",
                auraUITestingUtil.findDomElement(By.cssSelector("." + className)).getCssValue("font-style"));
    }

    @ThreadHostileTest("NamespaceDef modification affects namespace")
    public void testGetClientRenderingAfterTokensChange() throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(ComponentDef.class,
                String.format(baseComponentTag, "", "
hi
"));
        String className = cmpDesc.getNamespace() + StringUtils.capitalize(cmpDesc.getName());
        DefDescriptor<?> styleDesc = Aura.getDefinitionService().getDefDescriptor(cmpDesc, DefDescriptor.CSS_PREFIX,
                StyleDef.class);
        addSourceAutoCleanup(styleDesc, String.format(".%s {font-size:t(fsize);}", className));
        DefDescriptor<?> tokensDesc = Aura.getDefinitionService().getDefDescriptor(
                String.format("%s://%s:%sNamespace", DefDescriptor.MARKUP_PREFIX, cmpDesc.getNamespace(),
                        cmpDesc.getNamespace()), TokensDef.class);
        addSourceAutoCleanup(tokensDesc,
                "<aura:tokens><aura:token name='fsize' value='8px'/></aura:tokens>");
        open(cmpDesc);
        assertEquals("8px", auraUITestingUtil.findDomElement(By.cssSelector("." + className)).getCssValue("font-size"));
        updateStringSource(tokensDesc,
                "<aura:tokens><aura:token name='fsize' value='66px'/></aura:tokens>");
        open(cmpDesc);
        assertEquals("66px", auraUITestingUtil.findDomElement(By.cssSelector("." + className)).getCssValue("font-size"));
    }

    public void testGetClientRenderingAfterJsControllerChange() throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(ComponentDef.class,
                String.format(baseComponentTag, "", "
click
"));
        DefDescriptor<?> controllerDesc = Aura.getDefinitionService().getDefDescriptor(cmpDesc,
                DefDescriptor.JAVASCRIPT_PREFIX, ControllerDef.class);
        addSourceAutoCleanup(controllerDesc, "{clicked:function(){window.tempVar='inconsequential'}}");
        open(cmpDesc);
        assertNull(auraUITestingUtil.getEval("return window.tempVar;"));
        auraUITestingUtil.findDomElement(By.cssSelector("#click")).click();
        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver d) {
                return "inconsequential".equals(auraUITestingUtil.getEval("return window.tempVar;"));
            }
        });
        updateStringSource(controllerDesc, "{clicked:function(){window.tempVar='meaningful'}}");
        open(cmpDesc);
        assertNull(auraUITestingUtil.getEval("return window.tempVar;"));
        auraUITestingUtil.findDomElement(By.cssSelector("#click")).click();
        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver d) {
                return "meaningful".equals(auraUITestingUtil.getEval("return window.tempVar;"));
            }
        });
    }

    public void testGetClientRenderingAfterJsProviderChange() throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = getAuraTestingUtil().createStringSourceDescriptor(null,
                ComponentDef.class, null);
        DefDescriptor<?> providerDesc = Aura.getDefinitionService().getDefDescriptor(cmpDesc,
                DefDescriptor.JAVASCRIPT_PREFIX, ProviderDef.class);
        addSourceAutoCleanup(cmpDesc, String.format(baseComponentTag,
                String.format("render='client' provider='%s'", providerDesc.getQualifiedName()),
                "<aura:attribute name='given' type='string' default=''/>{!v.given}"));
        addSourceAutoCleanup(providerDesc, "({provide:function(){return {attributes:{'given':'silver spoon'}};}})");
        open(cmpDesc);
        assertEquals("silver spoon", getText(By.cssSelector("body")));
        updateStringSource(providerDesc, "({provide:function(){return {attributes:{'given':'golden egg'}};}})");
        open(cmpDesc);
        assertEquals("golden egg", getText(By.cssSelector("body")));
    }

    public void testGetClientRenderingAfterJsHelperChange() throws Exception {
        DefDescriptor<?> helperDesc = addSourceAutoCleanup(HelperDef.class, "({getHelp:function(){return 'simply';}})");
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(
                ComponentDef.class,
                String.format(baseComponentTag,
                        String.format("render='client' helper='%s'", helperDesc.getQualifiedName()), ""));
        open(cmpDesc);
        assertEquals("simply", auraUITestingUtil.getEval("return $A.getRoot().getDef().getHelper().getHelp();"));
        updateStringSource(helperDesc, "({getHelp:function(){return 'complicated';}})");
        open(cmpDesc);
        assertEquals("complicated", auraUITestingUtil.getEval("return $A.getRoot().getDef().getHelper().getHelp();"));
    }

    public void testGetClientRenderingAfterJsRendererChange() throws Exception {
        DefDescriptor<?> rendererDesc = addSourceAutoCleanup(RendererDef.class,
                "({render:function(){return 'default';}})");
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(ComponentDef.class,
                String.format(baseComponentTag, String.format("renderer='%s'", rendererDesc.getQualifiedName()), ""));
        open(cmpDesc);
        assertEquals("default", getText(By.cssSelector("body")));
        updateStringSource(rendererDesc, "({render:function(){return 'custom';}})");
        open(cmpDesc);
        assertEquals("custom", getText(By.cssSelector("body")));
    }

    public void testGetClientRenderingAfterEventChange() throws Exception {
        DefDescriptor<?> eventDesc = addSourceAutoCleanup(EventDef.class,
                "<aura:event type='APPLICATION'><aura:attribute name='explode' type='String' default='pow'/></aura:event>");
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(
                ComponentDef.class,
                String.format(baseComponentTag, "render='client'",
                        String.format("<aura:registerevent name='end' type='%s'/>", eventDesc.getDescriptorName())));
        open(cmpDesc);
        assertEquals("pow", auraUITestingUtil.getEval(String.format(
                "return $A.getEvt('%s').getDef().getAttributeDefs().explode['default'];",
                eventDesc.getDescriptorName())));
        updateStringSource(eventDesc,
                "<aura:event type='APPLICATION'><aura:attribute name='explode' type='String' default='kaboom'/></aura:event>");
        open(cmpDesc);
        assertEquals("kaboom", auraUITestingUtil.getEval(String.format(
                "return $A.getEvt('%s').getDef().getAttributeDefs().explode['default'];",
                eventDesc.getDescriptorName())));
    }

    public void testGetServerRenderingAfterInterfaceChange() throws Exception {
        DefDescriptor<?> interfaceDesc = addSourceAutoCleanup(
                InterfaceDef.class,
                "<aura:interface support='GA' description=''><aura:attribute name='entrance' type='String' default='grand'/></aura:interface>");
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(ComponentDef.class, String.format(baseComponentTag,
                String.format("implements='%s'", interfaceDesc.getQualifiedName()), "{!v.entrance}"));
        String url = getUrl(cmpDesc);
        openNoAura(url);
        assertEquals("grand", getText(By.cssSelector("body")));
        updateStringSource(
                interfaceDesc,
                "<aura:interface support='GA' description=''><aura:attribute name='entrance' type='String' default='secret'/></aura:interface>");
        // Firefox caches the response so we need to manually include a nonce to effect a reload
        openNoAura(url + "?nonce=" + System.nanoTime());
        auraUITestingUtil.waitForElementText(By.cssSelector("body"), "secret", true);
    }

    @ThreadHostileTest("LayoutsDef modification affects namespace")
    @ExcludeBrowsers({ BrowserType.IE10, BrowserType.IE11 })
    // known issue with IE11 and layout : W-2375142
    public void testGetClientRenderingAfterLayoutChange() throws Exception {
        DefDescriptor<ApplicationDef> appDesc = addSourceAutoCleanup(ApplicationDef.class,
                String.format(baseApplicationTag, "", "
"));
        DefDescriptor<?> layoutsDesc = Aura.getDefinitionService().getDefDescriptor(appDesc,
                DefDescriptor.MARKUP_PREFIX, LayoutsDef.class);
        addSourceAutoCleanup(
                layoutsDesc,
                "<aura:layouts default='def'><aura:layout name='def'><aura:layoutItem container='xspot'>first</aura:layoutItem></aura:layout></aura:layouts>");
        open(appDesc);
        auraUITestingUtil.waitForElementText(By.cssSelector("body"), "first", true);
        updateStringSource(
                layoutsDesc,
                "<aura:layouts default='def'><aura:layout name='def'><aura:layoutItem container='xspot'>second</aura:layoutItem></aura:layout></aura:layouts>");
        open(appDesc);
        auraUITestingUtil.waitForElementText(By.cssSelector("body"), "second", true);
    }

    public void testGetClientRenderingAfterDependencyChange() throws Exception {
        DefDescriptor<?> depDesc = addSourceAutoCleanup(ComponentDef.class,
                String.format(baseComponentTag, "", "<aura:attribute name='val' type='String' default='initial'/>"));
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(
                ComponentDef.class,
                String.format(baseComponentTag, "render='client'",
                        String.format("<aura:dependency resource='%s'/>", depDesc.getQualifiedName())));
        open(cmpDesc);
        assertEquals("initial", auraUITestingUtil.getEval(String.format(
                "return $A.componentService.newComponent('%s').get('v.val');", depDesc.getDescriptorName())));
        updateStringSource(depDesc,
                String.format(baseComponentTag, "", "<aura:attribute name='val' type='String' default='final'/>"));
        open(cmpDesc);
        assertEquals("final", auraUITestingUtil.getEval(String.format(
                "return $A.componentService.newComponent('%s').get('v.val');", depDesc.getDescriptorName())));
    }

    public void testPostAfterMarkupChange() throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = setupTriggerComponent("", "
free
");
        open(cmpDesc);
        assertEquals("free", getText(By.cssSelector("#sample")));
        updateStringSource(cmpDesc, String.format(baseComponentTag,
                "controller='java://org.auraframework.components.test.java.controller.JavaTestController'",
                "<button onclick='{!c.post}'>post</button>
deposit
"));
        triggerServerAction();
        auraUITestingUtil.waitForElementText(By.cssSelector("#sample"), "deposit", true);
    }

    @ThreadHostileTest("NamespaceDef modification affects namespace")
    public void testPostAfterStyleChange() throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = setupTriggerComponent("", "
hi
");
        String className = cmpDesc.getNamespace() + StringUtils.capitalize(cmpDesc.getName());
        DefDescriptor<?> styleDesc = Aura.getDefinitionService().getDefDescriptor(cmpDesc, DefDescriptor.CSS_PREFIX,
                StyleDef.class);
        addSourceAutoCleanup(styleDesc, String.format(".%s {font-style:italic;}", className));
        addSourceAutoCleanup(
                Aura.getDefinitionService().getDefDescriptor(
                        String.format("%s://%s", DefDescriptor.MARKUP_PREFIX, styleDesc.getNamespace()),
                        NamespaceDef.class), "<aura:namespace/>");
        open(cmpDesc);
        assertEquals("italic",
                auraUITestingUtil.findDomElement(By.cssSelector("." + className)).getCssValue("font-style"));
        updateStringSource(styleDesc, String.format(".%s {font-style:normal;}", className));
        triggerServerAction();
        auraUITestingUtil.waitForElementFunction(By.cssSelector("." + className), new Function<WebElement, Boolean>() {
            @Override
            public Boolean apply(WebElement element) {
                return "normal".equals(element.getCssValue("font-style"));
            }
        });
    }

    /**
     * A routine to do _many_ iterations of a client out of sync test.
     *
     * This test really shouldn't be run unless one of the tests is flapping. It lets you iterate a number of times to
     * force a failure.... No guarantees, but without the _waitingForReload check in the trigger function, this will
     * cause a failure in very few iterations.
     */
    @ThreadHostileTest("NamespaceDef modification affects namespace")
    public void _testPostManyAfterStyleChange() throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = setupTriggerComponent("", "
hi
");
        String className = cmpDesc.getNamespace() + StringUtils.capitalize(cmpDesc.getName());
        DefDescriptor<?> styleDesc = Aura.getDefinitionService().getDefDescriptor(cmpDesc, DefDescriptor.CSS_PREFIX,
                StyleDef.class);
        addSourceAutoCleanup(styleDesc, String.format(".%s {font-style:italic;}", className));
        addSourceAutoCleanup(
                Aura.getDefinitionService().getDefDescriptor(
                        String.format("%s://%s", DefDescriptor.MARKUP_PREFIX, styleDesc.getNamespace()),
                        NamespaceDef.class), "<aura:namespace/>");
        open(cmpDesc);
        assertEquals("italic",
                auraUITestingUtil.findDomElement(By.cssSelector("." + className)).getCssValue("font-style"));
        for (int i = 0; i < 1000; i++) {
            updateStringSource(styleDesc, String.format(".%s {font-style:normal;}", className));
            triggerServerAction();
            auraUITestingUtil.waitForElementFunction(By.cssSelector("." + className),
                    new Function<WebElement, Boolean>() {
                        @Override
                        public Boolean apply(WebElement element) {
                            return "normal".equals(element.getCssValue("font-style"));
                        }
                    });
            updateStringSource(styleDesc, String.format(".%s {font-style:italic;}", className));
            triggerServerAction();
            auraUITestingUtil.waitForElementFunction(By.cssSelector("." + className),
                    new Function<WebElement, Boolean>() {
                        @Override
                        public Boolean apply(WebElement element) {
                            return "italic".equals(element.getCssValue("font-style"));
                        }
                    });
        }
    }

    @ThreadHostileTest("NamespaceDef modification affects namespace")
    public void testPostAfterTokensChange() throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = setupTriggerComponent("", "
hi
");
        String className = cmpDesc.getNamespace() + StringUtils.capitalize(cmpDesc.getName());
        DefDescriptor<?> styleDesc = Aura.getDefinitionService().getDefDescriptor(cmpDesc, DefDescriptor.CSS_PREFIX,
                StyleDef.class);
        addSourceAutoCleanup(styleDesc, String.format(".%s {font-size:t(fsize);}", className));
        DefDescriptor<?> tokensDesc = Aura.getDefinitionService().getDefDescriptor(
                String.format("%s://%s:%sNamespace", DefDescriptor.MARKUP_PREFIX, cmpDesc.getNamespace(),
                        cmpDesc.getNamespace()), TokensDef.class);
        addSourceAutoCleanup(tokensDesc,
                "<aura:tokens><aura:token name='fsize' value='8px'/></aura:tokens>");
        open(cmpDesc);
        assertEquals("8px", auraUITestingUtil.findDomElement(By.cssSelector("." + className)).getCssValue("font-size"));
        updateStringSource(tokensDesc,
                "<aura:tokens><aura:token name='fsize' value='66px'/></aura:tokens>");
        triggerServerAction();
        auraUITestingUtil.waitForElementFunction(By.cssSelector("." + className), new Function<WebElement, Boolean>() {
            @Override
            public Boolean apply(WebElement element) {
                return "66px".equals(element.getCssValue("font-size"));
            }
        });
    }

    public void testPostAfterJsControllerChange() throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(
                ComponentDef.class,
                String.format(
                        baseComponentTag,
                        "controller='java://org.auraframework.components.test.java.controller.JavaTestController'",
                        "<button onclick='{!c.post}'>post</button>
click
"));
        DefDescriptor<?> controllerDesc = Aura.getDefinitionService()
                .getDefDescriptor(cmpDesc, DefDescriptor.JAVASCRIPT_PREFIX,
                        ControllerDef.class);
        addSourceAutoCleanup(
                controllerDesc,
                "{post:function(c){var a=c.get('c.getString');a.setParams({param:'dummy'});$A.enqueueAction(a);},clicked:function(){window.tempVar='inconsequential'}}");
        open(cmpDesc);
        assertNull(auraUITestingUtil.getEval("return window.tempVar;"));
        auraUITestingUtil.findDomElement(By.cssSelector("#click")).click();
        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver d) {
                return "inconsequential".equals(auraUITestingUtil.getEval("return window.tempVar;"));
            }
        });
        updateStringSource(
                controllerDesc,
                "{post:function(c){var a=c.get('c.getString');a.setParams({param:'dummy'});$A.enqueueAction(a);},clicked:function(){window.tempVar='meaningful'}}");
        triggerServerAction();
        // wait for page to reload by checking that our tempVar is undefined again
        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                return (Boolean) auraUITestingUtil
                        .getEval("return !window.tempVar;");
            }
        });
        auraUITestingUtil.findDomElement(By.cssSelector("#click")).click();
        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                return "meaningful".equals(auraUITestingUtil.getEval("return window.tempVar;"));
            }
        });
    }

    public void testPostAfterJsProviderChange() throws Exception {
        DefDescriptor<ComponentDef> cmpDesc = getAuraTestingUtil()
                .createStringSourceDescriptor(null, ComponentDef.class, null);
        DefDescriptor<?> providerDesc = Aura.getDefinitionService()
                .getDefDescriptor(cmpDesc, DefDescriptor.JAVASCRIPT_PREFIX,
                        ProviderDef.class);
        addSourceAutoCleanup(
                cmpDesc,
                String.format(
                        baseComponentTag,
                        String.format(
                                "controller='java://org.auraframework.components.test.java.controller.JavaTestController' provider='%s'",
                                providerDesc.getQualifiedName()),
                        "<button onclick='{!c.post}'>post</button><aura:attribute name='given' type='string' default=''/>
{!v.given}
"));
        DefDescriptor<?> controllerDesc = Aura.getDefinitionService()
                .getDefDescriptor(cmpDesc, DefDescriptor.JAVASCRIPT_PREFIX,
                        ControllerDef.class);
        addSourceAutoCleanup(
                controllerDesc,
                "{post:function(c){var a=c.get('c.getString');a.setParams({param:'dummy'});$A.enqueueAction(a);}}");
        addSourceAutoCleanup(providerDesc,
                "({provide:function(){return {attributes:{'given':'silver spoon'}};}})");
        open(cmpDesc);
        assertEquals("silver spoon", getText(By.cssSelector("#result")));
        updateStringSource(providerDesc,
                "({provide:function(){return {attributes:{'given':'golden egg'}};}})");
        triggerServerAction();
        auraUITestingUtil.waitForElementText(By.cssSelector("#result"),
                "golden egg", true);
    }

    public void testPostAfterJsHelperChange() throws Exception {
        DefDescriptor<?> helperDesc = addSourceAutoCleanup(HelperDef.class, "({getHelp:function(){return 'simply';}})");
        DefDescriptor<ComponentDef> cmpDesc = setupTriggerComponent(
                String.format("helper='%s'", helperDesc.getQualifiedName()), "");
        open(cmpDesc);
        assertEquals("simply", auraUITestingUtil.getEval("return $A.getRoot().getDef().getHelper().getHelp();"));
        updateStringSource(helperDesc, "({getHelp:function(){return 'complicated';}})");
        triggerServerAction();
        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                auraUITestingUtil.waitForDocumentReady();
                auraUITestingUtil.waitForAuraFrameworkReady(null);
                return "complicated".equals(auraUITestingUtil
                        .getEval("return window.$A && $A.getRoot() && $A.getRoot().getDef().getHelper().getHelp();"));
            }
        });
    }

    public void testPostAfterJsRendererChange() throws Exception {
        DefDescriptor<?> rendererDesc = addSourceAutoCleanup(
                RendererDef.class,
                "({render:function(){var e=document.createElement('div');e.id='target';e.appendChild(document.createTextNode('default'));var r=this.superRender();r.push(e);return r;}})");
        DefDescriptor<ComponentDef> cmpDesc = setupTriggerComponent(
                String.format("renderer='%s'", rendererDesc.getQualifiedName()), "");
        open(cmpDesc);
        assertEquals("default", getText(By.cssSelector("#target")));
        updateStringSource(
                rendererDesc,
                "({render:function(){var e=document.createElement('div');e.id='target';e.appendChild(document.createTextNode('custom'));var r=this.superRender();r.push(e);return r;}})");
        triggerServerAction();
        auraUITestingUtil.waitForElementText(By.cssSelector("#target"), "custom", true);
    }

    public void testPostAfterEventChange() throws Exception {
        final DefDescriptor<?> eventDesc = addSourceAutoCleanup(EventDef.class,
                "<aura:event type='APPLICATION'><aura:attribute name='explode' type='String' default='pow'/></aura:event>");
        DefDescriptor<ComponentDef> cmpDesc = setupTriggerComponent("",
                String.format("<aura:registerevent name='end' type='%s'/>", eventDesc.getDescriptorName()));
        open(cmpDesc);
        assertEquals("pow", auraUITestingUtil.getEval(String.format(
                "return $A.getEvt('%s').getDef().getAttributeDefs().explode['default'];",
                eventDesc.getDescriptorName())));
        updateStringSource(eventDesc,
                "<aura:event type='APPLICATION'><aura:attribute name='explode' type='String' default='kaboom'/></aura:event>");
        triggerServerAction();
        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                auraUITestingUtil.waitForDocumentReady();
                auraUITestingUtil.waitForAuraFrameworkReady(null);
                String eval = String
                        .format("return ((window.$A && $A.getEvt('%s')) && (window.$A && $A.getEvt('%s')).getDef().getAttributeDefs().explode['default']);",
                                eventDesc.getDescriptorName(), eventDesc.getDescriptorName());
                return "kaboom".equals(auraUITestingUtil.getEval(eval));
            }
        });
    }

    public void testPostAfterInterfaceChange() throws Exception {
        DefDescriptor<?> interfaceDesc = addSourceAutoCleanup(
                InterfaceDef.class,
                "<aura:interface support='GA' description=''><aura:attribute name='entrance' type='String' default='grand'/></aura:interface>");
        DefDescriptor<ComponentDef> cmpDesc = setupTriggerComponent(
                String.format("implements='%s'", interfaceDesc.getQualifiedName()),
                "
{!v.entrance}
");
        open(cmpDesc);
        assertEquals("grand", getText(By.cssSelector("#target")));
        updateStringSource(
                interfaceDesc,
                "<aura:interface support='GA' description=''><aura:attribute name='entrance' type='String' default='secret'/></aura:interface>");
        triggerServerAction();
        auraUITestingUtil.waitForElementText(By.cssSelector("#target"), "secret", true);
    }

    public void testPostAfterDependencyChange() throws Exception {
        final DefDescriptor<?> depDesc = addSourceAutoCleanup(ComponentDef.class,
                String.format(baseComponentTag, "", "<aura:attribute name='val' type='String' default='initial'/>"));
        DefDescriptor<ComponentDef> cmpDesc = setupTriggerComponent("",
                String.format("<aura:dependency resource='%s'/>", depDesc.getQualifiedName()));
        open(cmpDesc);
        assertEquals("initial", auraUITestingUtil.getEval(String.format(
                "return $A.componentService.getDef('%s').getAttributeDefs().getDef('val').getDefault();",
                depDesc.getDescriptorName())));
        updateStringSource(depDesc,
                String.format(baseComponentTag, "", "<aura:attribute name='val' type='String' default='final'/>"));
        triggerServerAction();
        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                auraUITestingUtil.waitForDocumentReady();
                auraUITestingUtil.waitForAuraFrameworkReady(null);
                return "final".equals(auraUITestingUtil.getEval(String
                        .format("return window.$A && $A.componentService.getDef('%s').getAttributeDefs().getDef('val').getDefault();",
                                depDesc.getDescriptorName())));
            }
        });
    }

    public void testGetClientRenderingAfterIncludeChange() throws Exception {
        DefDescriptor<?> helperDesc = addSourceAutoCleanup(HelperDef.class, "({})");
        DefDescriptor<?> libraryDesc = getAuraTestingUtil().createStringSourceDescriptor(null, LibraryDef.class, null);
        DefDescriptor<?> includeDesc = getAuraTestingUtil().createStringSourceDescriptor(null, IncludeDef.class,
                libraryDesc);
        addSourceAutoCleanup(includeDesc, "function(){return 'initialized'}");
        addSourceAutoCleanup(libraryDesc,
                String.format("<aura:library><aura:include name='%s'/></aura:library>", includeDesc.getName()));
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(
                ComponentDef.class,
                String.format(baseComponentTag,
                        String.format("render='client' helper='%s'", helperDesc.getQualifiedName()),
                        String.format("<aura:import library='%s' property='mylib'/>", libraryDesc.getDescriptorName())));

        open(cmpDesc);
        assertEquals("initialized", auraUITestingUtil.getEval(String.format(
                "return $A.getRoot().getDef().getHelper().mylib.%s;", includeDesc.getName())));

        updateStringSource(includeDesc, "function(){return 'updated'}");

        open(cmpDesc);
        assertEquals("updated", auraUITestingUtil.getEval(String.format(
                "return $A.getRoot().getDef().getHelper().mylib.%s;", includeDesc.getName())));
    }

    public void testGetClientRenderingAfterLibraryChange() throws Exception {
        DefDescriptor<?> helperDesc = addSourceAutoCleanup(HelperDef.class, "({})");
        DefDescriptor<?> libraryDesc = getAuraTestingUtil().createStringSourceDescriptor(null, LibraryDef.class, null);
        DefDescriptor<?> includeDesc = getAuraTestingUtil().createStringSourceDescriptor(null, IncludeDef.class,
                libraryDesc);
        addSourceAutoCleanup(includeDesc, "function(){return 'firstpick'}");
        DefDescriptor<?> includeOtherDesc = getAuraTestingUtil().createStringSourceDescriptor(null, IncludeDef.class,
                libraryDesc);
        addSourceAutoCleanup(includeOtherDesc, "function(){return 'secondpick'}");
        addSourceAutoCleanup(libraryDesc,
                String.format("<aura:library><aura:include name='%s'/></aura:library>", includeDesc.getName()));
        DefDescriptor<ComponentDef> cmpDesc = addSourceAutoCleanup(
                ComponentDef.class,
                String.format(baseComponentTag,
                        String.format("render='client' helper='%s'", helperDesc.getQualifiedName()),
                        String.format("<aura:import library='%s' property='mylib'/>", libraryDesc.getDescriptorName())));

        open(cmpDesc);
        assertEquals("firstpick", auraUITestingUtil.getEval(String.format(
                "return $A.getRoot().getDef().getHelper().mylib.%s;", includeDesc.getName())));

        updateStringSource(libraryDesc,
                String.format("<aura:library><aura:include name='%s'/></aura:library>", includeOtherDesc.getName()));

        open(cmpDesc);
        assertEquals("secondpick", auraUITestingUtil.getEval(String.format(
                "return $A.getRoot().getDef().getHelper().mylib.%s;", includeOtherDesc.getName())));
    }

    public void testPostAfterIncludeChange() throws Exception {
        DefDescriptor<?> helperDesc = addSourceAutoCleanup(HelperDef.class, "({})");
        DefDescriptor<?> libraryDesc = getAuraTestingUtil().createStringSourceDescriptor(null, LibraryDef.class, null);
        final DefDescriptor<?> includeDesc = getAuraTestingUtil().createStringSourceDescriptor(null, IncludeDef.class,
                libraryDesc);
        addSourceAutoCleanup(includeDesc, "function(){return 'initialized'}");
        addSourceAutoCleanup(libraryDesc,
                String.format("<aura:library><aura:include name='%s'/></aura:library>", includeDesc.getName()));
        DefDescriptor<ComponentDef> cmpDesc = setupTriggerComponent(
                String.format("render='client' helper='%s'", helperDesc.getQualifiedName()),
                String.format("<aura:import library='%s' property='mylib'/>", libraryDesc.getDescriptorName()));

        open(cmpDesc);
        assertEquals("initialized", auraUITestingUtil.getEval(String.format(
                "return $A.getRoot().getDef().getHelper().mylib.%s;", includeDesc.getName())));

        updateStringSource(includeDesc, "function(){return 'updated'}");

        triggerServerAction();
        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                auraUITestingUtil.waitForDocumentReady();
                auraUITestingUtil.waitForAuraFrameworkReady(null);
                return "updated".equals(auraUITestingUtil.getEval(String.format(
                        "return $A.getRoot().getDef().getHelper().mylib.%s;", includeDesc.getName())));
            }
        });
    }

    public void testPostAfterLibraryChange() throws Exception {
        DefDescriptor<?> helperDesc = addSourceAutoCleanup(HelperDef.class, "({})");
        DefDescriptor<?> libraryDesc = getAuraTestingUtil().createStringSourceDescriptor(null, LibraryDef.class, null);
        DefDescriptor<?> includeDesc = getAuraTestingUtil().createStringSourceDescriptor(null, IncludeDef.class,
                libraryDesc);
        addSourceAutoCleanup(includeDesc, "function(){return 'firstpick'}");
        final DefDescriptor<?> includeOtherDesc = getAuraTestingUtil().createStringSourceDescriptor(null,
                IncludeDef.class, libraryDesc);
        addSourceAutoCleanup(includeOtherDesc, "function(){return 'secondpick'}");
        addSourceAutoCleanup(libraryDesc,
                String.format("<aura:library><aura:include name='%s'/></aura:library>", includeDesc.getName()));
        DefDescriptor<ComponentDef> cmpDesc = setupTriggerComponent(
                String.format("render='client' helper='%s'", helperDesc.getQualifiedName()),
                String.format("<aura:import library='%s' property='mylib'/>", libraryDesc.getDescriptorName()));

        open(cmpDesc);
        assertEquals("firstpick", auraUITestingUtil.getEval(String.format(
                "return $A.getRoot().getDef().getHelper().mylib.%s;", includeDesc.getName())));

        updateStringSource(libraryDesc,
                String.format("<aura:library><aura:include name='%s'/></aura:library>", includeOtherDesc.getName()));

        triggerServerAction();
        auraUITestingUtil.waitUntil(new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver input) {
                auraUITestingUtil.waitForDocumentReady();
                auraUITestingUtil.waitForAuraFrameworkReady(null);
                return "secondpick".equals(auraUITestingUtil.getEval(String.format(
                        "return $A.getRoot().getDef().getHelper().mylib.%s;", includeOtherDesc.getName())));
            }
        });
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://aws.com/스키마"/>
        <property name="username" value="test"/>
        <property name="password" value="test"/>
    </bean>

    <beans:bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource"></beans:property>
        <beans:property name="mapperLocations" value="classpath*:com/namsoo/blueart/dao/mapper/*.xml"></beans:property>
    </beans:bean>

    <beans:bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <beans:constructor-arg index="0" ref="sqlSessionFactory"></beans:constructor-arg>
    </beans:bean>

</beans>

redpajama_set_name: RedPajamaGithub


text:
module Control.Monad.Choice (
  Choice
, fromList
, fromList'
, toList
, fromMaybe
, toMaybe
, strip
, foremost
, rest
, ambiguous
, choose
) where

import Control.Monad (liftM, ap, MonadPlus(..))
import Control.Applicative (Alternative(..))
import Data.List (nub)

data Choice a = Choice a [a] | NoChoice
  deriving (Show)

instance Functor Choice where
  fmap = liftM

instance Applicative Choice where
  pure  = return
  (<*>) = ap

instance Monad Choice where
  return = flip Choice []
  NoChoice >>= _ = NoChoice
  (Choice x xs) >>= f = fromList' m $ r ++ (xs >>= toList . f)
    where m = foremost $ f x
          r = rest $ f x

instance Alternative Choice where
  (<|>) = mplus
  empty = mzero

instance MonadPlus Choice where
  mzero = NoChoice
  NoChoice `mplus` c = c
  c `mplus` _ = c

instance Monoid (Choice a) where
  mempty = NoChoice
  mappend x y = fromList $ toList x ++ toList y

fromList :: [a] -> Choice a
fromList [] = NoChoice
fromList xs = Choice (head xs) (tail xs)

fromList' :: a -> [a] -> Choice a
fromList' x xs = fromList (x : xs)

fromMaybe :: Maybe a -> Choice a
fromMaybe Nothing = NoChoice
fromMaybe (Just x) = Choice x []

toList :: Choice a -> [a]
toList NoChoice = []
toList (Choice x xs) = x : xs

toMaybe :: Choice a -> Maybe a
toMaybe NoChoice = Nothing
toMaybe (Choice x _) = Just x

strip :: Eq a => Choice a -> Choice a
strip NoChoice = NoChoice
strip (Choice x xs) = Choice x ys
  where ys = nub $ filter (/= x) xs

foremost :: Choice a -> a
foremost NoChoice = error "foremost: NoChoice"
foremost (Choice x _) = x

rest :: Choice a -> [a]
rest NoChoice = error "rest: NoChoice"
rest (Choice _ xs) = xs

ambiguous :: Eq a => Choice a -> Bool
ambiguous NoChoice = False
ambiguous c = not $ null xs
  where Choice _ xs = strip c

choose :: b -> (Choice a -> b) -> Choice a -> b
choose n _ NoChoice = n
choose _ f x = f x


text:
id: 5900f4ca1000cf542c50ffdc
challengeType: 5
title: 'Problem 349: Langton''s ant'
forumTopicId: 302008
---

## Description

An ant moves on a regular grid of squares that are coloured either black or white.
The ant is always oriented in one of the cardinal directions (left, right, up or down) and moves from square to adjacent square according to the following rules:
- if it is on a black square, it flips the color of the square to white, rotates 90 degrees counterclockwise and moves forward one square.
- if it is on a white square, it flips the color of the square to black, rotates 90 degrees clockwise and moves forward one square.

Starting with a grid that is entirely white, how many squares are black after 1018 moves of the ant?

## Instructions

## Tests

```yml
tests:
  - text: <code>euler349()</code> should return 115384615384614940.
    testString: assert.strictEqual(euler349(), 115384615384614940);

```

## Challenge Seed

```js
function euler349() {
  // Good luck!
  return true;
}

euler349();
```

## Solution

```js
// solution required
```


text:
<?php

declare(strict_types=1);

namespace FSi\Bundle\AdminBundle\Behat\Context;

use Behat\Behat\Context\Context;
use Behat\Mink\Driver\Selenium2Driver;
use Behat\Mink\Session;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Faker\Factory;
use Faker\Generator;
use FriendsOfBehat\PageObjectExtension\Element\Element;
use FriendsOfBehat\PageObjectExtension\Page\Page;
use FriendsOfBehat\SymfonyExtension\Mink\MinkParameters;

abstract class AbstractContext implements Context
{
    private Session $session;
    private MinkParameters $minkParameters;
    private EntityManagerInterface $entityManager;
    private Generator $faker;

    public function __construct(Session $session, MinkParameters $minkParameters, EntityManagerInterface $entityManager)
    {
        $this->session = $session;
        $this->minkParameters = $minkParameters;
        $this->entityManager = $entityManager;
        $this->faker = Factory::create();
    }

    protected function getRepository($className): EntityRepository
    {
        return $this->getEntityManager()->getRepository($className);
    }

    protected function getEntityManager(): EntityManagerInterface
    {
        return $this->entityManager;
    }

    protected function getFaker(): Generator
    {
        return $this->faker;
    }

    protected function getSession(): Session
    {
        return $this->session;
    }

    /**
     * @template T of Element
     * @param class-string<T> $elementClass
     * @return T
     */
    protected function getElement(string $elementClass): Element
    {
        return new $elementClass($this->session, $this->minkParameters);
    }

    /**
     * @template T of Page
     * @param class-string<T> $pageClass
     * @return T
     */
    protected function getPage(string $pageClass): Page
    {
        return new $pageClass($this->session, $this->minkParameters);
    }

    protected function isSeleniumDriverUsed(): bool
    {
        return $this->session->getDriver() instanceof Selenium2Driver;
    }

    protected function parseScenarioValue($rawValue)
    {
        $value = trim($rawValue);
        switch ($value) {
            case 'false':
                return false;
            case 'true':
                return true;
            default:
                return $value;
        }
    }
}


text:
class AutocompletePopupModel;
class AutocompleteEditModel;
class AutocompleteEditViewMac;
@class AutocompleteMatrixTarget;
class Profile;

// Implements AutocompletePopupView using a raw NSWindow containing an
// NSTableView.
//
// TODO(rohitrao): This class is set up in a way that makes testing hard.
// Refactor and write unittests.  http://crbug.com/9977

class AutocompletePopupViewMac : public AutocompletePopupView {
 public:
  AutocompletePopupViewMac(AutocompleteEditViewMac* edit_view,
                           AutocompleteEditModel* edit_model,
                           const BubblePositioner* bubble_positioner,
                           Profile* profile,
                           NSTextField* field);
  virtual ~AutocompletePopupViewMac();

  // Implement the AutocompletePopupView interface.
  virtual bool IsOpen() const;
  virtual void InvalidateLine(size_t line) {
    // TODO(shess): Verify that there is no need to implement this.
    // This is currently used in two places in the model:
    //
    // When setting the selected line, the selected line is
    // invalidated, then the selected line is changed, then the new
    // selected line is invalidated, then PaintUpdatesNow() is called.
    // For us PaintUpdatesNow() should be sufficient.
    //
    // Same thing happens when changing the hovered line, except with
    // no call to PaintUpdatesNow().  Since this code does not
    // currently support special display of the hovered line, there's
    // nothing to do here.
    //
    // deanm indicates that this is an anti-flicker optimization,
    // which we probably cannot utilize (and may not need) so long as
    // we're using NSTableView to implement the popup contents.  We
    // may need to move away from NSTableView to implement hover,
    // though.
  }
  virtual void UpdatePopupAppearance();

  // This is only called by model in SetSelectedLine() after updating
  // everything.  Popup should already be visible.
  virtual void PaintUpdatesNow();

  // Returns the popup's model.
  virtual AutocompletePopupModel* GetModel();

  // Called when the user clicks an item.  Opens the hovered item and
  // potentially dismisses the popup without formally selecting anything in the
  // model.
  void OnClick();

  // Called when the user middle-clicks an item.  Opens the hovered
  // item in a background tab.
  void OnMiddleClick();

  // Return the text to show for the match, based on the match's
  // contents and description.  Result will be in |font|, with the
  // boldfaced version used for matches.
  static NSAttributedString* MatchText(const AutocompleteMatch& match,
                                gfx::Font& font,
                                float cellWidth);

  // Helper for MatchText() to allow sharing code between the contents
  // and description cases.  Returns NSMutableAttributedString as a
  // convenience for MatchText().
  static NSMutableAttributedString* DecorateMatchedString(
      const std::wstring &matchString,
      const AutocompleteMatch::ACMatchClassifications &classifications,
      NSColor* textColor, gfx::Font& font);

  // Helper for MatchText() to elide a marked-up string using
  // gfx::ElideText() as a model.  Modifies |aString| in place.
  // TODO(shess): Consider breaking AutocompleteButtonCell out of this
  // code, and modifying it to have something like -setMatch:, so that
  // these convolutions to expose internals for testing can be
  // cleaner.
  static NSMutableAttributedString* ElideString(
      NSMutableAttributedString* aString,
      const std::wstring originalString,
      const gfx::Font& font,
      const float cellWidth);

 private:
  // Create the popup_ instance if needed.
  void CreatePopupIfNeeded();

  // Opens the URL corresponding to the given |row|.  If |force_background| is
  // true, forces the URL to open in a background tab.  Otherwise, determines
  // the proper window open disposition from the modifier flags on |[NSApp
  // currentEvent]|.
  void OpenURLForRow(int row, bool force_background);

  scoped_ptr<AutocompletePopupModel> model_;
  AutocompleteEditViewMac* edit_view_;
  const BubblePositioner* bubble_positioner_;  // owned by toolbar controller
  NSTextField* field_;  // owned by tab controller

  scoped_nsobject<AutocompleteMatrixTarget> matrix_target_;
  // TODO(shess): Before checkin review implementation to make sure
  // that popup_'s object hierarchy doesn't keep references to
  // destructed objects.
  scoped_nsobject<NSWindow> popup_;

  DISALLOW_COPY_AND_ASSIGN(AutocompletePopupViewMac);
};

#endif  // CHROME_BROWSER_AUTOCOMPLETE_AUTOCOMPLETE_POPUP_VIEW_MAC_H_


text:
console.log("saveToLocalStorage.js");

const saveToLocalStorage = (store) => {
  localStorage.setItem('ASAPStore', JSON.stringify(store));
};

const loadFromLocalStorage = () => {
  AJSON.parse(localStorage.getItem('ASAPStore'));
  console.log(
};

export { saveToLocalStorage, loadFromLocalStorage };


text:
class PSD
  class EngineData
    # Sanitizes and helps with access to the document text.
    class Text
      # The current document split by newlines into an array.
      attr_reader   :text

      # The current line number in the document.
      attr_accessor :line

      # Stores the document as a newline-split array and initializes
      # the current line to 0.
      def initialize(text)
        @text = text.split("\n")
        @line = 0
      end

      # Returns the current line stripped of any tabs and padding.
      def current
        return nil if at_end?
        @text[@line].gsub(/\t/, "").strip
      end

      # Are we at the end of the document?
      def at_end?
        @text[@line].nil?
      end

      # Moves the line pointer to the next line and returns it.
      def next!
        @line += 1
        current
      end

      # Peeks at the next line in the document without moving the
      # line pointer.
      def next
        @text[@line + 1]
      end

      # Returns the number of lines in the document.
      def length
        @text.length
      end
      alias :size :length
    end
  end
end


text:
#include <QApplication>

#include "imageviewer-qt4.h"

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);
  ImageViewer imageViewer;
  imageViewer.show();
  return app.exec();
}


text:
package org.apache.beam.sdk.io.gcp.bigquery;

import java.util.Map;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.extensions.gcp.options.GcpOptions;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TableRowParser;
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.TypedRead.Method;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.ExperimentalOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.Validation;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.testing.TestPipelineOptions;
import org.apache.beam.sdk.transforms.Count;
import org.apache.beam.sdk.transforms.SerializableFunction;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Integration tests for {@link BigQueryIO#read(SerializableFunction)} using {@link
 * Method#DIRECT_READ}. This test reads from a pre-defined table and asserts that the number of
 * records read is equal to the expected count.
 */
@RunWith(JUnit4.class)
public class BigQueryIOStorageReadIT {

  private static final Map<String, Long> EXPECTED_NUM_RECORDS =
      ImmutableMap.<String, Long>of(
          "empty", 0L,
          "1M", 10592L,
          "1G", 11110839L,
          "1T", 11110839000L);

  private static final String DATASET_ID = "big_query_storage";
  private static final String TABLE_PREFIX = "storage_read_";

  private BigQueryIOStorageReadOptions options;

  /** Customized {@link TestPipelineOptions} for BigQueryIOStorageRead pipelines. */
  public interface BigQueryIOStorageReadOptions extends TestPipelineOptions, ExperimentalOptions {
    @Description("The table to be read")
    @Validation.Required
    String getInputTable();

    void setInputTable(String table);

    @Description("The expected number of records")
    @Validation.Required
    long getNumRecords();

    void setNumRecords(long numRecords);
  }

  private void setUpTestEnvironment(String tableSize) {
    PipelineOptionsFactory.register(BigQueryIOStorageReadOptions.class);
    options = TestPipeline.testingPipelineOptions().as(BigQueryIOStorageReadOptions.class);
    options.setNumRecords(EXPECTED_NUM_RECORDS.get(tableSize));
    String project = TestPipeline.testingPipelineOptions().as(GcpOptions.class).getProject();
    options.setInputTable(project + ":" + DATASET_ID + "." + TABLE_PREFIX + tableSize);
  }

  private void runBigQueryIOStorageReadPipeline() {
    Pipeline p = Pipeline.create(options);
    PCollection<Long> count =
        p.apply(
                "Read",
                BigQueryIO.read(TableRowParser.INSTANCE)
                    .from(options.getInputTable())
                    .withMethod(Method.DIRECT_READ))
            .apply("Count", Count.globally());
    PAssert.thatSingleton(count).isEqualTo(options.getNumRecords());
    p.run().waitUntilFinish();
  }

  @Test
  public void testBigQueryStorageRead1G() throws Exception {
    setUpTestEnvironment("1G");
    runBigQueryIOStorageReadPipeline();
  }
}


text:
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.views.generic.base import View  # view类
from django.contrib.auth.hashers import make_password   # 密码加密模块

from .models import UserProfile, EmailVerifyRecord
from .forms import LoginForm, RegisterForm, ForgetForm, ModifyPwdForm
from utils.email_send import send_register_email
# Create your views here.

class CustomBackend(ModelBackend):  # 自定义登陆方式 继承ModelBackend 把这个类配到settings里才会生效
    def authenticate(self, username=None, password=None, **kwargs):     # 重写authenticate
        try:
            #
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

# 用类做为view Django常用   用法 LoginView.as_view()
class LoginView(View):
    def get(self,request):
        return render(request, 'login.html', {})

    def post(self, request):
        login_form = LoginForm(request.POST)    # 校验表单字段 标准是LoginForm这个类 属性一一对应进行校验
        if login_form.is_valid():   # 如果校验通过
            user_name = request.POST.get('username', '')  # 获取用户名
            pass_word = request.POST.get('password', '')  # 获取密码
            # 到表里查找用户密码 有数据返回UserProfile类 没查到返回None
            # authenticate方法默认验证用户名密码 可重写该方法进行自定义 比如用邮箱和密码登陆
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                if user.is_active:
                    login(request, user)  # 登陆  login是django提供的登陆方法  user信息会放到request里 传到页面
                    return render(request, 'index.html')
                else:
                    return render(request, 'login.html', {'msg': '用户未激活', 'username': user_name})
            else:
                return render(request, 'login.html', {'msg': '用户名或密码错误'})
        else:
            return render(request, 'login.html', {'login_form': login_form})

# 函数做为view 可以用Django自带的view类替代
# def user_login(request):    # 登陆功能的view
#     if request.method == 'POST':    # 表单提交了 接收用户登陆信息 并验证
#         user_name = request.POST.get('username', '')    # 获取用户名
#         pass_word = request.POST.get('password', '')    # 获取密码
#         # 到表里查找用户密码 有数据返回UserProfile类 没查到返回None
#         # authenticate方法默认验证用户名密码 可重写该方法进行自定义 比如用邮箱和密码登陆
#         user = authenticate(username=user_name, password=pass_word)
#         if user is not None:
#             login(request, user)    # 登陆  login是django提供的登陆方法  user信息会放到request里 传到页面
#             return render(request, 'index.html')
#         else:
#             return render(request, 'login.html', {'msg': '用户名或密码错误'})
#     elif request.method == 'GET':   # 跳转到登陆页面
#         return render(request, 'login.html', {})

class RegisterView(View):
    def get(self, request):
        register_form = RegisterForm()  # 实例化form
        return render(request, 'register.html', {'register_form': register_form})   # 将form对象传送到前端 这个对象里有验证码图片 需要在前端输出register_form.captcha

    def post(self, request):
        register_form = RegisterForm(request.POST)  # 校验
        if register_form.is_valid():    # 如果校验通过
            user_name = request.POST.get('email', '')  # 获取用户名
            if UserProfile.objects.filter(username=user_name):
                return render(request, 'register.html', {'register_form': register_form, 'msg': '用户名已被注册'})
            pass_word = request.POST.get('password', '')  # 获取密码
            user_profile = UserProfile()
            user_profile.username = user_name
            user_profile.email = user_name
            user_profile.password = make_password(pass_word)    # 对密码进行加密存储
            user_profile.is_active = False
            user_profile.save()     # 保存到数据库

            send_register_email(user_name, 'register')
            return render(request, 'login.html', {})
        else:
            return render(request, 'register.html', {'register_form': register_form})

class ActiveView(View):
    def get(self, request, active_code):
        email_table = EmailVerifyRecord.objects.filter(code=active_code)    # filter返回的是一个类的集合
        if email_table:
            for each in email_table:
                user_table = UserProfile.objects.get(username=each.email)   # get返回一个类 如果查询到多个结果会报错
                if user_table:
                    user_table.is_active = True     # 修改为True 表示激活成功
                    user_table.save()
                else:
                    return render(request, 'register.html')
        else:
            return render(request, 'register.html', {'msg': '激活链接失效'})
        return render(request, 'login.html')

class ForgetView(View):
    def get(self, request):
        forget_form = ForgetForm()  # 实例化form
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})   # 将form对象传送到前端 这个对象里有验证码图片 需要在前端输出register_form.captcha

    def post(self, request):
        forget_form = ForgetForm(request.POST)  # 校验
        if forget_form.is_valid():    # 如果校验通过
            user_name = request.POST.get('email', '')  # 获取用户名
            if not UserProfile.objects.filter(username=user_name):
                return render(request, 'forgetpwd.html', {'forget_form': forget_form, 'msg': '用户名不存在'})
            send_register_email(user_name, 'forget')
            return render(request, 'forgetpwd.html', {'forget_form': forget_form, 'msg': '重置链接发送成功'})
        else:
            return render(request, 'forgetpwd.html', {'forget_form': forget_form})

class ResetView(View):
    def get(self, request, active_code):
        email_table = EmailVerifyRecord.objects.filter(code=active_code)    # filter返回的是一个类的集合
        if email_table:
            for each in email_table:
                user_table = UserProfile.objects.get(username=each.email)   # get返回一个类 如果查询到多个结果会报错
                if user_table:
                    return render(request, 'password_reset.html', {'email': each.email})
                else:
                    return render(request, 'forgetpwd.html', {'msg': '重置密码链接失效'})
        else:
            return render(request, 'forgetpwd.html', {'msg': '重置密码链接失效'})

class ModifyPwdView(View):
    def post(self, request):
        modify_form = ModifyPwdForm(request.POST)
        email = request.POST.get('email', '')
        if modify_form.is_valid():
            pwd = request.POST.get('password', '')
            pwd1 = request.POST.get('password1', '')
            if pwd != pwd1:
                return render(request, 'password_reset.html', {'msg': '两次输入的密码不一致', 'email': email})
            else:
                user = UserProfile.objects.get(email=email)
                password = make_password(pwd)
                user.password = password
                user.save()
                return render(request, 'login.html')
        else:
            return render(request, 'password_reset.html', {'modify_form': modify_form,  'email': email})


text:
package main

import (
	"github.com/ardielle/ardielle-go/rdl"
	"testing"
	"io/ioutil"
	"os"
	"encoding/json"
)

func TestParseRegex(test *testing.T) {
	data, err := ioutil.ReadFile("../../testdata/rdl.json")
	if err != nil {
		test.Error("can not read sample file ")
		os.Exit(1)
	}
	var schema rdl.Schema
	err = json.Unmarshal(data, &schema)
	if err != nil {
		test.Error("unmarshal sample data fail")
		os.Exit(1)
	}
	pathInfos := extractPathInfo(&schema, "/api")
	pathInfoJson, err := json.Marshal(pathInfos)
	if err != nil {
		test.Errorf("marshal json error: %v", err)
		os.Exit(1)
	}
	expectedPathInfoJson, err := ioutil.ReadFile("../../testdata/expectedRdlPathInfo.json")
	if err != nil {
		test.Error("read expected data fail")
		os.Exit(1)
	}
	if string(pathInfoJson) != string(expectedPathInfoJson) {
		test.Error("result not as expected")
		os.Exit(1)
	}
}

func TestPathRegexGenerator(test *testing.T) {
	type pathInfos struct {
		method string
		path string
	}
	uriPaths := []pathInfos {
		{"POST", "/passcodes"},
		{"GET", "/passcodes"},
		{"GET", "/passcodes/{id}"},
		{"GET", "/passcodes/{id}/bbb/{id2}"},
		{"GET", "/transactions?offset={offset}&count={count}"},
	}
	expectedPathRegex := []string {
		`/passcodes/?$`,
		`/passcodes(/?\?|/?$)`,
		`/passcodes/[^/]+(/?\?|/?$)`,
		`/passcodes/[^/]+/bbb/[^/]+(/?\?|/?$)`,
		`/transactions(/?\?|/?$)`,
	}
	for idx, pathInfo := range uriPaths {
		if pathRegex := genUriRegex(pathInfo.path, pathInfo.method);pathRegex != expectedPathRegex[idx] {
			test.Errorf("pathRegex generated not as expected, path: %v, actulPathRegex: %v",
			pathInfo.path, pathRegex)
		}
	}
}


text:
using System.Diagnostics.CodeAnalysis;

// Suppress this warning because it is used by "scenario" type of string parameters in theory test methods
[assembly: SuppressMessage("Usage", "xUnit1026:Theory methods should use all of their parameters")]


text:
namespace arangodb {

namespace velocypack {
class Builder;
}

namespace aql {
class Query;

struct QueryProfile {
  QueryProfile(QueryProfile const&) = delete;
  QueryProfile& operator=(QueryProfile const&) = delete;

  explicit QueryProfile(Query*);

  ~QueryProfile();

  double setDone(QueryExecutionState::ValueType);

  /// @brief sets the absolute end time for an execution state
  void setEnd(QueryExecutionState::ValueType state, double time);

  /// @brief convert the profile to VelocyPack
  std::shared_ptr<arangodb::velocypack::Builder> toVelocyPack();

  Query* query;
  std::array<double, static_cast<size_t>(QueryExecutionState::ValueType::INVALID_STATE)> timers;
  double stamp;
  bool tracked;
};

// we want the number of execution states to be quite low
// as we reserve a statically sized array for it
static_assert(static_cast<int>(QueryExecutionState::ValueType::INITIALIZATION) == 0, "unexpected min QueryExecutionState enum value");
static_assert(static_cast<int>(QueryExecutionState::ValueType::INVALID_STATE) < 10, "unexpected max QueryExecutionState enum value");

}
}

#endif


text:
import os
import sys

def main():
    try:
        source, destination = sys.argv[1:]
        assert os.path.isdir(source), '<source_directory> is not a directory'
        if os.path.exists(destination):
            assert os.path.isdir(destination), \
                   '<destination_directory> is not a directory'
        else:
            os.makedirs(destination)
        copy(source, destination)
    except Exception, error:
        program = 'USAGE:  %s <source_directory> <destination_directory>' % \
                  os.path.basename(sys.argv[0])
        problem = 'ERROR:  %s' % error
        divider = '=' * max(len(program), len(problem))
        sys.stdout.write('\n%s\n%s\n%s\n' % (program, divider, problem))

def copy(source, destination):
    for name in os.listdir(source):
        source_name = os.path.join(source, name)
        destination_name = os.path.join(destination, name)
        try:
            if os.path.isdir(source_name):
                os.mkdir(destination_name)
                copy(source_name, destination_name)
            elif os.path.isfile(source_name):
                file(destination_name, 'wb').write(
                    file(source_name, 'rb').read())
        except:
            sys.stderr.write('\n%s\n%s\n' % (source_name, destination_name))

if __name__ == '__main__':
    main()


text:
package transgenic.lauterbrunnen.lateral.dicontext.onecontextmultipledefaultimpls3;

import transgenic.lauterbrunnen.lateral.di.LateralDIContext;

/**
 * Created by stumeikle on 28/07/19.
 */
public class MyContext implements LateralDIContext {
}


text:
global.buster = require("buster");
var createTests = require("./tests");
var HTML5Outline = require("../dist/outliner.min");
var contextPath = require("path").resolve(__dirname + "/..");

function runTestsIn(jsdomModule) {
	require(jsdomModule).env(
		"

",
		{features: {FetchExternalResources: ["iframe"]}},
		function (e, w) {
			createTests(jsdomModule, w.document, contextPath, HTML5Outline);
		});
}

runTestsIn("jsdom-compat");
!process.version.indexOf("v0.10") || runTestsIn("jsdom");


text:
package ca.ulaval.ticketmaster.purchase;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import ca.ulaval.ticketmaster.events.tickets.model.Ticket;
import ca.ulaval.ticketmaster.exceptions.InvalidFormExceptions;
import ca.ulaval.ticketmaster.exceptions.InvalidPurchaseException;
import ca.ulaval.ticketmaster.exceptions.UnauthenticatedException;
import ca.ulaval.ticketmaster.home.DAAuthentication;
import ca.ulaval.ticketmaster.home.Page;
import ca.ulaval.ticketmaster.purchase.model.PaymentType;
import ca.ulaval.ticketmaster.purchase.model.PurchaseViewModel;
import ca.ulaval.ticketmaster.springproxy.ProxyHttpSession;
import ca.ulaval.ticketmaster.springproxy.ProxyModel;

@Controller
@RequestMapping(value = "/purchase")
public class PurchaseController {

    private BLBasket domaine;

    public PurchaseController() {
	domaine = new BLBasket();
    }

    @RequestMapping(value = "/Confirmation", method = RequestMethod.GET)
    public String confirmation(Model model) {
	return Page.Confirmation.toString();
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/Purchase", method = RequestMethod.GET)
    public String purchase(Model model, HttpSession session) {
	model.addAttribute("purchaseInfos", new PurchaseViewModel());
	model.addAttribute("paymentType", PaymentType.values());
	model.addAttribute("basketDisplay", (ArrayList<Ticket>) session.getAttribute("basketDisplay"));
	return Page.Purchase.toString();
    }

    @RequestMapping(value = "/Purchase", method = RequestMethod.POST)
    public String purchase(@Valid PurchaseViewModel purchaseModel, Model model, HttpSession session,
	    BindingResult result, HttpServletRequest request) {
	model.addAttribute("purchaseInfos", new PurchaseViewModel());
	model.addAttribute("paymentType", PaymentType.values());
	System.out.println(request.getLocalAddr());
	try {
	    domaine.purchase(ProxyHttpSession.create(session), ProxyModel.create(model), result);
	} catch (UnauthenticatedException e) {
	    return Page.Home.toString();
	} catch (InvalidFormExceptions e) {
	    return Page.Purchase.toString();
	} catch (InvalidPurchaseException e) {
	    return Page.Purchase.toString();
	}

	return "redirect:/purchase/Confirmation";
    }

    @RequestMapping(value = "/Basket", method = RequestMethod.GET)
    public String basket(Model model, HttpSession session) {
	if (DAAuthentication.isLogged(ProxyHttpSession.create(session)))
	    return Page.Basket.toString();
	else {
	    model.addAttribute("errorMsg", new UnauthenticatedException().getErrorMsg());
	    return Page.Home.toString();
	}
    }

    @RequestMapping(value = "/addBasket", method = RequestMethod.POST)
    public String copyToBasket(@RequestParam("amount") int amount, @RequestParam("ticketId") String ticketId,
	    @RequestParam("eventId") String eventId, Model model, HttpSession session) {
	try {
	    domaine.copyToBasket(eventId, ticketId, amount, ProxyModel.create(model),
		    ProxyHttpSession.create(session));
	} catch (UnauthenticatedException e) {
	    // model.addAttribute("errorMsg", e.getErrorMsg());
	    return Page.Home.toString();
	}

	return Page.Basket.toString();
    }

    @RequestMapping(value = "/emptyBasket", method = RequestMethod.GET)
    public String emptyBasket(Model model, HttpSession session) {
	try {
	    domaine.removeAllFromBasket(ProxyHttpSession.create(session));
	} catch (UnauthenticatedException e) {
	    return Page.Home.toString();
	}

	return Page.Basket.toString();
    }
}


text:
package cn.easyhbase.client.hbase;

import org.apache.hadoop.hbase.client.Result;

/**
 * @author emeroad
 */
public class EmptyLimitEventHandler implements LimitEventHandler{

    @Override
    public void handleLastResult(Result lastResult) {
    }
}


text:
/**
 * @file
 * @brief
 *  This file implements the Tunnel mode (Thread Miniport) functions required for the OpenThread library.
 */

#include "precomp.h"
#include "tunnel.tmh"

KSTART_ROUTINE otLwfTunWorkerThread;

SPINEL_CMD_HANDLER otLwfIrpCommandHandler;

typedef struct _SPINEL_IRP_CMD_CONTEXT
{
    PMS_FILTER              pFilter;
    PIRP                    Irp;
    SPINEL_IRP_CMD_HANDLER *Handler;
    spinel_tid_t            tid;
} SPINEL_IRP_CMD_CONTEXT;

_IRQL_requires_max_(PASSIVE_LEVEL)
NDIS_STATUS
otLwfTunInitialize(
    _In_ PMS_FILTER pFilter
    )
{
    NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
    HANDLE threadHandle = NULL;

    LogFuncEntry(DRIVER_DEFAULT);

    NT_ASSERT(pFilter->DeviceCapabilities & OTLWF_DEVICE_CAP_THREAD_1_0);

    KeInitializeEvent(
        &pFilter->TunWorkerThreadStopEvent,
        SynchronizationEvent, // auto-clearing event
        FALSE                 // event initially non-signalled
        );
    KeInitializeEvent(
        &pFilter->TunWorkerThreadAddressChangedEvent,
        SynchronizationEvent, // auto-clearing event
        FALSE                 // event initially non-signalled
        );

    // Start the worker thread
    Status = PsCreateSystemThread(
                &threadHandle,                  // ThreadHandle
                THREAD_ALL_ACCESS,              // DesiredAccess
                NULL,                           // ObjectAttributes
                NULL,                           // ProcessHandle
                NULL,                           // ClientId
                otLwfTunWorkerThread,           // StartRoutine
                pFilter                         // StartContext
                );
    if (!NT_SUCCESS(Status))
    {
        LogError(DRIVER_DEFAULT, "PsCreateSystemThread failed, %!STATUS!", Status);
        goto error;
    }

    // Grab the object reference to the worker thread
    Status = ObReferenceObjectByHandle(
                threadHandle,
                THREAD_ALL_ACCESS,
                *PsThreadType,
                KernelMode,
                &pFilter->TunWorkerThread,
                NULL
                );
    if (!NT_VERIFYMSG("ObReferenceObjectByHandle can't fail with a valid kernel handle", NT_SUCCESS(Status)))
    {
        LogError(DRIVER_DEFAULT, "ObReferenceObjectByHandle failed, %!STATUS!", Status);
        KeSetEvent(&pFilter->TunWorkerThreadStopEvent, IO_NO_INCREMENT, FALSE);
    }

    // Make sure to enable RLOC passthrough
    Status =
        otLwfCmdSetProp(
            pFilter,
            SPINEL_PROP_THREAD_RLOC16_DEBUG_PASSTHRU,
            SPINEL_DATATYPE_BOOL_S,
            TRUE
        );
    if (!NT_SUCCESS(Status))
    {
        LogError(DRIVER_DEFAULT, "Enabling RLOC pass through failed, %!STATUS!", Status);
        goto error;
    }

    // TODO - Query other values and capabilities

error:

    if (!NT_SUCCESS(Status))
    {
        otLwfTunUninitialize(pFilter);
    }

    LogFuncExitNDIS(DRIVER_DEFAULT, Status);

    return Status;
}

_IRQL_requires_max_(PASSIVE_LEVEL)
void
otLwfTunUninitialize(
    _In_ PMS_FILTER pFilter
    )
{
    LogFuncEntry(DRIVER_DEFAULT);

    // Clean up worker thread
    if (pFilter->TunWorkerThread)
    {
        LogInfo(DRIVER_DEFAULT, "Stopping tunnel worker thread and waiting for it to complete.");

        // Send event to shutdown worker thread
        KeSetEvent(&pFilter->TunWorkerThreadStopEvent, 0, FALSE);

        // Wait for worker thread to finish
        KeWaitForSingleObject(
            pFilter->TunWorkerThread,
            Executive,
            KernelMode,
            FALSE,
            NULL
            );

        // Free worker thread
        ObDereferenceObject(pFilter->TunWorkerThread);
        pFilter->TunWorkerThread = NULL;

        LogInfo(DRIVER_DEFAULT, "Tunnel worker thread cleaned up.");
    }

    LogFuncExit(DRIVER_DEFAULT);
}

// Worker thread for processing all tunnel events
_Use_decl_annotations_
VOID
otLwfTunWorkerThread(
    PVOID   Context
    )
{
    PMS_FILTER pFilter = (PMS_FILTER)Context;
    NT_ASSERT(pFilter);

    LogFuncEntry(DRIVER_DEFAULT);

    PKEVENT WaitEvents[] =
    {
        &pFilter->TunWorkerThreadStopEvent,
        &pFilter->TunWorkerThreadAddressChangedEvent
    };

    LogFuncExit(DRIVER_DEFAULT);

    while (true)
    {
        // Wait for event to stop or process event to fire
        NTSTATUS status =
            KeWaitForMultipleObjects(
                ARRAYSIZE(WaitEvents),
                (PVOID*)WaitEvents,
                WaitAny,
                Executive,
                KernelMode,
                FALSE,
                NULL,
                NULL);

        // If it is the first event, then we are shutting down. Exit loop and terminate thread
        if (status == STATUS_WAIT_0)
        {
            LogInfo(DRIVER_DEFAULT, "Received tunnel worker thread shutdown event.");
            break;
        }
        else if (status == STATUS_WAIT_0 + 1) // TunWorkerThreadAddressChangedEvent fired
        {
            PVOID DataBuffer = NULL;
            const uint8_t* value_data_ptr = NULL;
            spinel_size_t value_data_len = 0;

            // Query the current addresses
            status =
                otLwfCmdGetProp(
                    pFilter,
                    &DataBuffer,
                    SPINEL_PROP_IPV6_ADDRESS_TABLE,
                    SPINEL_DATATYPE_DATA_S,
                    &value_data_ptr,
                    &value_data_len);
            if (NT_SUCCESS(status))
            {
                uint32_t aNotifFlags = 0;
                otLwfTunAddressesUpdated(pFilter, value_data_ptr, value_data_len, &aNotifFlags);

                // Send notification
                if (aNotifFlags != 0)
                {
                    PFILTER_NOTIFICATION_ENTRY NotifEntry = FILTER_ALLOC_NOTIF(pFilter);
                    if (NotifEntry)
                    {
                        RtlZeroMemory(NotifEntry, sizeof(FILTER_NOTIFICATION_ENTRY));
                        NotifEntry->Notif.InterfaceGuid = pFilter->InterfaceGuid;
                        NotifEntry->Notif.NotifType = OTLWF_NOTIF_STATE_CHANGE;
                        NotifEntry->Notif.StateChangePayload.Flags = aNotifFlags;

                        otLwfIndicateNotification(NotifEntry);
                    }
                }
            }
            else
            {
                LogWarning(DRIVER_DEFAULT, "Failed to query addresses, %!STATUS!", status);
            }

            if (DataBuffer) FILTER_FREE_MEM(DataBuffer);
        }
        else
        {
            LogWarning(DRIVER_DEFAULT, "Unexpected wait result, %!STATUS!", status);
        }
    }

    PsTerminateSystemThread(STATUS_SUCCESS);
}

_IRQL_requires_max_(DISPATCH_LEVEL)
VOID
otLwfIrpCommandHandler(
    _In_ PMS_FILTER pFilter,
    _In_ PVOID Context,
    _In_ UINT Command,
    _In_ spinel_prop_key_t Key,
    _In_reads_bytes_(DataLength) const uint8_t* Data,
    _In_ spinel_size_t DataLength
    )
{
    SPINEL_IRP_CMD_CONTEXT* CmdContext = (SPINEL_IRP_CMD_CONTEXT*)Context;
    PIO_STACK_LOCATION  IrpSp = IoGetCurrentIrpStackLocation(CmdContext->Irp);

    ULONG IoControlCode = IrpSp->Parameters.DeviceIoControl.IoControlCode;
    PVOID OutBuffer = CmdContext->Irp->AssociatedIrp.SystemBuffer;
    ULONG OutBufferLength = IrpSp->Parameters.DeviceIoControl.OutputBufferLength;
    ULONG OrigOutBufferLength = OutBufferLength;

    NTSTATUS status;

    UNREFERENCED_PARAMETER(pFilter);

    // Clear the cancel routine
    IoSetCancelRoutine(CmdContext->Irp, NULL);

    if (Data == NULL)
    {
        status = STATUS_CANCELLED;
        OutBufferLength = 0;
    }
    else if (Command == SPINEL_CMD_PROP_VALUE_IS && Key == SPINEL_PROP_LAST_STATUS)
    {
        spinel_status_t spinel_status = SPINEL_STATUS_OK;
        spinel_ssize_t packed_len = spinel_datatype_unpack(Data, DataLength, "i", &spinel_status);
        if (packed_len < 0 || (ULONG)packed_len > DataLength)
        {
            status = STATUS_INSUFFICIENT_RESOURCES;
        }
        else
        {
            status = ThreadErrorToNtstatus(SpinelStatusToThreadError(spinel_status));
        }
    }
    else if (CmdContext->Handler)
    {
        status = CmdContext->Handler(Key, Data, DataLength, OutBuffer, &OutBufferLength);
    }
    else // No handler, so no output
    {
        status = STATUS_SUCCESS;
        OutBufferLength = 0;
    }

    // Clear any leftover output buffer
    if (OutBufferLength < OrigOutBufferLength)
    {
        RtlZeroMemory((PUCHAR)OutBuffer + OutBufferLength, OrigOutBufferLength - OutBufferLength);
    }

    LogVerbose(DRIVER_IOCTL, "Completing Irp=%p, with %!STATUS! for %s (Out:%u)",
                CmdContext->Irp, status, IoCtlString(IoControlCode), OutBufferLength);

    // Complete the IRP
    CmdContext->Irp->IoStatus.Information = OutBufferLength;
    CmdContext->Irp->IoStatus.Status = status;
    IoCompleteRequest(CmdContext->Irp, IO_NO_INCREMENT);

    FILTER_FREE_MEM(Context);
}

_Function_class_(DRIVER_CANCEL)
_Requires_lock_held_(_Global_cancel_spin_lock_)
_Releases_lock_(_Global_cancel_spin_lock_)
_IRQL_requires_min_(DISPATCH_LEVEL)
_IRQL_requires_(DISPATCH_LEVEL)
VOID
otLwfTunCancelIrp(
    _Inout_ struct _DEVICE_OBJECT *DeviceObject,
    _Inout_ _IRQL_uses_cancel_ struct _IRP *Irp
    )
{
    PIO_STACK_LOCATION IrpStack = IoGetCurrentIrpStackLocation(Irp);
    SPINEL_IRP_CMD_CONTEXT* CmdContext = (SPINEL_IRP_CMD_CONTEXT*)IrpStack->Context;

    UNREFERENCED_PARAMETER(DeviceObject);

    LogFuncEntryMsg(DRIVER_IOCTL, "Irp=%p", Irp);

    IoReleaseCancelSpinLock(Irp->CancelIrql);

    // Try to cancel pending command
    otLwfCmdCancel(
        CmdContext->pFilter,
        (Irp->CancelIrql == DISPATCH_LEVEL) ? TRUE : FALSE,
        CmdContext->tid);

    LogFuncExit(DRIVER_IOCTL);
}

_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
otLwfTunSendCommandForIrp(
    _In_ PMS_FILTER pFilter,
    _In_ PIRP Irp,
    _In_opt_ SPINEL_IRP_CMD_HANDLER *Handler,
    _In_ UINT Command,
    _In_ spinel_prop_key_t Key,
    _In_ ULONG MaxDataLength,
    _In_opt_ const char *pack_format,
    ...
    )
{
    NTSTATUS status = STATUS_SUCCESS;
    SPINEL_IRP_CMD_CONTEXT *pContext = NULL;
    PIO_STACK_LOCATION IrpStack = IoGetCurrentIrpStackLocation(Irp);

    // Create the context structure
    pContext = FILTER_ALLOC_MEM(pFilter->FilterHandle, sizeof(SPINEL_IRP_CMD_CONTEXT));
    if (pContext == NULL)
    {
        status = STATUS_INSUFFICIENT_RESOURCES;
        LogWarning(DRIVER_DEFAULT, "Failed to allocate irp cmd context");
        goto exit;
    }

    pContext->pFilter = pFilter;
    pContext->Irp = Irp;
    pContext->Handler = Handler;

    NT_ASSERT(IrpStack->Context == NULL);
    IrpStack->Context = pContext;

    // Set the cancel routine
    IoSetCancelRoutine(Irp, otLwfTunCancelIrp);

    va_list args;
    va_start(args, pack_format);
    status =
        otLwfCmdSendAsyncV(
            pFilter,
            otLwfIrpCommandHandler,
            pContext,
            &pContext->tid,
            Command,
            Key,
            MaxDataLength,
            pack_format,
            args);
    va_end(args);

    // Remove the handler entry from the list
    if (!NT_SUCCESS(status))
    {
        // Clear the cancel routine
        IoSetCancelRoutine(Irp, NULL);

        FILTER_FREE_MEM(pContext);
    }

exit:

    return status;
}

_IRQL_requires_max_(DISPATCH_LEVEL)
void
otLwfTunValueIs(
    _In_ PMS_FILTER pFilter,
    _In_ BOOLEAN DispatchLevel,
    _In_ spinel_prop_key_t key,
    _In_reads_bytes_(value_data_len) const uint8_t* value_data_ptr,
    _In_ spinel_size_t value_data_len
    )
{
    uint32_t aNotifFlags = 0;

    LogFuncEntryMsg(DRIVER_DEFAULT, "[%p] received Value for %s", pFilter, spinel_prop_key_to_cstr(key));

    if (key == SPINEL_PROP_NET_ROLE)
    {
        uint8_t value;
        spinel_datatype_unpack(value_data_ptr, value_data_len, SPINEL_DATATYPE_UINT8_S, &value);

        LogInfo(DRIVER_DEFAULT, "Interface %!GUID! new spinel role: %u", &pFilter->InterfaceGuid, value);

        // Make sure we are in the correct media connect state
        otLwfIndicateLinkState(
            pFilter,
            value > SPINEL_NET_ROLE_DETACHED ?
            MediaConnectStateConnected :
            MediaConnectStateDisconnected);

        // Set flag to indicate we should send a notification
        aNotifFlags = OT_CHANGED_THREAD_ROLE;
    }
    else if (key == SPINEL_PROP_IPV6_LL_ADDR)
    {
        // Set flag to indicate we should send a notification
        aNotifFlags = OT_CHANGED_THREAD_LL_ADDR;
    }
    else if (key == SPINEL_PROP_IPV6_ML_ADDR)
    {
        // Set flag to indicate we should send a notification
        aNotifFlags = OT_CHANGED_THREAD_ML_ADDR;
    }
    else if (key == SPINEL_PROP_NET_PARTITION_ID)
    {
        // Set flag to indicate we should send a notification
        aNotifFlags = OT_CHANGED_THREAD_PARTITION_ID;
    }
    else if (key == SPINEL_PROP_NET_KEY_SEQUENCE_COUNTER)
    {
        // Set flag to indicate we should send a notification
        aNotifFlags = OT_CHANGED_THREAD_KEY_SEQUENCE_COUNTER;
    }
    else if (key == SPINEL_PROP_IPV6_ADDRESS_TABLE)
    {
        KeSetEvent(&pFilter->TunWorkerThreadAddressChangedEvent, IO_NO_INCREMENT, FALSE);
    }
    else if (key == SPINEL_PROP_THREAD_CHILD_TABLE)
    {
        // TODO - Update cached children
        // TODO - Send notification
    }
    else if (key == SPINEL_PROP_THREAD_ON_MESH_NETS)
    {
        // TODO - Slaac

        // Set flag to indicate we should send a notification
        aNotifFlags = OT_CHANGED_THREAD_NETDATA;
    }
    else if ((key == SPINEL_PROP_STREAM_NET) || (key == SPINEL_PROP_STREAM_NET_INSECURE))
    {
        const uint8_t* frame_ptr = NULL;
        UINT frame_len = 0;
        spinel_ssize_t ret;

        ret = spinel_datatype_unpack(
            value_data_ptr,
            value_data_len,
            SPINEL_DATATYPE_DATA_WLEN_S SPINEL_DATATYPE_DATA_S,
            &frame_ptr,
            &frame_len,
            NULL,
            NULL);

        NT_ASSERT(ret > 0);
        if (ret > 0)
        {
            otLwfTunReceiveIp6Packet(
                pFilter,
                DispatchLevel,
                (SPINEL_PROP_STREAM_NET_INSECURE == key) ? FALSE : TRUE,
                frame_ptr,
                frame_len);
        }
    }
    else if (key == SPINEL_PROP_MAC_SCAN_STATE)
    {
        // TODO - If pending scan, send notification of completion
    }
    else if (key == SPINEL_PROP_STREAM_RAW)
    {
        // May be used in the future
    }
    else if (key == SPINEL_PROP_STREAM_DEBUG)
    {
        const uint8_t* output = NULL;
        UINT output_len = 0;
        spinel_ssize_t ret;

        ret = spinel_datatype_unpack(
            value_data_ptr,
            value_data_len,
            SPINEL_DATATYPE_DATA_S,
            &output,
            &output_len);

        NT_ASSERT(ret > 0);
        if (ret > 0 && output && output_len <= (UINT)ret)
        {
            if (strnlen((char*)output, output_len) != output_len)
            {
                LogInfo(DRIVER_DEFAULT, "DEVICE: %s", (char*)output);
            }
            else if (output_len < 128)
            {
                char strOutput[128] = { 0 };
                memcpy(strOutput, output, output_len);
                LogInfo(DRIVER_DEFAULT, "DEVICE: %s", strOutput);
            }
        }
    }

    // Send notification
    if (aNotifFlags != 0)
    {
        PFILTER_NOTIFICATION_ENTRY NotifEntry = FILTER_ALLOC_NOTIF(pFilter);
        if (NotifEntry)
        {
            RtlZeroMemory(NotifEntry, sizeof(FILTER_NOTIFICATION_ENTRY));
            NotifEntry->Notif.InterfaceGuid = pFilter->InterfaceGuid;
            NotifEntry->Notif.NotifType = OTLWF_NOTIF_STATE_CHANGE;
            NotifEntry->Notif.StateChangePayload.Flags = aNotifFlags;

            otLwfIndicateNotification(NotifEntry);
        }
    }

    LogFuncExit(DRIVER_DEFAULT);
}

_IRQL_requires_max_(DISPATCH_LEVEL)
void
otLwfTunValueInserted(
    _In_ PMS_FILTER pFilter,
    _In_ BOOLEAN DispatchLevel,
    _In_ spinel_prop_key_t key,
    _In_reads_bytes_(value_data_len) const uint8_t* value_data_ptr,
    _In_ spinel_size_t value_data_len
    )
{
    LogFuncEntryMsg(DRIVER_DEFAULT, "[%p] received Value Inserted for %s", pFilter, spinel_prop_key_to_cstr(key));

    UNREFERENCED_PARAMETER(pFilter);
    UNREFERENCED_PARAMETER(DispatchLevel);
    UNREFERENCED_PARAMETER(value_data_ptr);
    UNREFERENCED_PARAMETER(value_data_len);

    if (key == SPINEL_PROP_MAC_SCAN_BEACON)
    {
        PFILTER_NOTIFICATION_ENTRY NotifEntry = FILTER_ALLOC_NOTIF(pFilter);
        if (NotifEntry)
        {
            RtlZeroMemory(NotifEntry, sizeof(FILTER_NOTIFICATION_ENTRY));
            NotifEntry->Notif.InterfaceGuid = pFilter->InterfaceGuid;
            NotifEntry->Notif.NotifType = OTLWF_NOTIF_ACTIVE_SCAN;
            NotifEntry->Notif.ActiveScanPayload.Valid = TRUE;

            const otExtAddress *aExtAddr = NULL;
            const uint8_t *aExtPanId = NULL;
            const char *aNetworkName = NULL;
            unsigned int xpanid_len = 0;

            if (try_spinel_datatype_unpack(
                value_data_ptr,
                value_data_len,
                SPINEL_DATATYPE_MAC_SCAN_RESULT_S(
                    SPINEL_802_15_4_DATATYPE_MAC_SCAN_RESULT_V1_S,
                    SPINEL_NET_DATATYPE_MAC_SCAN_RESULT_V1_S
                ),
                &NotifEntry->Notif.ActiveScanPayload.Results.mChannel,
                &NotifEntry->Notif.ActiveScanPayload.Results.mRssi,
                &aExtAddr,
                NULL, // saddr (don't care)
                &NotifEntry->Notif.ActiveScanPayload.Results.mPanId,
                &NotifEntry->Notif.ActiveScanPayload.Results.mLqi,
                NULL, // proto (don't care)
                NULL, // flags (don't care)
                &aNetworkName,
                &aExtPanId,
                &xpanid_len
            ) &&
                aExtAddr != NULL && aExtPanId != NULL && aNetworkName != NULL &&
                xpanid_len == OT_EXT_PAN_ID_SIZE)
            {
                memcpy_s(NotifEntry->Notif.ActiveScanPayload.Results.mExtAddress.m8,
                    sizeof(NotifEntry->Notif.ActiveScanPayload.Results.mExtAddress.m8),
                    aExtAddr, sizeof(otExtAddress));
                memcpy_s(NotifEntry->Notif.ActiveScanPayload.Results.mExtendedPanId.m8,
                    sizeof(NotifEntry->Notif.ActiveScanPayload.Results.mExtendedPanId.m8),
                    aExtPanId, sizeof(otExtendedPanId));
                strcpy_s(NotifEntry->Notif.ActiveScanPayload.Results.mNetworkName.m8,
                    sizeof(NotifEntry->Notif.ActiveScanPayload.Results.mNetworkName.m8),
                    aNetworkName);
                otLwfIndicateNotification(NotifEntry);
            }
            else
            {
                FILTER_FREE_MEM(NotifEntry);
            }
        }
    }
    else if (key == SPINEL_PROP_MAC_ENERGY_SCAN_RESULT)
    {
        PFILTER_NOTIFICATION_ENTRY NotifEntry = FILTER_ALLOC_NOTIF(pFilter);
        if (NotifEntry)
        {
            RtlZeroMemory(NotifEntry, sizeof(FILTER_NOTIFICATION_ENTRY));
            NotifEntry->Notif.InterfaceGuid = pFilter->InterfaceGuid;
            NotifEntry->Notif.NotifType = OTLWF_NOTIF_ENERGY_SCAN;
            NotifEntry->Notif.EnergyScanPayload.Valid = TRUE;

            if (try_spinel_datatype_unpack(
                value_data_ptr,
                value_data_len,
                "Cc",
                &NotifEntry->Notif.EnergyScanPayload.Results.mChannel,
                &NotifEntry->Notif.EnergyScanPayload.Results.mMaxRssi
            ))
            {
                otLwfIndicateNotification(NotifEntry);
            }
            else
            {
                FILTER_FREE_MEM(NotifEntry);
            }
        }
    }

    LogFuncExit(DRIVER_DEFAULT);
}


text:
package models.services

import scala.concurrent.Future
import models.Token

/**
 * A trait that provides the means to handle auth tokens for the Silhouette module.
 *
 * Tokens are needed for users that are creating an account in the system instead of using
 * one in a third-party system.
 */
trait TokenService[T <: Token] {

  /**
   * Creates a new token.
   *
   * The new token will be persisted so that later it can be retrieved by its ID.
   *
   * @param token The token to create.
   * @return The created token or None if the token couldn't be created.
   */
  def create(token: T): Future[Option[T]]

  /**
   * Retrieves an available token.
   *
   * @param id The token ID.
   * @return The retrieved token or None if no token could be retrieved for the given ID.
   */
  def retrieve(id: String): Future[Option[T]]

  /**
   * Consumes a token.
   *
   * This method makes the token unavailable for further use.
   * It's up to the implementation how to do that. For example, the token can be deleted,
   * updated as "consumed", moved to another table, etc.
   *
   * Consumed tokens can't be retrieved.
   *
   * @param id The ID of the token to consume.
   */
  def consume(id: String)
}


text:
package javax.xml.ws;

import java.lang.annotation.Documented;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;

/**
 * Used to annotate service specific exception classes to customize
 * to the local and namespace name of the fault element and the name
 * of the fault bean.
 *
 *  @since JAX-WS 2.0
**/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface WebFault {
  /**
   *  Element's local name.
  **/
  public String name() default "";

  /**
   *  Element's namespace name.
  **/
  public String targetNamespace() default "";

  /**
   *  Fault bean name.
  **/
  public String faultBean() default "";

  /**
   *  wsdl:Message's name. Default name is the exception's class name.
   *  @since JAX-WS 2.2
   */
  public String messageName() default "";

}