text:
package org.apache.felix.http.itest.servletapi5;

import static java.util.Arrays.asList;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.osgi.framework.Constants.SERVICE_RANKING;
import static org.osgi.service.servlet.runtime.HttpServiceRuntimeConstants.HTTP_SERVICE_ENDPOINT;
import static org.osgi.service.servlet.runtime.dto.DTOConstants.FAILURE_REASON_EXCEPTION_ON_INIT;
import static org.osgi.service.servlet.runtime.dto.DTOConstants.FAILURE_REASON_NO_SERVLET_CONTEXT_MATCHING;
import static org.osgi.service.servlet.runtime.dto.DTOConstants.FAILURE_REASON_SHADOWED_BY_OTHER_SERVICE;
import static org.osgi.service.servlet.runtime.dto.DTOConstants.FAILURE_REASON_VALIDATION_FAILED;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_NAME;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_PATTERN;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_LISTENER;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_RESOURCE_PATTERN;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_RESOURCE_PREFIX;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_ERROR_PAGE;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN;
import static org.osgi.service.servlet.whiteboard.HttpWhiteboardConstants.HTTP_WHITEBOARD_TARGET;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Dictionary;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerMethod;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.dto.ServiceReferenceDTO;
import org.osgi.service.servlet.context.ServletContextHelper;
import org.osgi.service.servlet.runtime.HttpServiceRuntime;
import org.osgi.service.servlet.runtime.dto.FailedErrorPageDTO;
import org.osgi.service.servlet.runtime.dto.FailedServletDTO;
import org.osgi.service.servlet.runtime.dto.RequestInfoDTO;
import org.osgi.service.servlet.runtime.dto.RuntimeDTO;
import org.osgi.service.servlet.runtime.dto.ServletContextDTO;
import org.osgi.service.servlet.runtime.dto.ServletDTO;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.Servlet;
import jakarta.servlet.ServletContextAttributeListener;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequestAttributeListener;
import jakarta.servlet.ServletRequestListener;
import jakarta.servlet.http.HttpSessionAttributeListener;
import jakarta.servlet.http.HttpSessionListener;

@RunWith(PaxExam.class)
@ExamReactorStrategy(PerMethod.class)
public class HttpServiceRuntimeTest extends Servlet5BaseIntegrationTest {

    private static final String HTTP_CONTEXT_NAME = "org.osgi.service.http";

    private void registerServlet(String name, String path) throws InterruptedException {
        registerServlet(name, path, null);
    }

    private void registerServlet(String name, String path, String context) {
        List<Object> propertyEntries = Arrays.<Object>asList(
                HTTP_WHITEBOARD_SERVLET_PATTERN, path,
                HTTP_WHITEBOARD_SERVLET_NAME, name,
                HTTP_WHITEBOARD_CONTEXT_SELECT, context);

        Dictionary<String, ?> properties = createDictionary(context == null ?
                propertyEntries.subList(0, 4).toArray() : propertyEntries.toArray());

        registrations.add(m_context.registerService(Servlet.class.getName(), new TestServlet(), properties));
    }

    private void registerFilter(String name, String path) throws InterruptedException {
        registerFilter(name, path, null);
    }

    private void registerFilter(String name, String path, String context) {
        List<Object> propertyEntries = Arrays.<Object>asList(
                HTTP_WHITEBOARD_FILTER_PATTERN, path,
                HTTP_WHITEBOARD_FILTER_NAME, name,
                HTTP_WHITEBOARD_CONTEXT_SELECT, context);

        Dictionary<String, ?> properties = createDictionary(context == null ?
                propertyEntries.subList(0, 4).toArray() : propertyEntries.toArray());

        registrations.add(m_context.registerService(Filter.class.getName(), new TestFilter(), properties));
    }

    private void registerResource(String prefix, String path) throws InterruptedException {
        registerResource(prefix, path, null);
    }

    private void registerResource(String prefix, String path, String context) throws InterruptedException {
        List<Object> propertyEntries = Arrays.<Object>asList(
                HTTP_WHITEBOARD_RESOURCE_PATTERN, path,
                HTTP_WHITEBOARD_RESOURCE_PREFIX, prefix,
                HTTP_WHITEBOARD_CONTEXT_SELECT, context);

        Dictionary<String, ?> properties = createDictionary(context == null ?
                propertyEntries.subList(0, 4).toArray() : propertyEntries.toArray());

        registrations.add(m_context.registerService(TestResource.class.getName(), new TestResource(), properties));
    }

    private void registerErrorPage(String name, List<String> errors) throws InterruptedException {
        registerErrorPage(name, errors, null);
    }

    private void registerErrorPage(String name, List<String> errors, String context) {
        List<Object> propertyEntries = Arrays.<Object>asList(
                HTTP_WHITEBOARD_SERVLET_ERROR_PAGE, errors,
                HTTP_WHITEBOARD_SERVLET_NAME, name,
                HTTP_WHITEBOARD_CONTEXT_SELECT, context);

        Dictionary<String, ?> properties = createDictionary(context == null ?
                propertyEntries.subList(0, 4).toArray() : propertyEntries.toArray());

        registrations.add(m_context.registerService(Servlet.class.getName(), new TestServlet(), properties));
    }

    private void registerListener(Class<?> listenerClass, boolean useWithWhiteboard) throws InterruptedException {
        registerListener(listenerClass, useWithWhiteboard, null);
    }

    private void registerListener(Class<?> listenerClass, boolean useWithWhiteboard, String context) throws InterruptedException {
        List<Object> propertyEntries = Arrays.<Object>asList(
                HTTP_WHITEBOARD_LISTENER, useWithWhiteboard ? "true" : "false",
                HTTP_WHITEBOARD_CONTEXT_SELECT, context);

        Dictionary<String, ?> properties = createDictionary(context == null ?
                propertyEntries.subList(0, 2).toArray() : propertyEntries.toArray());

        registrations.add(m_context.registerService(listenerClass.getName(), mock(listenerClass), properties));
    }

    private ServiceRegistration<?> registerContext(String name, String path) throws InterruptedException {
        Dictionary<String, ?> properties = createDictionary(
                HTTP_WHITEBOARD_CONTEXT_NAME, name,
                HTTP_WHITEBOARD_CONTEXT_PATH, path);

        ServiceRegistration<?> contextRegistration = m_context.registerService(ServletContextHelper.class.getName(), mock(ServletContextHelper.class), properties);
        registrations.add(contextRegistration);
        return contextRegistration;
    }

    @Before
    public void awaitServiceRuntime() throws Exception {
        awaitService(HttpServiceRuntime.class);
    }

    @Test
    public void httpRuntimeServiceIsAvailableAfterBundleActivation() throws Exception {
        HttpServiceRuntime serviceRuntime = getService(HttpServiceRuntime.class);
        assertNotNull("HttpServiceRuntime unavailable", serviceRuntime);

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();
        ServiceReferenceDTO serviceDTO = runtimeDTO.serviceDTO;

        assertNotNull(serviceDTO);
        assertNotNull(serviceDTO.properties);
        assertTrue(serviceDTO.properties.containsKey(HTTP_SERVICE_ENDPOINT));

        assertEquals(0, runtimeDTO.failedErrorPageDTOs.length);
        assertEquals(0, runtimeDTO.failedFilterDTOs.length);
        assertEquals(0, runtimeDTO.failedListenerDTOs.length);
        assertEquals(0, runtimeDTO.failedResourceDTOs.length);
        assertEquals(0, runtimeDTO.failedServletContextDTOs.length);
        assertEquals(0, runtimeDTO.failedServletDTOs.length);

        ServletContextDTO defaultContext = assertDefaultContext(runtimeDTO);

        assertEquals(0, defaultContext.attributes.size());
        assertTrue(0 > runtimeDTO.servletContextDTOs[0].serviceId);
        assertEquals("", defaultContext.contextPath);
        assertEquals(0, defaultContext.initParams.size());

        assertEquals(0, defaultContext.filterDTOs.length);
        assertEquals(0, defaultContext.servletDTOs.length);
        assertEquals(0, defaultContext.resourceDTOs.length);
        assertEquals(0, defaultContext.errorPageDTOs.length);
        assertEquals(0, defaultContext.listenerDTOs.length);
    }

    @Test
    public void dtosForSuccesfullyRegisteredServlets() throws Exception {
        //register first servlet
        this.setupLatches(1);
        registerServlet("testServlet 1", "/servlet_1");
        this.waitForInit();
        HttpServiceRuntime serviceRuntime = getService(HttpServiceRuntime.class);
        assertNotNull("HttpServiceRuntime unavailable", serviceRuntime);

        RuntimeDTO runtimeDTOWithFirstSerlvet = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithFirstSerlvet.failedServletDTOs.length);

        ServletContextDTO contextDTO = assertDefaultContext(runtimeDTOWithFirstSerlvet);
        assertEquals(1, contextDTO.servletDTOs.length);
        assertEquals("testServlet 1", contextDTO.servletDTOs[0].name);

        //register second servlet
        this.setupLatches(1);
        registerServlet("testServlet 2", "/servlet_2");
        this.waitForInit();
        RuntimeDTO runtimeDTOWithBothSerlvets = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithBothSerlvets.failedServletDTOs.length);

        contextDTO = assertDefaultContext(runtimeDTOWithBothSerlvets);
        assertEquals(2, contextDTO.servletDTOs.length);
        final Set<String> names = new HashSet<>();
        names.add(contextDTO.servletDTOs[0].name);
        names.add(contextDTO.servletDTOs[1].name);
        assertTrue(names.contains("testServlet 1"));
        assertTrue(names.contains("testServlet 2"));
    }

    @Test
    public void dtosForSuccesfullyRegisteredFilters() throws Exception {
        //register first filter
        this.setupLatches(1);
        registerFilter("testFilter 1", "/servlet_1");
        this.waitForInit();

        HttpServiceRuntime serviceRuntime = getService(HttpServiceRuntime.class);
        assertNotNull("HttpServiceRuntime unavailable", serviceRuntime);

        RuntimeDTO runtimeDTOWithFirstFilter = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithFirstFilter.failedFilterDTOs.length);

        ServletContextDTO contextDTO = assertDefaultContext(runtimeDTOWithFirstFilter);
        assertEquals(1, contextDTO.filterDTOs.length);
        assertEquals("testFilter 1", contextDTO.filterDTOs[0].name);

        //register second filter
        this.setupLatches(1);
        registerFilter("testFilter 2", "/servlet_1");
        this.waitForInit();

        RuntimeDTO runtimeDTOWithBothFilters = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithBothFilters.failedFilterDTOs.length);

        contextDTO = assertDefaultContext(runtimeDTOWithBothFilters);
        assertEquals(2, contextDTO.filterDTOs.length);
        assertEquals("testFilter 1", contextDTO.filterDTOs[0].name);
        assertEquals("testFilter 2", contextDTO.filterDTOs[1].name);
    }

    @Test
    public void dtosForSuccesfullyRegisteredResources() throws Exception {
        // register first resource service
        registerResource("/resources", "/resource_1/*");

        HttpServiceRuntime serviceRuntime = getService(HttpServiceRuntime.class);
        assertNotNull("HttpServiceRuntime unavailable", serviceRuntime);

        RuntimeDTO runtimeDTOWithFirstResource = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithFirstResource.failedResourceDTOs.length);

        ServletContextDTO contextDTO = assertDefaultContext(runtimeDTOWithFirstResource);
        assertEquals(1, contextDTO.resourceDTOs.length);
        assertEquals("/resources", contextDTO.resourceDTOs[0].prefix);
        assertArrayEquals(new String[] { "/resource_1/*" }, contextDTO.resourceDTOs[0].patterns);

        // register second resource service
        registerResource("/resources", "/resource_2/*");

        RuntimeDTO runtimeDTOWithBothResources = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithBothResources.failedResourceDTOs.length);

        contextDTO = assertDefaultContext(runtimeDTOWithBothResources);
        assertEquals(2, contextDTO.resourceDTOs.length);
        assertEquals("/resources", contextDTO.resourceDTOs[0].prefix);
        assertEquals(1, contextDTO.resourceDTOs[0].patterns.length);
        assertEquals(1, contextDTO.resourceDTOs[1].patterns.length);
        final Set<String> patterns = new HashSet<>();
        patterns.add(contextDTO.resourceDTOs[0].patterns[0]);
        patterns.add(contextDTO.resourceDTOs[1].patterns[0]);
        assertTrue(patterns.contains("/resource_1/*"));
        assertTrue(patterns.contains("/resource_2/*"));
    }

    @Test
    public void dtosForSuccesfullyRegisteredErrorPages() throws Exception {
        // register first error page
        this.setupLatches(1);
        registerErrorPage("error page 1", asList("404", NoSuchElementException.class.getName()));
        this.waitForInit();

        HttpServiceRuntime serviceRuntime = getService(HttpServiceRuntime.class);
        assertNotNull("HttpServiceRuntime unavailable", serviceRuntime);

        RuntimeDTO runtimeDTOWithFirstErrorPage = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithFirstErrorPage.failedServletDTOs.length);
        assertEquals(0, runtimeDTOWithFirstErrorPage.failedErrorPageDTOs.length);

        ServletContextDTO contextDTO = assertDefaultContext(runtimeDTOWithFirstErrorPage);
        assertEquals(1, contextDTO.errorPageDTOs.length);
        assertEquals("error page 1", contextDTO.errorPageDTOs[0].name);
        assertArrayEquals(new String[] { NoSuchElementException.class.getName() }, contextDTO.errorPageDTOs[0].exceptions);
        assertArrayEquals(new long[] { 404 }, contextDTO.errorPageDTOs[0].errorCodes);

        // register second error page
        this.setupLatches(1);
        registerErrorPage("error page 2", asList("500", ServletException.class.getName()));
        this.waitForInit();

        RuntimeDTO runtimeDTOWithBothErrorPages = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithBothErrorPages.failedServletDTOs.length);
        assertEquals(0, runtimeDTOWithBothErrorPages.failedErrorPageDTOs.length);

        contextDTO = assertDefaultContext(runtimeDTOWithBothErrorPages);
        assertEquals(2, contextDTO.errorPageDTOs.length);
        assertEquals("error page 1", contextDTO.errorPageDTOs[0].name);
        assertEquals("error page 2", contextDTO.errorPageDTOs[1].name);
        assertArrayEquals(new String[] { ServletException.class.getName() }, contextDTO.errorPageDTOs[1].exceptions);
        assertArrayEquals(new long[] { 500 }, contextDTO.errorPageDTOs[1].errorCodes);
    }

    @Test
    public void dtosForSuccesfullyRegisteredErrorPageForClientErrorCodes() throws Exception {
        dtosForSuccesfullyRegisteredErrorPageWithWildcardErrorCode("4xx", 400);
    }

    @Test
    public void dtosForSuccesfullyRegisteredErrorPageForClientErrorCodesCaseInsensitive() throws Exception {
        dtosForSuccesfullyRegisteredErrorPageWithWildcardErrorCode("4xX", 400);
    }

    @Test
    public void dtosForSuccesfullyRegisteredErrorPageForServerErrorCodes() throws Exception {
        dtosForSuccesfullyRegisteredErrorPageWithWildcardErrorCode("5xx", 500);
    }

    @Test
    public void dtosForSuccesfullyRegisteredErrorPageForServerErrorCodesCaseInsensitive() throws Exception {
        dtosForSuccesfullyRegisteredErrorPageWithWildcardErrorCode("5XX", 500);
    }

    public void dtosForSuccesfullyRegisteredErrorPageWithWildcardErrorCode(String code, long startCode) throws Exception {
        this.setupLatches(1);
        registerErrorPage("error page 1", asList(code));
        this.waitForInit();

        HttpServiceRuntime serviceRuntime = getService(HttpServiceRuntime.class);
        assertNotNull("HttpServiceRuntime unavailable", serviceRuntime);

        RuntimeDTO runtimeDTOWithErrorPage = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithErrorPage.failedServletDTOs.length);
        assertEquals(0, runtimeDTOWithErrorPage.failedErrorPageDTOs.length);

        ServletContextDTO contextDTO = assertDefaultContext(runtimeDTOWithErrorPage);
        assertEquals(1, contextDTO.errorPageDTOs.length);
        assertEquals("error page 1", contextDTO.errorPageDTOs[0].name);
        assertContainsAllHundredFrom(startCode, contextDTO.errorPageDTOs[0].errorCodes);
    }

    private void assertContainsAllHundredFrom(Long start, long[] errorCodes) {
        assertEquals(100, errorCodes.length);
        SortedSet<Long> distinctErrorCodes = new TreeSet<>();
        for (Long code : errorCodes)
        {
            distinctErrorCodes.add(code);
        }
        assertEquals(100, distinctErrorCodes.size());
        assertEquals(start, distinctErrorCodes.first());
        assertEquals(Long.valueOf(start + 99), distinctErrorCodes.last());
    }

    @Test
    public void dtosForSuccesfullyRegisteredListeners() throws Exception {
        // register a servlet context listenere as first listener
        registerListener(ServletContextListener.class, true);
        awaitService(ServletContextListener.class);

        HttpServiceRuntime serviceRuntime = getService(HttpServiceRuntime.class);
        assertNotNull("HttpServiceRuntime unavailable", serviceRuntime);

        RuntimeDTO runtimeDTOWithFirstListener = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithFirstListener.failedListenerDTOs.length);

        ServletContextDTO contextDTO = assertDefaultContext(runtimeDTOWithFirstListener);
        assertEquals(1, contextDTO.listenerDTOs.length);
        assertEquals(ServletContextListener.class.getName(), contextDTO.listenerDTOs[0].types[0]);

        // register all other listener types
        registerListener(ServletContextAttributeListener.class, true);
        registerListener(ServletRequestListener.class, true);
        registerListener(ServletRequestAttributeListener.class, true);
        registerListener(HttpSessionListener.class, true);
        registerListener(HttpSessionAttributeListener.class, true);

        awaitService(ServletContextAttributeListener.class);
        awaitService(ServletRequestListener.class);
        awaitService(ServletRequestAttributeListener.class);
        awaitService(HttpSessionListener.class);
        awaitService(HttpSessionAttributeListener.class);

        RuntimeDTO runtimeDTOWithAllListeners = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithAllListeners.failedListenerDTOs.length);

        contextDTO = assertDefaultContext(runtimeDTOWithAllListeners);

        assertEquals(6, contextDTO.listenerDTOs.length);
        assertEquals(ServletContextListener.class.getName(), contextDTO.listenerDTOs[0].types[0]);
        assertEquals(ServletContextAttributeListener.class.getName(), contextDTO.listenerDTOs[1].types[0]);
        assertEquals(ServletRequestListener.class.getName(), contextDTO.listenerDTOs[2].types[0]);
        assertEquals(ServletRequestAttributeListener.class.getName(), contextDTO.listenerDTOs[3].types[0]);
        assertEquals(HttpSessionListener.class.getName(), contextDTO.listenerDTOs[4].types[0]);
        assertEquals(HttpSessionAttributeListener.class.getName(), contextDTO.listenerDTOs[5].types[0]);
    }

    @Test
    public void dtosForSuccesfullyRegisteredContexts() throws Exception {
        // register first additional context
        registerContext("contextA", "/contextA");

        HttpServiceRuntime serviceRuntime = getService(HttpServiceRuntime.class);
        assertNotNull("HttpServiceRuntime unavailable", serviceRuntime);

        RuntimeDTO runtimeDTOWithAdditionalContext = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithAdditionalContext.failedServletContextDTOs.length);
        assertEquals(3, runtimeDTOWithAdditionalContext.servletContextDTOs.length);

        // default context is last, as it has the lowest service ranking
        assertEquals(HTTP_CONTEXT_NAME, runtimeDTOWithAdditionalContext.servletContextDTOs[0].name);
        assertEquals("", runtimeDTOWithAdditionalContext.servletContextDTOs[0].contextPath);
        assertEquals("contextA", runtimeDTOWithAdditionalContext.servletContextDTOs[1].name);
        assertEquals("/contextA", runtimeDTOWithAdditionalContext.servletContextDTOs[1].contextPath);
        assertEquals("default", runtimeDTOWithAdditionalContext.servletContextDTOs[2].name);
        assertEquals("", runtimeDTOWithAdditionalContext.servletContextDTOs[2].contextPath);

        // register second additional context
        registerContext("contextB", "/contextB");

        RuntimeDTO runtimeDTOWithAllContexts = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTOWithAllContexts.failedServletContextDTOs.length);
        assertEquals(4, runtimeDTOWithAllContexts.servletContextDTOs.length);

        // default context is last, as it has the lowest service ranking
        assertEquals(HTTP_CONTEXT_NAME, runtimeDTOWithAdditionalContext.servletContextDTOs[0].name);
        assertEquals("", runtimeDTOWithAdditionalContext.servletContextDTOs[0].contextPath);
        assertEquals("contextA", runtimeDTOWithAllContexts.servletContextDTOs[1].name);
        assertEquals("/contextA", runtimeDTOWithAllContexts.servletContextDTOs[1].contextPath);
        assertEquals("contextB", runtimeDTOWithAllContexts.servletContextDTOs[2].name);
        assertEquals("/contextB", runtimeDTOWithAllContexts.servletContextDTOs[2].contextPath);
        assertEquals("default", runtimeDTOWithAllContexts.servletContextDTOs[3].name);
        assertEquals("", runtimeDTOWithAllContexts.servletContextDTOs[3].contextPath);
    }

    @Test
    public void successfulSetup() throws InterruptedException {
        long counter = this.getRuntimeCounter();

        registerContext("test-context", "/test-context");

        counter = this.waitForRuntime(counter);

        registerServlet("default servlet", "/default");
        counter = this.waitForRuntime(counter);

        registerFilter("default filter", "/default");
        counter = this.waitForRuntime(counter);

        registerErrorPage("default error page", asList(Exception.class.getName()));
        counter = this.waitForRuntime(counter);

        registerResource("/", "/default/resource");
        counter = this.waitForRuntime(counter);

        registerListener(ServletRequestListener.class, true);
        counter = this.waitForRuntime(counter);

        registerServlet("context servlet", "/default", "(" + HTTP_WHITEBOARD_CONTEXT_NAME + "=test-context)");
        counter = this.waitForRuntime(counter);

        registerFilter("context filter", "/default", "(" + HTTP_WHITEBOARD_CONTEXT_NAME + "=test-context)");
        counter = this.waitForRuntime(counter);

        registerErrorPage("context error page", asList("500"), "(" + HTTP_WHITEBOARD_CONTEXT_NAME + "=test-context)");
        counter = this.waitForRuntime(counter);

        registerResource("/", "/test-contextd/resource", "(" + HTTP_WHITEBOARD_CONTEXT_NAME + "=test-context)");
        counter = this.waitForRuntime(counter);

        registerListener(ServletRequestListener.class, true, "(" + HTTP_WHITEBOARD_CONTEXT_NAME + "=test-context)");
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        final RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTO.failedErrorPageDTOs.length);
        assertEquals(0, runtimeDTO.failedFilterDTOs.length);
        assertEquals(0, runtimeDTO.failedListenerDTOs.length);
        assertEquals(0, runtimeDTO.failedResourceDTOs.length);
        assertEquals(0, runtimeDTO.failedServletContextDTOs.length);
        assertEquals(0, runtimeDTO.failedServletDTOs.length);

        assertEquals(3, runtimeDTO.servletContextDTOs.length);
        assertEquals(HTTP_CONTEXT_NAME, runtimeDTO.servletContextDTOs[0].name);
        assertEquals("test-context", runtimeDTO.servletContextDTOs[1].name);
        assertEquals("default", runtimeDTO.servletContextDTOs[2].name);

        ServletContextDTO defaultContextDTO = runtimeDTO.servletContextDTOs[2];
        long contextServiceId = defaultContextDTO.serviceId;

        assertEquals(Arrays.toString(defaultContextDTO.servletDTOs), 2, defaultContextDTO.servletDTOs.length);
        assertServlet(defaultContextDTO.servletDTOs, "default servlet", contextServiceId);
        assertServlet(defaultContextDTO.servletDTOs, "default error page", contextServiceId);

        assertEquals(1, defaultContextDTO.filterDTOs.length);
        assertEquals("default filter", defaultContextDTO.filterDTOs[0].name);
        assertEquals(contextServiceId, defaultContextDTO.filterDTOs[0].servletContextId);
        assertEquals(1, defaultContextDTO.errorPageDTOs.length);
        assertEquals(Exception.class.getName(), defaultContextDTO.errorPageDTOs[0].exceptions[0]);
        assertEquals(contextServiceId, defaultContextDTO.errorPageDTOs[0].servletContextId);
        assertEquals(1, defaultContextDTO.listenerDTOs.length);
        assertEquals(ServletRequestListener.class.getName(), defaultContextDTO.listenerDTOs[0].types[0]);
        assertEquals(contextServiceId, defaultContextDTO.listenerDTOs[0].servletContextId);

        ServletContextDTO testContextDTO = runtimeDTO.servletContextDTOs[1];
        contextServiceId = testContextDTO.serviceId;

        assertEquals(2, testContextDTO.servletDTOs.length);
        assertServlet(testContextDTO.servletDTOs, "context servlet", contextServiceId);
        assertServlet(testContextDTO.servletDTOs, "context error page", contextServiceId);

        assertEquals(1, testContextDTO.filterDTOs.length);
        assertEquals("context filter", testContextDTO.filterDTOs[0].name);
        assertEquals(contextServiceId, testContextDTO.filterDTOs[0].servletContextId);
        assertEquals(1, testContextDTO.errorPageDTOs.length);
        assertEquals(500L, testContextDTO.errorPageDTOs[0].errorCodes[0]);
        assertEquals(contextServiceId, testContextDTO.errorPageDTOs[0].servletContextId);
        assertEquals(1, testContextDTO.listenerDTOs.length);
        assertEquals(ServletRequestListener.class.getName(), testContextDTO.listenerDTOs[0].types[0]);
        assertEquals(contextServiceId, testContextDTO.listenerDTOs[0].servletContextId);
    }

    private void assertServlet(final ServletDTO[] servletDTOs,
    		final String name,
    		final long contextServiceId) {
    	assertNotNull(servletDTOs);
    	for(final ServletDTO dto : servletDTOs) {
    		if ( name.equals(dto.name) && contextServiceId == dto.servletContextId ) {
    			return;
    		}
    	}
    	fail("Servlet with name " + name + " and context id " + contextServiceId + " not found in " + Arrays.toString(servletDTOs));
	}

	@Test
    public void exceptionInServletInitAppearsAsFailure() throws ServletException, InterruptedException {
        Dictionary<String, ?> properties = createDictionary(
                HTTP_WHITEBOARD_SERVLET_PATTERN, "/servlet",
                HTTP_WHITEBOARD_SERVLET_NAME, "servlet");

        long counter = this.getRuntimeCounter();

        @SuppressWarnings("serial")
        Servlet failingServlet = new TestServlet() {
            @Override
            public void init() throws ServletException {
                super.init();
                throw new ServletException();
            }
        };

        registrations.add(m_context.registerService(Servlet.class.getName(), failingServlet, properties));
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();
        assertEquals(1, runtimeDTO.failedServletDTOs.length);
        assertEquals("servlet", runtimeDTO.failedServletDTOs[0].name);
        assertEquals(FAILURE_REASON_EXCEPTION_ON_INIT, runtimeDTO.failedServletDTOs[0].failureReason);
    }

    @Test
    public void exceptionInServletInitDuringServletRemovalAppearsAsFailure() throws ServletException, InterruptedException {
        Dictionary<String, ?> properties1 = createDictionary(
            HTTP_WHITEBOARD_SERVLET_PATTERN, "/servlet1",
            HTTP_WHITEBOARD_SERVLET_NAME, "servlet1");

        long counter = this.getRuntimeCounter();

        @SuppressWarnings("serial")
        Servlet failingServlet1 = new TestServlet() {
            boolean isInit = false;
            @Override
            public void init() throws ServletException {
                //fail when initialized the second time
                if (isInit) {
                    throw new ServletException();
                }
                isInit = true;
                super.init();
            }
        };

        Dictionary<String, ?> properties2 = createDictionary(
            HTTP_WHITEBOARD_SERVLET_PATTERN, "/servlet2",
            HTTP_WHITEBOARD_SERVLET_NAME, "servlet2");

        @SuppressWarnings("serial")
        Servlet failingServlet2 = new TestServlet() {
            boolean isInit = false;
            @Override
            public void init() throws ServletException {
                //fail when initialized the second time
                if (isInit) {
                    throw new ServletException();
                }
                isInit = true;
                super.init();
            }
        };

        Dictionary<String, ?> propertiesShadowing = createDictionary(
            HTTP_WHITEBOARD_SERVLET_PATTERN, asList("/servlet1", "/servlet2"),
            HTTP_WHITEBOARD_SERVLET_NAME, "servletShadowing",
            SERVICE_RANKING, Integer.MAX_VALUE);

        Servlet servletShadowing = new TestServlet();

        registrations.add(m_context.registerService(Servlet.class.getName(), failingServlet1, properties1));
        counter = this.waitForRuntime(counter);
        registrations.add(m_context.registerService(Servlet.class.getName(), failingServlet2, properties2));
        counter = this.waitForRuntime(counter);

        ServiceRegistration<?> shadowingRegistration = m_context.registerService(Servlet.class.getName(), servletShadowing, propertiesShadowing);
        registrations.add(shadowingRegistration);
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();
        assertEquals(2, runtimeDTO.failedServletDTOs.length);
        assertEquals(FAILURE_REASON_SHADOWED_BY_OTHER_SERVICE, runtimeDTO.failedServletDTOs[0].failureReason);
        assertEquals(FAILURE_REASON_SHADOWED_BY_OTHER_SERVICE, runtimeDTO.failedServletDTOs[1].failureReason);

        shadowingRegistration.unregister();
        counter = this.waitForRuntime(counter);

        runtimeDTO = serviceRuntime.getRuntimeDTO();
        assertEquals(2, runtimeDTO.failedServletDTOs.length);
        assertEquals(FAILURE_REASON_EXCEPTION_ON_INIT, runtimeDTO.failedServletDTOs[0].failureReason);
        assertEquals(FAILURE_REASON_EXCEPTION_ON_INIT, runtimeDTO.failedServletDTOs[1].failureReason);
    }

    @Test
    public void exceptionInFilterInitAppearsAsFailure() throws ServletException, InterruptedException {
        Dictionary<String, ?> properties = createDictionary(
                HTTP_WHITEBOARD_FILTER_PATTERN, "/filter",
                HTTP_WHITEBOARD_FILTER_NAME, "filter");

        long counter = this.getRuntimeCounter();

        Filter failingFilter = new TestFilter() {
            @Override
            public void init(FilterConfig config) throws ServletException {
                super.init(config);
                throw new ServletException();
            }
        };

        registrations.add(m_context.registerService(Filter.class.getName(), failingFilter, properties));
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();
        assertEquals(1, runtimeDTO.failedFilterDTOs.length);
        assertEquals("filter", runtimeDTO.failedFilterDTOs[0].name);
        assertEquals(FAILURE_REASON_EXCEPTION_ON_INIT, runtimeDTO.failedFilterDTOs[0].failureReason);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.1
    @Test
    public void hiddenDefaultContextAppearsAsFailure() throws InterruptedException {
        long counter = this.getRuntimeCounter();
        registerContext("default", "");
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();
        assertEquals(1, runtimeDTO.failedServletContextDTOs.length);
        assertEquals("default", runtimeDTO.failedServletContextDTOs[0].name);
        assertDefaultContext(runtimeDTO);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.1
    @Test
    public void contextHelperWithDuplicateNameAppearsAsFailure() throws InterruptedException {
        long counter = this.getRuntimeCounter();
        ServiceRegistration<?> firstContextReg = registerContext("contextA", "/first");
        counter = this.waitForRuntime(counter);
        registerContext("contextA", "/second");
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(1, runtimeDTO.failedServletContextDTOs.length);
        assertEquals("contextA", runtimeDTO.failedServletContextDTOs[0].name);
        assertEquals("/second", runtimeDTO.failedServletContextDTOs[0].contextPath);
        assertEquals(FAILURE_REASON_SHADOWED_BY_OTHER_SERVICE, runtimeDTO.failedServletContextDTOs[0].failureReason);

        assertEquals(3, runtimeDTO.servletContextDTOs.length);
        assertEquals(HTTP_CONTEXT_NAME, runtimeDTO.servletContextDTOs[0].name);
        assertEquals("default", runtimeDTO.servletContextDTOs[2].name);

        assertEquals("contextA", runtimeDTO.servletContextDTOs[1].name);
        assertEquals("/first", runtimeDTO.servletContextDTOs[1].contextPath);

        firstContextReg.unregister();
        counter = this.waitForRuntime(counter);

        runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTO.failedServletContextDTOs.length);

        assertEquals(3, runtimeDTO.servletContextDTOs.length);
        assertEquals(HTTP_CONTEXT_NAME, runtimeDTO.servletContextDTOs[0].name);
        assertEquals("default", runtimeDTO.servletContextDTOs[2].name);

        assertEquals("contextA", runtimeDTO.servletContextDTOs[1].name);
        assertEquals("/second", runtimeDTO.servletContextDTOs[1].contextPath);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.1
    @Test
    public void missingContextHelperNameAppearsAsFailure() {
        Dictionary<String, ?> properties = createDictionary(HTTP_WHITEBOARD_CONTEXT_PATH, "");

        long counter = this.getRuntimeCounter();
        registrations.add(m_context.registerService(ServletContextHelper.class.getName(), mock(ServletContextHelper.class), properties));
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(1, runtimeDTO.failedServletContextDTOs.length);
        assertEquals(null, runtimeDTO.failedServletContextDTOs[0].name);
        assertEquals(FAILURE_REASON_VALIDATION_FAILED, runtimeDTO.failedServletContextDTOs[0].failureReason);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.1
    @Test
    public void invalidContextHelperNameAppearsAsFailure() throws InterruptedException {
        long counter = this.getRuntimeCounter();
        registerContext("context A", "");
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(1, runtimeDTO.failedServletContextDTOs.length);
        assertEquals("context A", runtimeDTO.failedServletContextDTOs[0].name);
        assertEquals(FAILURE_REASON_VALIDATION_FAILED, runtimeDTO.failedServletContextDTOs[0].failureReason);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.1
    @Test
    public void invalidContextHelperPathAppearsAsFailure() throws InterruptedException {
        long counter = this.getRuntimeCounter();
        registerContext("contextA", "#");
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(1, runtimeDTO.failedServletContextDTOs.length);
        assertEquals("#", runtimeDTO.failedServletContextDTOs[0].contextPath);
        assertEquals(FAILURE_REASON_VALIDATION_FAILED, runtimeDTO.failedServletContextDTOs[0].failureReason);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.3
    @Test
    public void selectionOfNonExistingContextHelperAppearsAsFailure() throws InterruptedException {
        long counter = this.getRuntimeCounter();
        registerServlet("servlet 1", "/", "(" + HTTP_WHITEBOARD_CONTEXT_NAME + "=contextA)");
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(1, runtimeDTO.failedServletDTOs.length);
        assertEquals("servlet 1", runtimeDTO.failedServletDTOs[0].name);
        assertEquals(FAILURE_REASON_NO_SERVLET_CONTEXT_MATCHING, runtimeDTO.failedServletDTOs[0].failureReason);

        registerContext("contextA", "/contextA");
        counter = this.waitForRuntime(counter);

        runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTO.failedServletDTOs.length);
        assertEquals(3, runtimeDTO.servletContextDTOs.length);
        assertEquals("contextA", runtimeDTO.servletContextDTOs[1].name);
        assertEquals(1, runtimeDTO.servletContextDTOs[1].servletDTOs.length);
        assertEquals("servlet 1", runtimeDTO.servletContextDTOs[1].servletDTOs[0].name);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.3
    @Test
    public void differentTargetIsIgnored() throws InterruptedException {
        Dictionary<String, ?> properties = createDictionary(
                HTTP_WHITEBOARD_SERVLET_PATTERN, "/servlet",
                HTTP_WHITEBOARD_SERVLET_NAME, "servlet",
                HTTP_WHITEBOARD_TARGET, "(org.osgi.service.http.port=8282)");

        long counter = this.getRuntimeCounter();
        registrations.add(m_context.registerService(Servlet.class.getName(), new TestServlet(), properties));
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTO.failedServletDTOs.length);

        ServletContextDTO defaultContext = assertDefaultContext(runtimeDTO);
        assertEquals(0, defaultContext.servletDTOs.length);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.4
    @Test
    public void servletWithoutNameGetsFullyQualifiedName() throws InterruptedException {
        Dictionary<String, ?> properties = createDictionary(HTTP_WHITEBOARD_SERVLET_PATTERN, "/servlet");

        long counter = this.getRuntimeCounter();
        registrations.add(m_context.registerService(Servlet.class.getName(), new TestServlet(), properties));
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTO.failedServletDTOs.length);

        ServletContextDTO defaultContext = assertDefaultContext(serviceRuntime.getRuntimeDTO());
        assertEquals(1, defaultContext.servletDTOs.length);
        assertEquals(TestServlet.class.getName(), defaultContext.servletDTOs[0].name);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.4.1
    @Test
    public void patternAndErrorPageSpecified() throws InterruptedException {
        Dictionary<String, ?> properties = createDictionary(
                HTTP_WHITEBOARD_SERVLET_PATTERN, "/servlet",
                HTTP_WHITEBOARD_SERVLET_NAME, "servlet",
                HTTP_WHITEBOARD_SERVLET_ERROR_PAGE, asList("400"));

        long counter = this.getRuntimeCounter();
        registrations.add(m_context.registerService(Servlet.class.getName(), new TestServlet(), properties));
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();
        ServletContextDTO defaultContext = assertDefaultContext(runtimeDTO);

        assertEquals(0, runtimeDTO.failedErrorPageDTOs.length);
        assertEquals(0, runtimeDTO.failedServletDTOs.length);

        assertEquals(1, defaultContext.servletDTOs.length);
        assertEquals(1, defaultContext.errorPageDTOs.length);

        assertEquals("servlet", defaultContext.servletDTOs[0].name);
        assertEquals("servlet", defaultContext.errorPageDTOs[0].name);

        assertArrayEquals(new String[] { "/servlet" }, defaultContext.servletDTOs[0].patterns);
        assertArrayEquals(new long[] { 400 }, defaultContext.errorPageDTOs[0].errorCodes);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.4.1
    @Test
    public void multipleServletsForSamePatternChoosenByServiceRankingRules() throws InterruptedException {
        long counter = this.getRuntimeCounter();
        registerServlet("servlet 1", "/pathcollision");
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTO.failedServletDTOs.length);
        ServletContextDTO defaultContext = assertDefaultContext(runtimeDTO);
        assertEquals(1, defaultContext.servletDTOs.length);

        Dictionary<String, ?> properties = createDictionary(
                HTTP_WHITEBOARD_SERVLET_PATTERN, "/pathcollision",
                HTTP_WHITEBOARD_SERVLET_NAME, "servlet 2",
                SERVICE_RANKING, Integer.MAX_VALUE);

        TestServlet testServlet = new TestServlet();
        ServiceRegistration<?> higherRankingServlet = m_context.registerService(Servlet.class.getName(), testServlet, properties);
        registrations.add(higherRankingServlet);
        counter = this.waitForRuntime(counter);

        RuntimeDTO runtimeWithShadowedServlet = serviceRuntime.getRuntimeDTO();

        defaultContext = assertDefaultContext(runtimeWithShadowedServlet);
        assertEquals(1, defaultContext.servletDTOs.length);

        assertEquals(1, runtimeWithShadowedServlet.failedServletDTOs.length);
        FailedServletDTO failedServletDTO = runtimeWithShadowedServlet.failedServletDTOs[0];
        assertEquals("servlet 1", failedServletDTO.name);
        assertEquals(FAILURE_REASON_SHADOWED_BY_OTHER_SERVICE, failedServletDTO.failureReason);

        higherRankingServlet.unregister();
        counter = this.waitForRuntime(counter);

        runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTO.failedServletDTOs.length);
        defaultContext = assertDefaultContext(runtimeDTO);
        assertEquals(1, defaultContext.servletDTOs.length);
        assertEquals("servlet 1", defaultContext.servletDTOs[0].name);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.4.1
    @Test
    public void multipleErrorPagesForSameErrorCodeChoosenByServiceRankingRules() throws InterruptedException {
        long counter = this.getRuntimeCounter();
        registerErrorPage("error page 1", asList(NullPointerException.class.getName(), "500"));
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        ServletContextDTO defaultContext = assertDefaultContext(runtimeDTO);

        assertEquals(0, runtimeDTO.failedErrorPageDTOs.length);
        assertEquals(1, defaultContext.errorPageDTOs.length);

        Dictionary<String, ?> properties = createDictionary(
                HTTP_WHITEBOARD_SERVLET_ERROR_PAGE, asList("500", IllegalArgumentException.class.getName()),
                HTTP_WHITEBOARD_SERVLET_NAME, "error page 2",
                SERVICE_RANKING, Integer.MAX_VALUE);

        TestServlet testServlet = new TestServlet();
        ServiceRegistration<?> higherRankingServlet = m_context.registerService(Servlet.class.getName(), testServlet, properties);
        registrations.add(higherRankingServlet);
        counter = this.waitForRuntime(counter);

        RuntimeDTO runtimeWithShadowedErrorPage = serviceRuntime.getRuntimeDTO();

        defaultContext = assertDefaultContext(runtimeWithShadowedErrorPage);

        assertEquals(2, defaultContext.errorPageDTOs.length);
        assertEquals("error page 2", defaultContext.errorPageDTOs[0].name);
        assertArrayEquals(new long[] { 500 }, defaultContext.errorPageDTOs[0].errorCodes);
        assertArrayEquals(new String[] { IllegalArgumentException.class.getName() }, defaultContext.errorPageDTOs[0].exceptions);
        assertEquals("error page 1", defaultContext.errorPageDTOs[1].name);
        assertEquals(0, defaultContext.errorPageDTOs[1].errorCodes.length);
        assertArrayEquals(new String[] { NullPointerException.class.getName() }, defaultContext.errorPageDTOs[1].exceptions);

        assertEquals(1, runtimeWithShadowedErrorPage.failedErrorPageDTOs.length);
        FailedErrorPageDTO failedErrorPageDTO = runtimeWithShadowedErrorPage.failedErrorPageDTOs[0];
        assertEquals("error page 1", failedErrorPageDTO.name);
        assertArrayEquals(new long[] { 500 }, failedErrorPageDTO.errorCodes);
        assertEquals(0, failedErrorPageDTO.exceptions.length);
        assertEquals(FAILURE_REASON_SHADOWED_BY_OTHER_SERVICE, failedErrorPageDTO.failureReason);

        higherRankingServlet.unregister();
        counter = this.waitForRuntime(counter);

        runtimeDTO = serviceRuntime.getRuntimeDTO();

        defaultContext = assertDefaultContext(runtimeDTO);

        assertEquals(0, runtimeDTO.failedErrorPageDTOs.length);
        assertEquals(1, defaultContext.errorPageDTOs.length);
        assertEquals("error page 1", defaultContext.errorPageDTOs[0].name);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.7
    @Test
    public void invalidListenerPopertyValueAppearsAsFailure() throws Exception {
        Dictionary<String, ?> properties = createDictionary(HTTP_WHITEBOARD_LISTENER, "invalid");

        registrations.add(m_context.registerService(ServletRequestListener.class.getName(), mock(ServletRequestListener.class), properties));

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(1, runtimeDTO.failedListenerDTOs.length);
        assertEquals(FAILURE_REASON_VALIDATION_FAILED, runtimeDTO.failedListenerDTOs[0].failureReason);
    }

    // As specified in OSGi Compendium Release 6, Chapter 140.8
    @Test
    public void contextReplacedWithHigherRankingContext() throws Exception {
        long counter = this.getRuntimeCounter();
        ServiceRegistration<?> firstContext = registerContext("test-context", "/first");
        Long firstContextId = (Long) firstContext.getReference().getProperty(Constants.SERVICE_ID);
        counter = this.waitForRuntime(counter);

        registerServlet("servlet", "/servlet", "(" + HTTP_WHITEBOARD_CONTEXT_NAME + "=test-context)");
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTO.failedServletContextDTOs.length);
        assertEquals(3, runtimeDTO.servletContextDTOs.length);
        assertEquals(firstContextId.longValue(), runtimeDTO.servletContextDTOs[1].serviceId);
        assertEquals("test-context", runtimeDTO.servletContextDTOs[1].name);
        assertEquals("/first", runtimeDTO.servletContextDTOs[1].contextPath);
        assertEquals("default", runtimeDTO.servletContextDTOs[2].name);
        assertEquals(HTTP_CONTEXT_NAME, runtimeDTO.servletContextDTOs[0].name);

        assertEquals(1, runtimeDTO.servletContextDTOs[1].servletDTOs.length);
        assertEquals("servlet", runtimeDTO.servletContextDTOs[1].servletDTOs[0].name);

        Dictionary<String, ?> properties = createDictionary(
                HTTP_WHITEBOARD_CONTEXT_NAME, "test-context",
                HTTP_WHITEBOARD_CONTEXT_PATH, "/second",
                SERVICE_RANKING, Integer.MAX_VALUE);

        ServiceRegistration<?> secondContext = m_context.registerService(ServletContextHelper.class.getName(), mock(ServletContextHelper.class), properties);
        registrations.add(secondContext);
        Long secondContextId = (Long) secondContext.getReference().getProperty(Constants.SERVICE_ID);
        counter = this.waitForRuntime(counter);

        runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(1, runtimeDTO.failedServletContextDTOs.length);
        assertEquals(firstContextId.longValue(), runtimeDTO.failedServletContextDTOs[0].serviceId);
        assertEquals("test-context", runtimeDTO.failedServletContextDTOs[0].name);
        assertEquals("/first", runtimeDTO.failedServletContextDTOs[0].contextPath);

        assertEquals(3, runtimeDTO.servletContextDTOs.length);

        final List<String> names = new ArrayList<>();
        for(final ServletContextDTO dto : runtimeDTO.servletContextDTOs)
        {
            names.add(dto.name);
        }
        final int httpContextIndex = names.indexOf(HTTP_CONTEXT_NAME);
        final int secondContextIndex = names.indexOf("test-context");
        final int defaultContextIndex = names.indexOf("default");
        assertEquals(secondContextId.longValue(), runtimeDTO.servletContextDTOs[secondContextIndex].serviceId);
        assertEquals("test-context", runtimeDTO.servletContextDTOs[secondContextIndex].name);
        assertEquals("/second", runtimeDTO.servletContextDTOs[secondContextIndex].contextPath);
        assertEquals("default", runtimeDTO.servletContextDTOs[defaultContextIndex].name);
        assertEquals(HTTP_CONTEXT_NAME, runtimeDTO.servletContextDTOs[httpContextIndex].name);

        assertEquals(1, runtimeDTO.servletContextDTOs[secondContextIndex].servletDTOs.length);
        assertEquals("servlet", runtimeDTO.servletContextDTOs[secondContextIndex].servletDTOs[0].name);

        secondContext.unregister();
        counter = this.waitForRuntime(counter);

        runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTO.failedServletContextDTOs.length);
        assertEquals(3, runtimeDTO.servletContextDTOs.length);
        assertEquals(firstContextId.longValue(), runtimeDTO.servletContextDTOs[1].serviceId);
        assertEquals("test-context", runtimeDTO.servletContextDTOs[1].name);
        assertEquals("/first", runtimeDTO.servletContextDTOs[1].contextPath);
        assertEquals("default", runtimeDTO.servletContextDTOs[2].name);
        assertEquals(HTTP_CONTEXT_NAME, runtimeDTO.servletContextDTOs[0].name);

        assertEquals(1, runtimeDTO.servletContextDTOs[1].servletDTOs.length);
        assertEquals("servlet", runtimeDTO.servletContextDTOs[1].servletDTOs[0].name);
    }

    @Test
    public void namedServletIsNotIgnored() throws InterruptedException {
        // Neither pattern nor error page specified
        Dictionary<String, ?> properties = createDictionary(HTTP_WHITEBOARD_SERVLET_NAME, "servlet");

        long counter = this.getRuntimeCounter();
        registrations.add(m_context.registerService(Servlet.class.getName(), new TestServlet(), properties));
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTO.failedServletContextDTOs.length);
        ServletContextDTO defaultContext = assertDefaultContext(runtimeDTO);
        assertEquals(1, defaultContext.servletDTOs.length);
        assertEquals(0, defaultContext.servletDTOs[0].patterns.length);
        assertEquals("servlet", defaultContext.servletDTOs[0].name);
    }

    @Test
    public void dtosAreIndependentCopies() throws Exception {
        //register first servlet
        Dictionary<String, ?> properties = createDictionary(
                HTTP_WHITEBOARD_SERVLET_PATTERN, "/test",
                HTTP_WHITEBOARD_SERVLET_NAME, "servlet 1",
                HTTP_WHITEBOARD_SERVLET_INIT_PARAM_PREFIX + "test", "testValue");

        long counter = this.getRuntimeCounter();
        registrations.add(m_context.registerService(Servlet.class.getName(), new TestServlet(), properties));
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTOWithFirstSerlvet = serviceRuntime.getRuntimeDTO();

        //register second servlet
        registerServlet("testServlet 2", "/servlet_2");
        counter = this.waitForRuntime(counter);

        RuntimeDTO runtimeDTOWithTwoSerlvets = serviceRuntime.getRuntimeDTO();

        assertNotSame(runtimeDTOWithFirstSerlvet, runtimeDTOWithTwoSerlvets);

        ServletContextDTO defaultContextFirstServlet = assertDefaultContext(runtimeDTOWithFirstSerlvet);
        ServletContextDTO defaultContextTwoServlets = assertDefaultContext(runtimeDTOWithTwoSerlvets);
        assertNotSame(defaultContextFirstServlet.servletDTOs[0].patterns,
                defaultContextTwoServlets.servletDTOs[0].patterns);

        boolean mapsModifiable = true;
        try {
            defaultContextTwoServlets.servletDTOs[0].initParams.clear();
        } catch (UnsupportedOperationException e) {
            mapsModifiable = false;
        }

        if (mapsModifiable) {
            assertNotSame(defaultContextFirstServlet.servletDTOs[0].initParams,
                    defaultContextTwoServlets.servletDTOs[0].initParams);
        }
    }

    @Test
    public void requestInfoDTO() throws Exception {
        long counter = this.getRuntimeCounter();
        registerServlet("servlet", "/default");
        counter = this.waitForRuntime(counter);
        registerFilter("filter1", "/default");
        counter = this.waitForRuntime(counter);
        registerFilter("filter2", "/default");
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        ServletContextDTO defaultContext = assertDefaultContext(serviceRuntime.getRuntimeDTO());
        long defaultContextId = defaultContext.serviceId;

        RequestInfoDTO requestInfoDTO = serviceRuntime.calculateRequestInfoDTO("/default");
        assertEquals("/default", requestInfoDTO.path);
        assertEquals(defaultContextId, requestInfoDTO.servletContextId);
        assertEquals("servlet", requestInfoDTO.servletDTO.name);
        assertEquals(2, requestInfoDTO.filterDTOs.length);
        assertEquals("filter1", requestInfoDTO.filterDTOs[0].name);
        assertEquals("filter2", requestInfoDTO.filterDTOs[1].name);
    }

    @Test
    public void serviceEndpointPropertyIsSet() {
        // if there is more than one network interface, there might be more than one endpoint!
        final String[] endpoint = (String[]) m_context.getServiceReference(HttpServiceRuntime.class).getProperty(HTTP_SERVICE_ENDPOINT);
        assertNotNull(endpoint);
        assertTrue(Arrays.toString(endpoint), endpoint.length > 0);
        assertTrue(endpoint[0].startsWith("http://"));
        assertTrue(endpoint[0].endsWith(":8080/"));
    }

    /**
     * Test for FELIX-5319
     * @throws Exception
     */
    @Test
    public void testCombinedServletAndResourceRegistration() throws Exception {
        long counter = this.getRuntimeCounter();
        // register single component as Servlet and Resource
        final String servletPath = "/hello/sayHello";
        final String servletName = "Hello World";
        final String rsrcPattern = "/hello/static/*";
        final String rsrcPrefix = "/static";

        List<Object> propertyEntries = Arrays.<Object>asList(
                HTTP_WHITEBOARD_SERVLET_PATTERN, servletPath,
                HTTP_WHITEBOARD_SERVLET_NAME, servletName,
                HTTP_WHITEBOARD_RESOURCE_PATTERN, rsrcPattern,
                HTTP_WHITEBOARD_RESOURCE_PREFIX, rsrcPrefix);

        Dictionary<String, ?> properties = createDictionary(propertyEntries.toArray());

        registrations.add(m_context.registerService(Servlet.class.getName(), new TestServlet(), properties));
        counter = this.waitForRuntime(counter);

        final HttpServiceRuntime serviceRuntime = this.getHttpServiceRuntime();

        RuntimeDTO runtimeDTO = serviceRuntime.getRuntimeDTO();

        assertEquals(0, runtimeDTO.failedServletDTOs.length);
        assertEquals(0, runtimeDTO.failedResourceDTOs.length);

        // check servlet registration
        ServletContextDTO contextDTO = assertDefaultContext(runtimeDTO);
        assertEquals(1, contextDTO.servletDTOs.length);
        assertEquals(servletName, contextDTO.servletDTOs[0].name);
        assertEquals(1, contextDTO.servletDTOs[0].patterns.length);
        assertEquals(servletPath, contextDTO.servletDTOs[0].patterns[0]);

        // check resource registration
        assertEquals(1, contextDTO.resourceDTOs.length);
        assertEquals(1, contextDTO.resourceDTOs[0].patterns.length);
        assertEquals(rsrcPattern, contextDTO.resourceDTOs[0].patterns[0]);
        assertEquals(rsrcPrefix, contextDTO.resourceDTOs[0].prefix);
    }

    private ServletContextDTO assertDefaultContext(RuntimeDTO runtimeDTO) {
        assertTrue(1 < runtimeDTO.servletContextDTOs.length);
        assertEquals(HTTP_CONTEXT_NAME, runtimeDTO.servletContextDTOs[0].name);
        assertEquals("default", runtimeDTO.servletContextDTOs[1].name);
        return runtimeDTO.servletContextDTOs[1];
    }

    public static class TestResource {
        // Tagging class
    }
}


text:
package com.github.anba.es6draft.runtime.types;

import com.github.anba.es6draft.runtime.ExecutionContext;

/**
 *
6 ECMAScript Data Types and Values

 *
6.1 ECMAScript Language Types

 *
6.1.7 The Object Type

 *

 *
6.1.7.2 Object Internal Methods and Internal Slots
 *

 *

 * Internal Method: [[Construct]]
 */
public interface Constructor extends ScriptObject, Callable {
    /**
     * [[Construct]]
     *
     * @param callerContext
     *            the caller's execution context
     * @param args
     *            the constructor function arguments
     * @return the new script object
     */
    default ScriptObject construct(ExecutionContext callerContext, Object... args) {
        return construct(callerContext, this, args);
    }

    /**
     * [[Construct]]
     *
     * @param callerContext
     *            the caller's execution context
     * @param newTarget
     *            the constructor to which the {@code new} operator was initially applied
     * @param args
     *            the constructor function arguments
     * @return the new script object
     */
    ScriptObject construct(ExecutionContext callerContext, Constructor newTarget, Object... args);
}

redpajama_set_name: RedPajamaGithub


text:
package com.hrskrs.gesturefun;

import android.view.LayoutInflater;
import android.view.View;

import com.hrskrs.gesturefun.core.BaseFragment;

/**
 * Created by hrskrs
 */
public class MainFragment extends BaseFragment {

    public static MainFragment newInstance() {
        return new MainFragment();
    }

    @Override
    protected int getContentLayoutResId() {
        return R.layout.fragment_main;
    }

    @Override
    protected void populateUI(LayoutInflater inflater, View rooView) {

    }
}


text:
require 'ae'
AE.ansi = false


text:
layout: page
title: About
permalink: /about/
---

Developer from Shanghai, China!

### More Information
My [LinkedIn page](http://www.linkedin.com/in/lei-chen-88b73236?trk=nav_responsive_tab_profile)

### Contact me

[clraychen@gmail.com](mailto:clraychen@gmail.com)


text:
<?php

namespace Kilte\MySQLi\Tests;

/**
 * Class MySQLiTestCase.
 */
class MySQLiTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * Returns MySQLi configuration.
     *
     * @return array
     */
    protected function getMySQLiConfiguration()
    {
        return array(
            'host' => isset($GLOBALS['DB_HOST']) ? $GLOBALS['DB_HOST'] : 'localhost',
            'username' => isset($GLOBALS['DB_USER']) ? $GLOBALS['DB_USER'] : 'root',
            'password' => isset($GLOBALS['DB_PASSWD']) ? $GLOBALS['DB_PASSWD'] : '',
            'database' => isset($GLOBALS['DB_NAME']) ? $GLOBALS['DB_NAME'] : 'silex_user_test',
            'charset' => isset($GLOBALS['DB_CHARSET']) ? $GLOBALS['DB_CHARSET'] : 'utf8',
        );
    }
}


text:
LOG_SETUP("rpc_callback_server");

struct RPC : public FRT_Invokable
{
    void CallBack(FRT_RPCRequest *req);
    void Init(FRT_Supervisor *s);
};

void do_callback(FRT_RPCRequest *req) {
    FNET_Connection *conn = req->GetConnection();
    FRT_RPCRequest *cb = new FRT_RPCRequest();
    cb->SetMethodName(req->GetParams()->GetValue(0)._string._str);
    FRT_Supervisor::InvokeSync(conn->Owner(), conn, cb, 5.0);
    if(cb->IsError()) {
        printf("[error(%d): %s]\n",
               cb->GetErrorCode(),
               cb->GetErrorMessage());
    }
    cb->SubRef();
    req->Return();
}

void
RPC::CallBack(FRT_RPCRequest *req)
{
    req->Detach();
    std::thread(do_callback, req).detach();
}

void
RPC::Init(FRT_Supervisor *s)
{
    FRT_ReflectionBuilder rb(s);
    //-------------------------------------------------------------------
    rb.DefineMethod("callBack", "s", "",
                    FRT_METHOD(RPC::CallBack), this);
    //-------------------------------------------------------------------
}

class MyApp
{
public:
    int main(int argc, char **argv);
};

int
MyApp::main(int argc, char **argv)
{
    FNET_SignalShutDown::hookSignals();
    if (argc < 2) {
        printf("usage  : rpc_server <listenspec>\n");
        return 1;
    }
    RPC rpc;
    fnet::frt::StandaloneFRT server;
    FRT_Supervisor & supervisor = server.supervisor();
    rpc.Init(&supervisor);
    supervisor.Listen(argv[1]);
    FNET_SignalShutDown ssd(*supervisor.GetTransport());
    server.supervisor().GetTransport()->WaitFinished();
    return 0;
}

int main(int argc, char **argv) {
    vespalib::SignalHandler::PIPE.ignore();
    MyApp myapp;
    return myapp.main(argc, argv);
}


text:
#ifndef _gcem_round_HPP
#define _gcem_round_HPP

namespace internal
{

template<typename T>
constexpr
T
round_int(const T x)
noexcept
{
    return static_cast<T>(find_whole(x));
}

template<typename T>
constexpr
T
round_check(const T x)
noexcept
{
    return( // NaN check
            is_nan(x) ? \
                GCLIM<T>::quiet_NaN() :
            // +/- infinite
            !is_finite(x) ? \
                x :
            // signed-zero cases
            GCLIM<T>::epsilon() > abs(x) ? \
                x :
            // else
                sgn(x) * round_int(abs(x)) );
}

}

/**
 * Compile-time round function
 *
 * @param x a real-valued input.
 * @return computes the rounding value of the input.
 */

template<typename T>
constexpr
return_t<T>
round(const T x)
noexcept
{
    return internal::round_check( static_cast<return_t<T>>(x) );
}

#endif


text:
A PAK.MAN file corresponds to the PAK file of the same name.  The PAK.MAN file is used to determine the location of a particular file within a PAK file.

### PakMan Header

A PAK.MAN file has a short header that primarily tells us the root directory and how many total directories are in the file

	typedef struct {
		uint16_t zero;
		uint16_t rootPathLen;
		char16_t rootPath[nameLen];
		uint32_t unknown;
		uint32_t numDirectories;
	} PakManHeader;

``zero`` is a 16-bit integer (equal to 0x0000 in the May preview)
``rootPathLen`` is the length of the rootPath string (in characters)
``rootPath`` is a string containing the path for the 'root' directory
``unknown`` is a 32-bit number of unknown importance
``numDirectories`` is the number of ``Directory`` structures in the PAK.MAN file

### FileInfo

A ``FileInfo`` is a structure that contains information about a file within the PAK archive.

	typedef struct {
		uint32_t unk_0;
		uint8_t fileType;
		uint16_t nameLen;
		char16_t name[nameLen];
		uint32_t offset;
		uint32_t uncompressedSize;
		FILETIME lastModified;
	} FileInfo;

``unk_0`` is 32-bits of data with an unknown purpose
``fileType`` is an 8-bit number specifying what kind of file this ``FileInfo`` references.
``nameLen`` is the length of the file name string (in characters)
``name`` is a string containing the name (and extension if any) for this file
``offset`` is the offset of a ``FileData`` within the associated PAK file that contains the compressed file data
``uncompressedSize`` is the size in bytes of the file after decompression
``lastModified`` is the last time this file was modified, using Windows FILETIME format (64-bits representing 100-nanosecond intervals since Jan 1, 1601)

### Directory

Immediately following the ``PakManHeader`` comes a number of ``Directory`` structures.  These occur one after another until the end of the file.

	typedef struct {
		uint16_t pathLen;
		char16_t path[pathLen];
		uint32_t numFiles;
		FileInfo files[numFiles]
	} FileData;

``pathLen`` is the length of the path string (in characters)
``path`` is a string containing the directory path (e.g. "MEDIA/DUNGEONS/TESTDUNGEONS/")
``numFiles`` is the number of ``FileInfo`` structures for this directory
``files`` is an array of ``numFiles`` ``FileInfo`` structures representing the files and subdirectories under this directory


text:
import numpy
from keras.layers import Input, Embedding
from keras.models import Model

from deep_qa.layers.encoders import BOWEncoder

class TestBOWEncoder:
    def test_on_unmasked_input(self):
        sentence_length = 5
        embedding_dim = 10
        vocabulary_size = 15
        input_layer = Input(shape=(sentence_length,), dtype='int32')
        # Embedding does not mask zeros
        embedding = Embedding(input_dim=vocabulary_size, output_dim=embedding_dim)
        encoder = BOWEncoder()
        embedded_input = embedding(input_layer)
        encoded_input = encoder(embedded_input)
        model = Model(inputs=input_layer, outputs=encoded_input)
        model.compile(loss="mse", optimizer="sgd")  # Will not train this model
        test_input = numpy.asarray([[0, 3, 1, 7, 10]], dtype='int32')
        embedding_weights = embedding.get_weights()[0]  # get_weights returns a list with one element.
        expected_output = numpy.mean(embedding_weights[test_input], axis=1)
        actual_output = model.predict(test_input)
        # Exact comparison of the two arrays may break because theano's floating point operations
        # usually have an epsilon. The following comparison is done till the sixth decimal, hence good enough.
        numpy.testing.assert_array_almost_equal(expected_output, actual_output)

    def test_on_masked_input(self):
        sentence_length = 5
        embedding_dim = 10
        vocabulary_size = 15
        input_layer = Input(shape=(sentence_length,), dtype='int32')
        # Embedding masks zeros
        embedding = Embedding(input_dim=vocabulary_size, output_dim=embedding_dim, mask_zero=True)
        encoder = BOWEncoder()
        embedded_input = embedding(input_layer)
        encoded_input = encoder(embedded_input)
        model = Model(inputs=input_layer, outputs=encoded_input)
        model.compile(loss="mse", optimizer="sgd")  # Will not train this model
        test_input = numpy.asarray([[0, 3, 1, 7, 10]], dtype='int32')
        embedding_weights = embedding.get_weights()[0]  # get_weights returns a list with one element.
        # Omitting the first element (0), because that is supposed to be masked in the model.
        expected_output = numpy.mean(embedding_weights[test_input[:, 1:]], axis=1)
        actual_output = model.predict(test_input)
        # Following comparison is till the sixth decimal.
        numpy.testing.assert_array_almost_equal(expected_output, actual_output)

    def test_on_all_zeros(self):
        sentence_length = 5
        embedding_dim = 10
        vocabulary_size = 15
        input_layer = Input(shape=(sentence_length,), dtype='int32')
        # Embedding masks zeros
        embedding = Embedding(input_dim=vocabulary_size, output_dim=embedding_dim, mask_zero=True)
        encoder = BOWEncoder()
        embedded_input = embedding(input_layer)
        encoded_input = encoder(embedded_input)
        model = Model(inputs=input_layer, outputs=encoded_input)
        model.compile(loss="mse", optimizer="sgd")  # Will not train this model
        test_input = numpy.asarray([[0, 0, 0, 0, 0]], dtype='int32')
        # Omitting the first element (0), because that is supposed to be masked in the model.
        expected_output = numpy.zeros((1, embedding_dim))
        actual_output = model.predict(test_input)
        # Following comparison is till the sixth decimal.
        numpy.testing.assert_array_almost_equal(expected_output, actual_output)


text:
import os
import time

import imath
import IECore
import Gaffer
import GafferScene
import GafferUI
import GafferSceneUI

# Delay for x seconds
def __delay( delay ) :
	endtime = time.time() + delay
	while time.time() < endtime :
		GafferUI.EventLoop.waitForIdle( 1 )

# Default layout's editors
mainWindow = GafferUI.ScriptWindow.acquire( script )
viewer = mainWindow.getLayout().editors( GafferUI.Viewer )[0]
graphEditor = mainWindow.getLayout().editors( GafferUI.GraphEditor )[0]
nodeEditor = mainWindow.getLayout().editors( GafferUI.NodeEditor )[0]
sceneInspector = mainWindow.getLayout().editors( GafferSceneUI.SceneInspector )[0]
hierarchyView = mainWindow.getLayout().editors( GafferSceneUI.HierarchyView )[0]
pythonEditor = mainWindow.getLayout().editors( GafferUI.PythonEditor )[0]

# For simplicity, the screengrabs are generated in reverse order
script["fileName"].setValue( os.path.expandvars( "$GAFFER_ROOT/resources/examples/rendering/multiShotRenderSpreadsheet.gfr" ) )
script.load()
script.removeChild( script["Backdrop"] )
script.removeChild( script["Backdrop1"] )
script.removeChild( script["Backdrop2"] )
sheet = script["Spreadsheet_RenderOptions"]
defaultRow = sheet["rows"]["default"]
row1 = sheet["rows"]["row1"]
row2A = sheet["rows"]["row2"]
row2B = sheet["rows"]["row3"]
row2Other = sheet["rows"]["row4"]

# Tutorial: Finished spreadsheet
nodeEditorWindow = GafferUI.NodeEditor.acquire( sheet, floating = True )
nodeEditorWindow._qtWidget().setFocus()
nodeEditorWindow.parent()._qtWidget().resize( 696, 325 )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = nodeEditorWindow, imagePath = "images/tutorialSettingUpASpreadsheetRow2Other.png" )

# Tutorial: Rows A and 2B
sheet["rows"].removeChild( row2Other )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = nodeEditorWindow, imagePath = "images/tutorialSettingUpASpreadsheetRows2A2B.png" )

# Tutorial: Overscan values
sheet["rows"].removeChild( row2B )
row2 = row2A
row2["name"].setValue( "2" )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = nodeEditorWindow, imagePath = "images/tutorialSettingUpASpreadsheetOverscanValues.png" )

# Tutorial: Spreadsheet name in Graph Editor
nodeEditorWindow.parent()._qtWidget().hide()
with GafferUI.Window() as window :
	graphEditorWindow = GafferUI.GraphEditor( script )
graphEditorWindow.parent().reveal()
graphEditorWindow.parent()._qtWidget().resize( 300, 200 )
__delay( 0.1 )
graphEditorWindow.frame( Gaffer.StandardSet( [ sheet ] ) )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = graphEditorWindow, imagePath = "images/tutorialSettingUpASpreadsheetFullName.png" )
graphEditorWindow.parent().close()
del graphEditorWindow

# Tutorial: Row 2
nodeEditorWindow.parent()._qtWidget().show()
__delay( 0.1 )
sheet["rows"].removeColumn( 5 )
sheet["rows"].removeColumn( 4 )
sheet["rows"].removeColumn( 3 )
sheet["rows"].removeColumn( 2 )
sheet["rows"].removeColumn( 1 )
row2["name"].setValue( "2" )
row2["cells"]["maxAASamples"].enabledPlug().setValue( True )
row2["cells"]["maxAASamples"]["value"]["value"].setValue( 36 )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = nodeEditorWindow, imagePath = "images/tutorialSettingUpASpreadsheetRow2.png" )

# Tutorial: Clean column
sheet["rows"].removeRow( row2 )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = nodeEditorWindow, imagePath = "images/tutorialSettingUpASpreadsheetCleanColumn.png" )

# Tutorial: Default cell
Gaffer.Metadata.registerValue( defaultRow["cells"]["maxAASamples"], 'spreadsheet:columnWidth', 100 )
Gaffer.Metadata.registerValue( defaultRow["cells"]["maxAASamples"], 'spreadsheet:columnLabel', 'Max AA Samples' )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = nodeEditorWindow, imagePath = "images/tutorialSettingUpASpreadsheetDefaultCell.png" )

# Tutorial: Filled row 1
defaultRow["cells"]["maxAASamples"].enabledPlug().setValue( False )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = nodeEditorWindow, imagePath = "images/tutorialSettingUpASpreadsheetRow1.png" )

# Tutorial: Selector plug
row1["name"].setValue( "" )
row1["cells"]["maxAASamples"]["value"]["value"].setValue( 32 )
row1["cells"]["maxAASamples"].enabledPlug().setValue( False )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = nodeEditorWindow, imagePath = "images/tutorialSettingUpASpreadsheetSelector.png" )

# Tutorial: New spreadsheet
sheet["selector"].setValue( "" )
script.selection().add( Gaffer.StandardSet( [ script["AppleseedOptions"] ] ) )
GafferUI.PlugValueWidget.acquire( script["AppleseedOptions"]["options"]["maxAASamples"] )
pos = nodeEditorWindow.parent()._qtWidget().pos()
pos.setX( pos.x() - 150 )
nodeEditorWindow.parent()._qtWidget().move( pos )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = mainWindow, imagePath = "images/tutorialSettingUpASpreadsheetNewSpreadsheet.png" )
script.selection().clear()

# Tutorial: Global Context Variables
nodeEditorWindow.parent().close()
del nodeEditorWindow
script.removeChild( sheet )
del sheet
GafferUI.FileMenu.showSettings( mainWindow.getLayout() )
settingsWindow = mainWindow.childWindows()[0]
settingsWindow.getChild().plugValueWidget( script["variables"] ).reveal()
settingsWindow.setVisible( True )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = settingsWindow, imagePath = "images/tutorialSettingUpASpreadsheetGlobalContextVariables.png" )
settingsWindow.close()
del settingsWindow

# Tutorial: AppleseedOptions node
with GafferUI.Window() as window :
	graphEditorWindow = GafferUI.GraphEditor( script )
graphEditorWindow.parent().reveal()
graphEditorWindow.parent()._qtWidget().resize( 300, 200 )
__delay( 0.1 )
graphEditorWindow.frame( script.children( Gaffer.Node ) )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = graphEditorWindow, imagePath = "images/tutorialSettingUpASpreadsheetAppleseedOptionsNode.png" )

# Tutorial: StandardOptions node
script.removeChild( script["AppleseedOptions"] )
graphEditorWindow.frame( script.children( Gaffer.Node ) )
__delay( 0.1 )
GafferUI.WidgetAlgo.grab( widget = graphEditorWindow, imagePath = "images/tutorialSettingUpASpreadsheetStandardOptionsNode.png" )


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE language SYSTEM "language.dtd">
<language name="Verilog" version="2" kateversion="2.4" section="Hardware" extensions="*.v;*.V;*.vl" mimetype="text/x-verilog-src" author="Yevgen Voronenko (ysv22@drexel.edu), Ryan Dalzell (ryan@tullyroan.com)" license="">
  <highlighting>
    <list name="keywords">
      <item>macromodule</item>
      <item>table</item>
      <item>endtable</item>
      <item>specify</item>
      <item>specparam</item>
      <item>endspecify</item>

      <item>defparam</item>
      <item>default</item>
      <item>if</item>
      <item>ifnone</item>
      <item>else</item>
      <item>forever</item>
      <item>while</item>
      <item>for</item>
      <item>wait</item>
      <item>repeat</item>
      <item>disable</item>

      <item>assign</item>
      <item>deassign</item>
      <item>force</item>
      <item>release</item>

      <item>always</item>
      <item>initial</item>
      <item>edge</item>
      <item>posedge</item>
      <item>negedge</item>

      <!-- verilog-2001 keywords -->
      <item>config</item>
      <item>endconfig</item>
      <item>library</item>
      <item>design</item>
      <item>liblist</item>
      <item>cell</item>
      <item>use</item>
      <item>instance</item>
    </list>

    <list name="beginwords">
        <item>begin</item>
        <item>fork</item>
        <item>module</item>
        <item>case</item>
        <item>casex</item>
        <item>casez</item>
        <item>task</item>
        <item>function</item>
        <item>generate</item>
    </list>

    <list name="endwords">
        <item>end</item>
        <item>join</item>
        <item>endmodule</item>
        <item>endcase</item>
        <item>endtask</item>
        <item>endfunction</item>
        <item>endgenerate</item>
    </list>

    <list name="strength">
	<!-- drive strength supply0/supply1 omitted, its in types.. -->
	<item>strong0</item>
	<item>strong1</item>
	<item>pull0</item>
	<item>pull1</item>
	<item>weak0</item>
	<item>weak1</item>
	<item>highz0</item>
	<item>highz1</item>
	<!-- charge strength -->
	<item>small</item>
	<item>medium</item>
	<item>large</item>
    </list>

    <list name="gates">
       <item>pullup</item>
       <item>pulldown</item>
       <item>cmos</item>
       <item>rcmos</item>
       <item>nmos</item>
       <item>pmos</item>
       <item>rnmos</item>
       <item>rpmos</item>
       <item>and</item>
       <item>nand</item>
       <item>or</item>
       <item>nor</item>
       <item>xor</item>
       <item>xnor</item>
       <item>not</item>
       <item>buf</item>
       <item>tran</item>
       <item>rtran</item>
       <item>tranif0</item>
       <item>tranif1</item>
       <item>rtranif0</item>
       <item>rtranif1</item>
       <item>bufif0</item>
       <item>bufif1</item>
       <item>notif0</item>
       <item>notif1</item>
    </list>

    <list name="types">
      <!-- port direction -->
      <item>input</item>
      <item>output</item>
      <item>inout</item>
      <!-- net type -->
      <item>wire</item>
      <item>tri</item>
      <item>tri0</item>
      <item>tri1</item>
      <item>wand</item>
      <item>wor</item>
      <item>triand</item>
      <item>trior</item>
      <item>supply0</item>
      <item>supply1</item>
      <!-- reg/variable -->
      <item>reg</item>
      <item>integer</item>
      <item>real</item>
      <item>realtime</item>
      <item>time</item>
      <!-- modifier -->
      <item>vectored</item>
      <item>scalared</item>
      <item>trireg</item>
      <!-- other -->
      <item>parameter</item>
      <item>event</item>
      <!-- verilog-2001 types -->
      <item>signed</item>
      <item>automatic</item>
      <item>genvar</item>
      <item>localparam</item>
    </list>

    <contexts>
      <context attribute="Normal Text" lineEndContext="#stay" name="Normal">
        <DetectSpaces />
        <RegExpr attribute="Keyword" context="Block name" String="begin\ *:" beginRegion="Block"/>
        <RegExpr attribute="Keyword" context="Block name" String="fork\ *:" beginRegion="Block"/>
        <keyword attribute="Keyword" String="beginwords" context="#stay" beginRegion="Block"/>
        <keyword attribute="Keyword" String="endwords" context="#stay" endRegion="Block"/>

        <keyword attribute="Keyword" context="#stay" String="keywords" />
        <keyword attribute="Data Type" context="#stay" String="types" />
        <keyword attribute="Drive/charge strength" context="#stay" String="strength" />
        <keyword attribute="Gate instantiation" context="#stay" String="gates" />

        <RegExpr attribute="Decimal" context="#stay" String="[\d_]*'d[\d_]+"/>
        <RegExpr attribute="Octal" context="#stay" String="[\d_]*'o[0-7xXzZ_]+"/>
        <RegExpr attribute="Hex" context="#stay" String="[\d_]*'h[\da-fA-FxXzZ_]+"/>
        <RegExpr attribute="Binary" context="#stay" String="[\d_]*'b[01_zZxX]+"/>
        <Float attribute="Float" context="#stay"/>
        <Int attribute="Integer" context="#stay" />

        <RegExpr attribute="Case label" context="#stay" String="[a-zA-Z0-9_, \t]+\s*:" firstNonSpace="true"/>
        <!--<RegExpr attribute="Port map" context="Port" String="\.[a-zA-Z0-9_]+"/>-->

        <DetectChar attribute="String" context="String" char="""/>
        <Detect2Chars attribute="Comment" context="Commentar 1" char="/" char1="/"/>
        <Detect2Chars attribute="Comment" context="Commentar 2" char="/" char1="*" beginRegion="Comment"/>
        <AnyChar attribute="Symbol" context="#stay" String="!%&()+,-<=+/:;>?[]^{|}~@"/>

        <DetectChar attribute="Preprocessor" context="Preprocessor" char="`" column="0"/>
        <RegExpr attribute="Preprocessor" context="#stay" String="\`[a-zA-Z_]+\w*" />
        <RegExpr attribute="System Task" context="#stay" String="\$[a-zA-Z_]+\w*" />
        <RegExpr attribute="Delay" context="#stay" String="#[\d_]+" />

      </context>
      <context attribute="String" lineEndContext="#pop" name="String">
        <LineContinue attribute="String" context="Some Context"/>
        <HlCStringChar attribute="String Char" context="#stay"/>
        <DetectChar attribute="String" context="#pop" char="""/>
      </context>
      <context attribute="Comment" lineEndContext="#pop" name="Commentar 1">
        <IncludeRules context="##Alerts" />
      </context>
      <context attribute="Comment" lineEndContext="#stay" name="Commentar 2">
        <IncludeRules context="##Alerts" />
        <Detect2Chars attribute="Comment" context="#pop" char="*" char1="/" endRegion="Comment"/>
      </context>
      <context attribute="Preprocessor" lineEndContext="#pop" name="Preprocessor">
        <LineContinue attribute="Preprocessor" context="Some Context"/>
        <RangeDetect attribute="Prep. Lib" context="#stay" char=""" char1="""/>
        <RangeDetect attribute="Prep. Lib" context="#stay" char="<" char1=">"/>
        <Detect2Chars attribute="Comment" context="Commentar 1" char="/" char1="/"/>
        <Detect2Chars attribute="Comment" context="Commentar/Preprocessor" char="/" char1="*"/>
      </context>
      <context attribute="Comment" lineEndContext="#stay" name="Commentar/Preprocessor">
        <Detect2Chars attribute="Comment" context="#pop" char="*" char1="/" />
      </context>
      <context attribute="Normal Text" lineEndContext="#pop" name="Some Context"/>
      <context attribute="Comment" lineEndContext="#stay" name="Some Context2">
          <IncludeRules context="##Alerts" />
          <StringDetect attribute="Comment" context="#pop" String="#endif" firstNonSpace="true"/>
      </context>

      <context attribute="Block name" lineEndContext="#pop" name="Block name">
          <DetectIdentifier attribute="Data Type" context="#pop"/>
      </context>

      <context attribute="Normal Text" lineEndContext="#stay" name="Port">
          <DetectIdentifier attribute="Normal Text" context="#pop"/>
      </context>
    </contexts>

    <itemDatas>
      <itemData name="Normal Text" defStyleNum="dsNormal"/>
      <itemData name="Keyword"  defStyleNum="dsKeyword"/>
      <itemData name="Data Type"  defStyleNum="dsDataType"/>

      <itemData name="Decimal"  defStyleNum="dsBaseN"/>
      <itemData name="Octal"  defStyleNum="dsBaseN"/>
      <itemData name="Hex"  defStyleNum="dsBaseN"/>
      <itemData name="Binary"  defStyleNum="dsBaseN"/>
      <itemData name="Float"  defStyleNum="dsFloat"/>

      <itemData name="String"  defStyleNum="dsString"/>
      <itemData name="String Char"  defStyleNum="dsChar"/>
      <itemData name="Comment"  defStyleNum="dsComment"/>
      <itemData name="Alert"        defStyleNum="dsAlert" />
      <itemData name="Symbol"  defStyleNum="dsNormal"/>
      <itemData name="Preprocessor"  defStyleNum="dsOthers"/>
      <itemData name="Prep. Lib"  defStyleNum="dsFloat"/>
      <itemData name="System Task" defStyleNum="dsDataType"/>

      <itemData name="Integer" defStyleNum="dsDecVal"/>
      <itemData name="Delay" defStyleNum="dsBaseN"/>
      <itemData name="Block name" defStyleNum="dsDataType"/>
      <itemData name="Drive/charge strength" defStyleNum="dsBaseN"/>
      <itemData name="Gate instantiation" defStyleNum="dsDataType"/>
      <itemData name="Port map" defStyleNum="dsDataType"/>
      <itemData name="Case label" defStyleNum="dsDecVal"/>
    </itemDatas>
  </highlighting>
  <general>
    <comments>
      <comment name="singleLine" start="//" />
      <comment name="multiLine" start="/*" end="*/" region="Comment"/>
    </comments>
    <keywords casesensitive="1" />
  </general>
</language>


text:
var keystone = require('keystone');
const mailgun = require('mailgun-js');
const cbOptions = require('../../../options.js');

const DOMAIN = cbOptions.mailgun.domain;
const apiKey = cbOptions.mailgun.apiKey;
const mg = mailgun({ apiKey, domain: DOMAIN });

exports = module.exports = function (req, res) {

  var view = new keystone.View(req, res);
  var locals = res.locals;
  locals.section = 'account';

  // Turn off ads on this page
  locals.hideAds = true;

  view.on('init', function(next) {

    var userConfirm = req.user.confirmHash;

    // setup e-mail data with unicode symbols
    var mailOptions = {
      from: '"CloseBrace" <contact@closebrace.com>', // sender address
      to: req.user.email, // list of receivers
      subject: 'Please Confirm Your CloseBrace Account', // Subject line
      text: 'Thanks for registering with CloseBrace. You can confirm your account by visiting the following URL: https://closebrace.com/account/confirm?conf=' + userConfirm + ' ... If you did not sign up for CloseBrace and someone has used your email address by mistake, you don\'t need to do anything. This account will not be emailed again (unless a re-send of this confirmation email is requested), and will be automatically deleted in ten days.', // plaintext body
      html: '
Welcome to CloseBrace

Thanks for registering with CloseBrace, the tutorial and resource site for JavaScript developers, by JavaScript developers.

You can confirm your account by visiting the following URL: https://closebrace.com/account/confirm?conf=' + userConfirm + '

If you did not sign up for CloseBrace and someone has used your email address by mistake, you don\'t need to do anything. This account will not be emailed again (unless a re-send of this confirmation email is requested), and will be automatically deleted in ten days.
' // html body
    };

    // send mail
    mg.messages().send(mailOptions, (error, body) => {
      if (error) {
        req.flash('error', { title: 'Unable to send email', detail: error });
        return next();
      }
      req.flash('success', { detail: 'We\'ve re-sent your confirmation. Please check your email and click or copy-n-paste the provided link, which will make the notice below go away.'})
      res.redirect('/account/profile');
    });
  });

  view.render('account/profile');

};


text:
package com.jsheet.helper;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * Created by kavin on 18/07/17.
 */
public class Keys {
    public final String googleServiceAccountName;
    public final File googleServiceAccountKey;
    public Keys(){
        try {
            this.googleServiceAccountName = Files.readAllLines(Paths.get("keys/google_sheet_service_account.txt"), Charset.defaultCharset()).get(0);
            this.googleServiceAccountKey = new File("keys/google_sheet_service_account_key.p12");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/colorPrimaryDark" />
</layer-list>


text:
require "spec_helper"

describe Level do
  it { should be_able_to_be_destroyed }
  it { should restrict_destroy_when_exists :enrollment }
  it { should destroy_dependent :advisement_authorization }
  it { should restrict_destroy_when_exists :major }
  it { should restrict_destroy_when_exists :phase_duration }
  it { should restrict_destroy_when_exists :scholarship }

  let(:level) { Level.new }
  subject { level }
  describe "Validations" do
    describe "name" do
      context "should be valid when" do
        it "name is not null and is not taken" do
          level.name = "Level name"
          expect(level).to have(0).errors_on :name
        end
      end
      context "should have error blank when" do
        it "name is null" do
          level.name = nil
          expect(level).to have_error(:blank).on :name
        end
      end
      context "should have error taken when" do
        it "name is already in use" do
          name = "Level name"
          FactoryBot.create(:level, :name => name)
          level.name = name
          expect(level).to have_error(:taken).on :name
        end
      end
    end
    describe "default_duration" do
      context "should be valid when" do
        it "default_duration is not null" do
          level.default_duration = 48
          expect(level).to have(0).errors_on :default_duration
        end
      end
      context "should have error blank when" do
        it "default_duration is null" do
          level.default_duration = nil
          expect(level).to have_error(:blank).on :default_duration
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
        android:layout_width="match_parent"
        android:layout_height="0sp"
        android:layout_weight="1"
        android:textStyle="bold"
        android:id="@+id/lvAbout" />
    <ImageView
        android:layout_width="100sp"
        android:layout_height="100sp"
        android:src="@drawable/applogo_35splash"
        android:layout_gravity="center"
        android:id="@+id/ivMemberProfile" />
</LinearLayout>


text:
.class Lcom/samsung/android/settings/bluetooth/BluetoothControlHistory$ControlAppInfo;
.super Ljava/lang/Object;
.source "BluetoothControlHistory.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/samsung/android/settings/bluetooth/BluetoothControlHistory;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "ControlAppInfo"
.end annotation

# instance fields
.field private mLastEvent:I

.field private mLastEventTime:J

.field private mPackageName:Ljava/lang/String;

# direct methods
.method public constructor <init>(Ljava/lang/String;IJ)V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput-object p1, p0, Lcom/samsung/android/settings/bluetooth/BluetoothControlHistory$ControlAppInfo;->mPackageName:Ljava/lang/String;

    iput p2, p0, Lcom/samsung/android/settings/bluetooth/BluetoothControlHistory$ControlAppInfo;->mLastEvent:I

    iput-wide p3, p0, Lcom/samsung/android/settings/bluetooth/BluetoothControlHistory$ControlAppInfo;->mLastEventTime:J

    return-void
.end method

# virtual methods
.method public getLastEvent()I
    .locals 1

    iget v0, p0, Lcom/samsung/android/settings/bluetooth/BluetoothControlHistory$ControlAppInfo;->mLastEvent:I

    return v0
.end method

.method public getLastEventTime()J
    .locals 2

    iget-wide v0, p0, Lcom/samsung/android/settings/bluetooth/BluetoothControlHistory$ControlAppInfo;->mLastEventTime:J

    return-wide v0
.end method

.method public getPackageName()Ljava/lang/String;
    .locals 1

    iget-object v0, p0, Lcom/samsung/android/settings/bluetooth/BluetoothControlHistory$ControlAppInfo;->mPackageName:Ljava/lang/String;

    if-eqz v0, :cond_0

    iget-object v0, p0, Lcom/samsung/android/settings/bluetooth/BluetoothControlHistory$ControlAppInfo;->mPackageName:Ljava/lang/String;

    return-object v0

    :cond_0
    const-string/jumbo v0, ""

    return-object v0
.end method


text:
import { MemorySource, MemorySourceSettings } from '@orbit/memory';
import { applyStandardSourceInjections } from '../utils/standard-injections';

export default {
  create(injections: MemorySourceSettings): MemorySource {
    applyStandardSourceInjections(injections);
    injections.name = injections.name ?? 'store';
    injections.cacheSettings = { debounceLiveQueries: false };
    return new MemorySource(injections);
  }
};


text:
package model

import "testing"

// Subject dummies.
var s = []Subject{
	Subject{Short: "Md", Name: "Melden", SplitClass: false},
	Subject{Short: "Lm", Name: "Lärmen", SplitClass: true},
	Subject{Short: "Zl", Name: "Zählen", SplitClass: false}}

func TestSubjectCreate(t *testing.T) {
	// Create a subject.
	subject := s[0]
	subject.Create()

	// Check existence.
	var count int
	if db.Get(&count, "SELECT count(*) FROM subjects WHERE short = ?", s[0].Short); count == 0 {
		t.Error("Subject wasn't created.")
	}
}

func TestSubjectRead(t *testing.T) {
	// Read subject by short.
	subject := Subject{Short: s[0].Short}
	subject.Read()

	if subject.Name != s[0].Name {
		t.Errorf("Subject was not read as expected: (%+v) actual: %+v", s[0], subject)
	}

	// Read another subject by short. This one doesn't exists.
	subject = Subject{Short: s[1].Short}
	subject.Read()

	if subject.Short != s[1].Short || subject.Name != "" || subject.SplitClass != false {
		t.Errorf("Subject was unexpectedly read: %+v", subject)
	}
}

func TestSubjectExists(t *testing.T) {
	// Test that subject exists.
	subject := Subject{Short: s[0].Short}
	if !subject.Exists() {
		t.Error("Existent subject was not recognized.")
	}

	// Test that subject exists not.
	subject = Subject{Short: s[1].Short}
	if subject.Exists() {
		t.Error("Non existent subject was recognized.")
	}
}

func TestSubjectUpdate(t *testing.T) {
	// Change Name and SplitClass.
	newName := s[1].Name
	subject := Subject{Short: s[0].Short, Name: newName, SplitClass: s[0].SplitClass}
	subject.Update()

	// Test that subject.
	subject = Subject{Short: s[0].Short}
	subject.Read()
	if subject.Name != newName || subject.SplitClass != s[0].SplitClass {
		t.Error("Subject was read with old values after update.")
	}
}

func TestSubjectUpdateShort(t *testing.T) {
	// Change Short, Name and SplitClass.
	subject := s[1]
	subject.UpdateShort(s[0].Short)

	// Read old short. There shouldn't be anything to read.
	subject = Subject{Short: s[0].Short}
	if subject.Exists() {
		t.Error("Subject is still associated with old short after UpdateShort call.")
	}

	// Read updated subject.
	subject = Subject{Short: s[1].Short}
	subject.Read()
	if subject != s[1] {
		t.Error("Subject was read with old values after update.")
	}
}

func TestReadAllSubjects(t *testing.T) {
	// Count before.
	lenBefore := len(ReadAllSubjects())

	// Create new records.
	subjects := []Subject{
		Subject{Short: "t1", Name: "Test1", SplitClass: false},
		Subject{Short: "t2", Name: "Test2", SplitClass: true}}
	subjects[0].Create()
	subjects[1].Create()

	// Read all subjects and test whether the newly created subjects are returned, too.
	var hasFirst, hasSecond bool
	var readSubjects = ReadAllSubjects()
	for _, subject := range readSubjects {
		if subject == subjects[0] {
			hasFirst = true
		}
		if subject == subjects[1] {
			hasSecond = true
		}
	}
	if len(readSubjects) != lenBefore+2 {
		t.Error("The read amount of subjects differs from the expected amount.")
	}
	if !hasFirst || !hasSecond {
		t.Error("Didn't read all subjects.")
	}

	// Delete the records.
	subjects[0].Delete()
	subjects[1].Delete()
}

func TestSubjectDelete(t *testing.T) {
	// Create new record.
	subject := s[2]
	subject.Create()

	// Delete the subject.
	subject = s[1]
	subject.Delete()

	// Check if it was deleted.
	subject = Subject{Short: s[1].Short}
	if subject.Exists() {
		t.Error("Subject still exists after deletion.")
	}

	// Delete last subject.
	subject = s[2]
	subject.Delete()

	// Check if it was deleted.
	subject = Subject{Short: s[2].Short}
	if subject.Exists() {
		t.Error("Subject still exists after deletion.")
	}
}


text:
APP_NAME = "Factorio-modman"

FACTORIO_BASEURL = "https://mods.factorio.com/"
FACTORIO_LOGINURL = "https://auth.factorio.com/login/process"

# Set this to 0 or None to disable api request caching
API_CACHE_SECONDS = 60*60

# Prefix for modpack inheritance
MODPACK_INHERITANCE_PREFIX = "!"