text:
package com.intellij.util.xml;

import com.intellij.openapi.util.Condition;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ReflectionCache;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ConcurrentHashMap;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.jetbrains.annotations.Nullable;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author peter
 */
public class JavaMethodSignature {
  private static final Map<Method, JavaMethodSignature> ourSignatures = new ConcurrentHashMap<Method, JavaMethodSignature>();
  private final String myMethodName;
  private final Class[] myMethodParameters;
  private final Set<Class> myKnownClasses = new THashSet<Class>();
  private final List<Method> myAllMethods = new SmartList<Method>();
  private final Map<Class,Method> myMethods = new THashMap<Class, Method>();

  private JavaMethodSignature(final String methodName, final Class[] methodParameters) {
    myMethodName = methodName;
    myMethodParameters = methodParameters;
  }

  public String getMethodName() {
    return myMethodName;
  }

  public Class[] getParameterTypes() {
    return myMethodParameters;
  }

  public final Object invoke(final Object instance, final Object... args) throws IllegalAccessException, InvocationTargetException {
    final Class<?> aClass = instance.getClass();
    final Method method = findMethod(aClass);
    assert method != null : "No method " + this + " in " + aClass;
    return method.invoke(instance, args);
  }

  @Nullable
  public final synchronized Method findMethod(final Class aClass) {
    if (myMethods.containsKey(aClass)) {
      return myMethods.get(aClass);
    }
    Method method = getDeclaredMethod(aClass);
    if (method == null && ReflectionCache.isInterface(aClass)) {
      method = getDeclaredMethod(Object.class);
    }
    myMethods.put(aClass, method);
    return method;
  }

  private void addMethodsIfNeeded(final Class aClass) {
    if (!myKnownClasses.contains(aClass)) {
      addMethodWithSupers(aClass, findMethod(aClass));
    }
  }

  @Nullable
  private Method getDeclaredMethod(final Class aClass) {
    final Method method = ReflectionUtil.getMethod(aClass, myMethodName, myMethodParameters);
    return method == null ? ReflectionUtil.getDeclaredMethod(aClass, myMethodName, myMethodParameters) : method;
  }

  private void addMethodWithSupers(final Class aClass, final Method method) {
    myKnownClasses.add(aClass);
    if (method != null) {
      myAllMethods.add(method);
    }
    final Class superClass = aClass.getSuperclass();
    if (superClass != null) {
      addMethodsIfNeeded(superClass);
    } else {
      if (aClass.isInterface()) {
        addMethodsIfNeeded(Object.class);
      }
    }
    for (final Class anInterface : aClass.getInterfaces()) {
      addMethodsIfNeeded(anInterface);
    }
  }

  @Nullable
  public final synchronized <T extends Annotation> T findAnnotation(final Class<T> annotationClass, final Class startFrom) {
    addMethodsIfNeeded(startFrom);
    //noinspection ForLoopReplaceableByForEach
    T result = null;
    Class bestClass = null;

    final int size = myAllMethods.size();
    for (int i = 0; i < size; i++) {
      Method method = myAllMethods.get(i);
      final T annotation = method.getAnnotation(annotationClass);
      if (annotation != null) {
        final Class<?> declaringClass = method.getDeclaringClass();
        if (ReflectionCache.isAssignable(declaringClass, startFrom) &&
            (result == null || ReflectionCache.isAssignable(bestClass, declaringClass))) {
          result = annotation;
          bestClass = declaringClass;
        }
      }
    }
    return result;
  }

  public final synchronized List<Method> getAllMethods(final Class startFrom) {
    addMethodsIfNeeded(startFrom);
    final List<Method> list = ContainerUtil.findAll(myAllMethods, new Condition<Method>() {
      public boolean value(final Method method) {
        return method.getDeclaringClass().isAssignableFrom(startFrom);
      }
    });
    return list;
  }

  @Nullable
  public final synchronized <T extends Annotation> Method findAnnotatedMethod(final Class<T> annotationClass, final Class startFrom) {
    addMethodsIfNeeded(startFrom);
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < myAllMethods.size(); i++) {
      Method method = myAllMethods.get(i);
      final T annotation = method.getAnnotation(annotationClass);
      if (annotation != null && ReflectionCache.isAssignable(method.getDeclaringClass(), startFrom)) {
        return method;
      }
    }
    return null;
  }

  public String toString() {
    return myMethodName + Arrays.asList(myMethodParameters);
  }

  @Override
  public boolean equals(final Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    final JavaMethodSignature that = (JavaMethodSignature)o;

    if (!myMethodName.equals(that.myMethodName)) return false;
    if (!Arrays.equals(myMethodParameters, that.myMethodParameters)) return false;

    return true;
  }

  @Override
  public int hashCode() {
    int result = myMethodName.hashCode();
    result = 31 * result + Arrays.hashCode(myMethodParameters);
    return result;
  }

  public static JavaMethodSignature getSignature(Method method) {
    JavaMethodSignature signature = ourSignatures.get(method);
    if (signature != null) return signature;

    Class<?>[] parameters = method.getParameterTypes();
    ourSignatures.put(method, signature = new JavaMethodSignature(method.getName(), parameters.length == 0 ? ArrayUtil.EMPTY_CLASS_ARRAY : parameters));
    return signature;
  }

  public static JavaMethodSignature getSignature(final String name, final Class<?>... parameterTypes) {
    return new JavaMethodSignature(name, parameterTypes);
  }

}


text:
Authentication system for the AURIN Workbench

Workbenchauth is implemented as a Java Spring MVC application that provides
REST-API functions for authentication and authorization services to web
applications.  There is also a simple administrative interface implemented
using AngularJS.

A basic user manual is available for [user administration](doc/UserGuide.md).

To build with maven:

	export AURIN_DIR='/etc/aurin'
	mvn clean package -Ddeployment=development -Dsystem=ali-dev -Daurin.dir=$AURIN_DIR

## Requirements

The system has been tested on Ubuntu 14.04 LTS with Apache Tomcat 7 and the Postfix MTA.

redpajama_set_name: RedPajamaGithub


text:
import { createElement as h } from 'react';
import { mount } from '@not-govuk/component-test-helpers';
import StatusMessage from '../src/StatusMessage';

describe('StatusMessage', () => {
  describe('when given a status', () => {
    const component = mount(h(StatusMessage, { status: 'My heading' }));
    it('should show the status', () => expect(component.text()).toEqual('My heading'));
    it('should not show extra contents', () => expect(component.exists('.hods-status-message span')).toEqual(false));
    it('should not show any actions', () => expect(component.exists('.hods-status-message__actions')).toEqual(false));

    describe('and extra contents', () => {
      const component = mount(h(StatusMessage, { status: 'My heading' }, 'extra info'));
      it('should show the status and extra contents', () =>
        expect(component.text()).toMatch(/^My heading\s+extra info$/));

      describe('with an action', () => {
        const component = mount(h(StatusMessage, {
          status: 'My heading',
          actions: [{ href: '#', text: 'Run' }]
        }, 'extra info'));
        it('should show the status and extra contents', () =>
          expect(component.find('p').text()).toMatch(/^My heading\s+extra info$/));
        it('should also show the action', () =>
          expect(component.find('.hods-status-message__actions li')).toHaveLength(1));
        it('should render the action', () =>
          expect(component.find('.hods-status-message__actions').text()).toEqual('Run'));
      });
      describe('with multiple actions', () => {
        const actions = [
          { href: '#', text: 'Run' },
          { href: '#', text: 'Jump' },
          { href: '#', text: 'Sleep' }
        ];
        const component = mount(h(StatusMessage, { status: 'My heading', actions }, 'extra info'));
        it('should show the status and extra contents', () =>
          expect(component.find('p').text()).toMatch(/^My heading\s+extra info$/));
        it('should have actions', () => expect(component.find('.hods-status-message__actions li')).toHaveLength(3));
        it('should show all the actions', () =>
          expect(component.find('.hods-status-message__actions').text()).toMatch(/^Run\s*Jump\s*Sleep$/));
      });
    });
  });
});


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<artifactId>yuml-remote-renderer-httpclient</artifactId>
	<name>yuml remote renderer httpclient</name>
	<description>
		Uses the http://yuml.me api for rendering. It's using the apache http client for accessing yuml.me.
	</description>
	<parent>
		<groupId>com.java-adventures.yuml</groupId>
		<artifactId>yuml-connector-parent</artifactId>
		<version>0.2.1-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<dependencies>
		<dependency>
			<groupId>com.java-adventures.yuml</groupId>
			<artifactId>yuml-remote-renderer</artifactId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>log4j-over-slf4j</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<exclusions>
				<exclusion>
					<artifactId>commons-logging</artifactId>
					<groupId>commons-logging</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-all</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.github.tomakehurst</groupId>
			<artifactId>wiremock</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<artifactId>commons-logging</artifactId>
					<groupId>commons-logging</groupId>
				</exclusion>
				<exclusion>
					<artifactId>log4j</artifactId>
					<groupId>log4j</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
		</dependency>
	</dependencies>
	<build>
		<plugins>
		</plugins>
	</build>
</project>


text:
package org.apache.sling.validation.impl;

import org.apache.jackrabbit.JcrConstants;
import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.wrappers.ValueMapDecorator;
import org.apache.sling.jcr.resource.JcrResourceConstants;
import org.apache.sling.validation.api.Type;
import org.apache.sling.validation.api.ValidationModel;
import org.apache.sling.validation.api.ValidationResult;
import org.apache.sling.validation.api.ValidationService;
import org.apache.sling.validation.api.ValidatorLookupService;
import org.apache.sling.validation.impl.setup.MockedResourceResolver;
import org.apache.sling.validation.impl.validators.RegexValidator;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.reflect.Whitebox;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ValidationServiceImplTest {

    /**
     * Assume the validation models are stored under (/libs|/apps) + / + VALIDATION_MODELS_RELATIVE_PATH.
     */
    private static final String VALIDATION_MODELS_RELATIVE_PATH = "sling/validation/models";
    private static final String APPS = "/apps";
    private static final String LIBS = "/libs";
    private static ResourceResolverFactory rrf;
    private static Resource appsValidatorsRoot;
    private static Resource libsValidatorsRoot;
    private ValidationService validationService;
    private ValidatorLookupService validatorLookupService;

    @BeforeClass
    public static void init() throws Exception {
        rrf = mock(ResourceResolverFactory.class);
        when(rrf.getAdministrativeResourceResolver(null)).thenAnswer(new Answer<ResourceResolver>() {
            public ResourceResolver answer(InvocationOnMock invocation) throws Throwable {
                return new MockedResourceResolver();
            }
        });
        ResourceResolver rr = rrf.getAdministrativeResourceResolver(null);
        if (rr != null) {
            appsValidatorsRoot = ResourceUtil.getOrCreateResource(rr, APPS + "/" + VALIDATION_MODELS_RELATIVE_PATH, (Map) null,
                    "sling:Folder", true);
            libsValidatorsRoot = ResourceUtil.getOrCreateResource(rr, LIBS + "/" + VALIDATION_MODELS_RELATIVE_PATH, (Map) null,
                    "sling:Folder", true);
            rr.close();
        }
    }

    @AfterClass
    public static void beNiceAndClean() throws Exception {
        ResourceResolver rr = rrf.getAdministrativeResourceResolver(null);
        if (rr != null) {
            if (appsValidatorsRoot != null) {
                rr.delete(appsValidatorsRoot);
            }
            if (libsValidatorsRoot != null) {
                rr.delete(libsValidatorsRoot);
            }
            rr.commit();
            rr.close();
        }
    }

    @Before
    public void setUp() {
        validationService = new ValidationServiceImpl();
        Whitebox.setInternalState(validationService, "rrf", rrf);
        validatorLookupService = mock(ValidatorLookupService.class);
    }

    @Test
    public void testGetValidationModel() throws Exception {
        when(validatorLookupService.getValidator("org.apache.sling.validation.impl.validators.RegexValidator")).thenReturn(new
                RegexValidator());
        Whitebox.setInternalState(validationService, "validatorLookupService", validatorLookupService);

        List<TestProperty> properties = new ArrayList<TestProperty>();
        TestProperty property = new TestProperty();
        property.name = "field1";
        property.type = Type.DATE;
        property.validators.put("org.apache.sling.validation.impl.validators.RegexValidator", null);
        properties.add(property);
        ResourceResolver rr = rrf.getAdministrativeResourceResolver(null);
        Resource model1 = null, model2 = null;
        try {
            if (rr != null) {
                model1 = createValidationModelResource(rr, libsValidatorsRoot.getPath(), "testValidationModel1", "sling/validation/test",
                        new String[]{"/apps/validation"}, properties);
                model2 = createValidationModelResource(rr, libsValidatorsRoot.getPath(), "testValidationModel2", "sling/validation/test",
                        new String[]{"/apps/validation/1",
                        "/apps/validation/2"}, properties);
            }

            // BEST MATCHING PATH = /apps/validation/1; assume the applicable paths contain /apps/validation/2
            ValidationModel vm = validationService.getValidationModel("sling/validation/test", "/apps/validation/1/resource");
            assertTrue(arrayContainsString(vm.getApplicablePaths(), "/apps/validation/2"));

            // BEST MATCHING PATH = /apps/validation; assume the applicable paths contain /apps/validation but not /apps/validation/1
            vm = validationService.getValidationModel("sling/validation/test", "/apps/validation/resource");
            assertTrue(arrayContainsString(vm.getApplicablePaths(), "/apps/validation"));
            assertTrue(!arrayContainsString(vm.getApplicablePaths(), "/apps/validation/1"));
            if (model1 != null) {
                rr.delete(model1);
            }
            if (model2 != null) {
                rr.delete(model2);
            }
        } finally {
            if (rr != null) {
                rr.commit();
                rr.close();
            }
        }
    }

    @Test
    public void testGetValidationModelWithOverlay() throws Exception {
        when(validatorLookupService.getValidator("org.apache.sling.validation.impl.validators.RegexValidator")).thenReturn(new
                RegexValidator());
        Whitebox.setInternalState(validationService, "validatorLookupService", validatorLookupService);

        List<TestProperty> fields = new ArrayList<TestProperty>();
        TestProperty field = new TestProperty();
        field.name = "field1";
        field.type = Type.DATE;
        field.validators.put("org.apache.sling.validation.impl.validators.RegexValidator", null);
        fields.add(field);
        ResourceResolver rr = rrf.getAdministrativeResourceResolver(null);
        Resource model1 = null, model2 = null, model3 = null;
        try {
            if (rr != null) {
                model1 = createValidationModelResource(rr, libsValidatorsRoot.getPath(), "testValidationModel1", "sling/validation/test",
                        new String[]{"/apps/validation/1"}, fields);
                model2 = createValidationModelResource(rr, appsValidatorsRoot.getPath(), "testValidationModel1", "sling/validation/test",
                        new String[]{"/apps/validation/1",
                                "/apps/validation/2"}, fields);
                model3 = createValidationModelResource(rr, libsValidatorsRoot.getPath(), "testValidationModel2", "sling/validation/test",
                        new String[]{"/apps/validation/3"}, fields);
            }

            // BEST MATCHING PATH = /apps/validation/1; assume the applicable paths contain /apps/validation/2
            ValidationModel vm = validationService.getValidationModel("sling/validation/test", "/apps/validation/1/resource");
            assertTrue(arrayContainsString(vm.getApplicablePaths(), "/apps/validation/2"));

            vm = validationService.getValidationModel("sling/validation/test", "/apps/validation/3/resource");
            assertTrue(arrayContainsString(vm.getApplicablePaths(), "/apps/validation/3"));

            if (model1 != null) {
                rr.delete(model1);
            }
            if (model2 != null) {
                rr.delete(model2);
            }
            if (model3 != null) {
                rr.delete(model3);
            }
        } finally {
            if (rr != null) {
                rr.commit();
                rr.close();
            }
        }
    }

    @Test
    public void testValueMapWithWrongDataType() throws Exception {
        when(validatorLookupService.getValidator("org.apache.sling.validation.impl.validators.RegexValidator")).thenReturn(new
                RegexValidator());
        Whitebox.setInternalState(validationService, "validatorLookupService", validatorLookupService);

        List<TestProperty> properties = new ArrayList<TestProperty>();
        TestProperty property = new TestProperty();
        property.name = "field1";
        property.type = Type.DATE;
        property.validators.put("org.apache.sling.validation.impl.validators.RegexValidator", null);
        properties.add(property);
        ResourceResolver rr = rrf.getAdministrativeResourceResolver(null);
        Resource model1 = null;
        try {
            if (rr != null) {
                model1 = createValidationModelResource(rr, libsValidatorsRoot.getPath(), "testValidationModel1", "sling/validation/test",
                        new String[]{"/apps/validation"}, properties);
            }
            ValidationModel vm = validationService.getValidationModel("sling/validation/test", "/apps/validation/1/resource");
            HashMap<String, Object> hashMap = new HashMap<String, Object>() {{
                put("field1", "1");
            }};
            ValueMap map = new ValueMapDecorator(hashMap);
            ValidationResult vr = validationService.validate(map, vm);
            assertFalse(vr.isValid());
            if (model1 != null) {
                rr.delete(model1);
            }
        } finally {
            if (rr != null) {
                rr.commit();
                rr.close();
            }
        }
    }

    @Test
    public void testValueMapWithCorrectDataType() throws Exception {
        when(validatorLookupService.getValidator("org.apache.sling.validation.impl.validators.RegexValidator")).thenReturn(new
                RegexValidator());
        Whitebox.setInternalState(validationService, "validatorLookupService", validatorLookupService);

        List<TestProperty> fields = new ArrayList<TestProperty>();
        TestProperty field = new TestProperty();
        field.name = "field1";
        field.type = Type.STRING;
        field.validators.put("org.apache.sling.validation.impl.validators.RegexValidator", new String[] {"regex=^\\p{L}+$"});
        fields.add(field);
        ResourceResolver rr = rrf.getAdministrativeResourceResolver(null);
        Resource model1 = null;
        try {
            if (rr != null) {
                model1 = createValidationModelResource(rr, libsValidatorsRoot.getPath(), "testValidationModel1", "sling/validation/test",
                        new String[]{"/apps/validation"}, fields);
            }
            ValidationModel vm = validationService.getValidationModel("sling/validation/test", "/apps/validation/1/resource");
            HashMap<String, Object> hashMap = new HashMap<String, Object>() {{
                put("field1", "HelloWorld");
            }};
            ValueMap map = new ValueMapDecorator(hashMap);
            ValidationResult vr = validationService.validate(map, vm);
            assertTrue(vr.isValid());
            if (model1 != null) {
                rr.delete(model1);
            }
        } finally {
            if (rr != null) {
                rr.commit();
                rr.close();
            }
        }
    }

    @Test
     public void testResourceWithMissingChildProperty() throws Exception {
        when(validatorLookupService.getValidator("org.apache.sling.validation.impl.validators.RegexValidator")).thenReturn(new
                RegexValidator());
        Whitebox.setInternalState(validationService, "validatorLookupService", validatorLookupService);

        List<TestProperty> fields = new ArrayList<TestProperty>();
        TestProperty property = new TestProperty();
        property.name = "field1";
        property.type = Type.INT;
        property.validators.put("org.apache.sling.validation.impl.validators.RegexValidator", new String[] {RegexValidator.REGEX_PARAM + "=" + "\\d"});
        fields.add(property);
        ResourceResolver rr = rrf.getAdministrativeResourceResolver(null);
        Resource model1 = null;
        Resource testResource = null;
        try {
            if (rr != null) {
                model1 = createValidationModelResource(rr, libsValidatorsRoot.getPath(), "testValidationModel1", "sling/validation/test",
                        new String[]{"/apps/validation"}, fields);
                Resource modelChildren = rr.create(model1, "children", new HashMap<String, Object>(){{
                    put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                }});
                Resource child = rr.create(modelChildren, "child1", new HashMap<String, Object>(){{
                    put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                }});
                Resource childProperties = rr.create(child, "properties", new HashMap<String, Object>(){{
                    put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                }});
                Resource childProperty = rr.create(childProperties, "hello", new HashMap<String, Object>(){{
                    put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                    put(Constants.PROPERTY_TYPE, "string");
                }});
                Resource grandChildren = rr.create(child, "children", new HashMap<String, Object>(){{
                    put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                }});
                Resource grandChild = rr.create(grandChildren, "grandChild1", new HashMap<String, Object>(){{
                    put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                }});

                testResource = ResourceUtil.getOrCreateResource(rr, "/apps/validation/1/resource", JcrConstants.NT_UNSTRUCTURED,
                        JcrConstants.NT_UNSTRUCTURED, true);
                Resource childResource = rr.create(testResource, "child1", new HashMap<String, Object>(){{
                    put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                }});
                rr.commit();

                ModifiableValueMap mvm = testResource.adaptTo(ModifiableValueMap.class);
                mvm.put("field1", "1");
                rr.commit();

                // /apps/validation/1/resource/child1 will miss its mandatory "hello" property
                Resource resourceChild = rr.create(testResource, "child1", new HashMap<String, Object>(){{
                    put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                }});

                Resource resourceGrandChild = rr.create(resourceChild, "grandChild1", new HashMap<String, Object>(){{
                    put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                }});
                rr.commit();
            }
            ValidationModel vm = validationService.getValidationModel("sling/validation/test", "/apps/validation/1/resource");
            ValidationResult vr = validationService.validate(testResource, vm);
            assertFalse(vr.isValid());
            assertTrue(vr.getFailureMessages().containsKey("child1/hello"));
        } finally {
            if (rr != null) {
                if (model1 != null) {
                    rr.delete(model1);
                }
                if (testResource != null) {
                    rr.delete(testResource);
                }
                rr.commit();
                rr.close();
            }
        }
    }

    private Resource createValidationModelResource(ResourceResolver rr, String root, String name, String validatedResourceType,
                                               String[] applicableResourcePaths, List<TestProperty> properties) throws Exception {
        Map<String, Object> modelProperties = new HashMap<String, Object>();
        modelProperties.put(Constants.VALIDATED_RESOURCE_TYPE, validatedResourceType);
        modelProperties.put(Constants.APPLICABLE_PATHS, applicableResourcePaths);
        modelProperties.put(JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY, Constants.VALIDATION_MODEL_RESOURCE_TYPE);
        modelProperties.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
        Resource model = ResourceUtil.getOrCreateResource(rr, root + "/" + name, modelProperties, JcrResourceConstants.NT_SLING_FOLDER, true);
        if (model != null) {
            Resource propertiesResource = ResourceUtil.getOrCreateResource(rr, model.getPath() + "/" + Constants
                    .PROPERTIES, JcrConstants.NT_UNSTRUCTURED, null, true);
            if (propertiesResource != null) {
                for (TestProperty property : properties) {
                    Map<String, Object> modelPropertyJCRProperties = new HashMap<String, Object>();
                    modelPropertyJCRProperties.put(Constants.PROPERTY_TYPE, property.type.getName());
                    modelPropertyJCRProperties.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                    Resource propertyResource = ResourceUtil.getOrCreateResource(rr, propertiesResource.getPath() + "/" + property.name,
                            modelPropertyJCRProperties, null, true);
                    if (propertyResource != null) {
                        Resource validators = ResourceUtil.getOrCreateResource(rr,
                                propertyResource.getPath() + "/" + Constants.VALIDATORS,
                                JcrConstants.NT_UNSTRUCTURED, null, true);
                        if (validators != null) {
                            for (Map.Entry<String, String[]> v : property.validators.entrySet()) {
                                Map<String, Object> validatorProperties = new HashMap<String, Object>();
                                validatorProperties.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_UNSTRUCTURED);
                                if (v.getValue() != null) {
                                    validatorProperties.put(Constants.VALIDATOR_ARGUMENTS, v.getValue());
                                }
                                ResourceUtil.getOrCreateResource(rr, validators.getPath() + "/" + v.getKey(), validatorProperties, null,
                                        true);
                            }
                        }
                    }
                }
            }
        }
        return model;
    }

    private boolean arrayContainsString(String[] array, String string) {
        boolean result = false;
        if (array != null && string != null) {
            for (String s : array) {
                if (string.equals(s)) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }

    private class TestProperty {
        String name;
        Type type;
        Map<String, String[]> validators;

        TestProperty() {
            validators = new HashMap<String, String[]>();
        }
    }

    private class TestChild {

    }

}


text:
require 'optparse'

require "vagrant/util/safe_puts"

module VagrantPlugins
  module CommandSSHConfig
    class Command < Vagrant.plugin("2", :command)
      include Vagrant::Util::SafePuts

      def self.synopsis
        "outputs OpenSSH valid configuration to connect to the machine"
      end

      def execute
        options = {}

        opts = OptionParser.new do |o|
          o.banner = "Usage: vagrant ssh-config [options] [name|id]"
          o.separator ""
          o.separator "Options:"
          o.separator ""

          o.on("--host NAME", "Name the host for the config") do |h|
            options[:host] = h
          end
        end

        argv = parse_options(opts)
        return if !argv

        with_target_vms(argv) do |machine|
          ssh_info = machine.ssh_info
          raise Vagrant::Errors::SSHNotReady if ssh_info.nil?

          variables = {
            host_key: options[:host] || machine.name || "vagrant",
            ssh_host: ssh_info[:host],
            ssh_port: ssh_info[:port],
            ssh_user: ssh_info[:username],
            private_key_path: ssh_info[:private_key_path],
            forward_agent: ssh_info[:forward_agent],
            forward_x11:   ssh_info[:forward_x11],
            proxy_command: ssh_info[:proxy_command],
            ssh_command:   ssh_info[:ssh_command],
            forward_env:   ssh_info[:forward_env],
          }

          # Render the template and output directly to STDOUT
          template = "commands/ssh_config/config"
          config   = Vagrant::Util::TemplateRenderer.render(template, variables)
          machine.ui.machine("ssh-config", config)
          safe_puts(config)
          safe_puts
        end

        # Success, exit status 0
        0
      end
    end
  end
end


text:
namespace VisualBasic6X.Converter.Console
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Microsoft.Build.Evaluation;

    /// <summary>
    /// Converts a Visual Basic 6 project to the new .vbpx MSBuild project format.
    /// </summary>
    public class ProjectConverter
    {
        private static readonly IEnumerable<Guid> primaryReferences = new[]
        {
            new Guid("{00020430-0000-0000-C000-000000000046}"), // OLE Automation
            new Guid("{EF53050B-882E-4776-B643-EDA472E8E3F2}"), // Microsoft ActiveX Data Objects
        };

        public Project Convert(VB6Project vb6Project)
        {
            if (vb6Project == null) throw new ArgumentNullException("vb6Project");

            var project = new Project();

            // Default target is Build
            project.Xml.DefaultTargets = "Build";

            // Default configuration is Debug
            var configurationProperty = project.Xml.AddProperty("Configuration", "Debug");
            configurationProperty.Condition = "'$(Configuration)' == ''";

            // Standard properties
            project.SetProperty("SchemaVersion", "2.0");
            project.SetProperty("ProjectGuid", Guid.NewGuid().ToString("B"));
            project.SetProperty("AssemblyName", vb6Project.Name);
            //project.SetProperty("RootNamespace", projectName);
            project.SetProperty("EnableUnmanagedDebugging", true.ToString());

            // Determine the project output type
            string projectType;
            switch (vb6Project.ProjectType)
            {
                case VB6ProjectType.OleExe:
                    // For an ActiveX exe, there's no equivalent standard property we can use,
                    // so we have a special property we can use to override.
                    project.SetProperty("VB6OutputType", "OleExe");
                    projectType = "WinExe";
                    break;
                case VB6ProjectType.Exe:
                    projectType = "WinExe";
                    break;
                case VB6ProjectType.OleDll:
                    projectType = "Library";
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            project.SetProperty("ProjectType", projectType);

            // Debug configuration
            var debugConfig = project.Xml.AddPropertyGroup();
            debugConfig.Condition = "'$(Configuration)' == 'Debug'";
            debugConfig.AddProperty("OutputPath", @"bin\Debug\");

            // Release configuration
            var releaseConfig = project.Xml.AddPropertyGroup();
            releaseConfig.Condition = "'$(Configuration)' == 'Release'";
            releaseConfig.AddProperty("OutputPath", @"bin\Release\");

            // Will contain the items for compilation
            var compileGroup = project.Xml.AddItemGroup();

            // Will contain non-compilation items
            var noneGroup = project.Xml.AddItemGroup();

            // Add our source files
            foreach (var source in vb6Project.SourceFiles)
            {
                var item = compileGroup.AddItem("Compile", source.FileName);

                // Is this the startup item?
                if (source.Name.Equals(vb6Project.Startup, StringComparison.OrdinalIgnoreCase)) item.AddMetadata("Startup", "true");

                // If this is a form, we may need additional meta data
                if (source.Type != VB6SourceFileType.Form) continue;

                // Icon form?
                if (source.Name.Equals(vb6Project.IconForm, StringComparison.OrdinalIgnoreCase)) item.AddMetadata("Icon", "true");

                // Is there a .frx to go with this form? We will want to include it
                // in the project as a dependency.
                var formFrxPath = Path.Combine( Path.GetDirectoryName(vb6Project.FileName), source.Name + ".frx");
                var formFrxFile = new FileInfo(formFrxPath);
                if (!formFrxFile.Exists) continue;

                // We add the .frx as another item, but we make it dependent on the
                // parent form, so it shows up as nested in Visual Studio (like code-behind files).
                var frxItem = noneGroup.AddItem("Compile", formFrxFile.Name);
                frxItem.AddMetadata("DependentUpon", source.FileName);
            }

            // COM References
            var referenceGroup = project.Xml.AddItemGroup();
            foreach (var reference in vb6Project.References)
            {
                var item = referenceGroup.AddItem("COMReference", reference.Description);

                // Add the COM Reference meta data
                item.AddMetadata("Guid", reference.Guid.ToString("B"));
                item.AddMetadata("VersionMajor", reference.VersionMajor.ToString());
                item.AddMetadata("VersionMinor", reference.VersionMinor.ToString());
                item.AddMetadata("Lcid", "0");
                item.AddMetadata("Isolated", "False");
                item.AddMetadata("WrapperTool", IsPrimaryReference(reference.Guid) ? "primary" : "tlbimp");
                item.AddMetadata("EmbedInteropTypes", "True");
                item.AddMetadata("Private", "True");
            }
            foreach (var reference in vb6Project.Components)
            {
                var item = referenceGroup.AddItem("COMReference", reference.FileName);

                // Add the COM Reference meta data
                item.AddMetadata("Guid", reference.Guid.ToString("B"));
                item.AddMetadata("VersionMajor", reference.VersionMajor.ToString());
                item.AddMetadata("VersionMinor", reference.VersionMinor.ToString());
                item.AddMetadata("Lcid", "0");
                item.AddMetadata("Isolated", "False");
                item.AddMetadata("WrapperTool", IsPrimaryReference(reference.Guid) ? "primary" : "aximp");
                item.AddMetadata("EmbedInteropTypes", "True");
                item.AddMetadata("Private", "True");
            }

            // We need to import the Visual Basic 6 build targets for this to compile properly.
            project.Xml.AddImport(@"$(LocalAppData)\SadRobot\VisualBasic6X\VisualBasic6.targets");

            // The converted project will be in the same location as the project, except with the .vbpx extension.
            var convertedProject = new FileInfo(Path.Combine(Path.GetDirectoryName(vb6Project.FileName), Path.GetFileNameWithoutExtension(vb6Project.Name) + ".vbpx"));
            project.Save(convertedProject.FullName);

            return project;
        }

        private bool IsPrimaryReference(Guid guid)
        {
            return primaryReferences.Any(g => g.Equals(guid));
        }
    }
}


text:
package simulator.ui;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author LeeThree
 */
public class DebuggerTable extends JTable {

    public DebuggerTable() {
        setModel(new DefaultTableModel(
                new Object[][]{},
                new String[]{
                    "Line No.", "Assembly", "Code", "Address"
                }) {

            Class[] types = new Class[]{
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean[]{
                false, false, false, false
            };

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });
        setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
        setShowVerticalLines(false);
        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        highlightRenderer = new DefaultTableCellRenderer();
        highlightRenderer.setBackground(Color.YELLOW);
        breakpointRenderer = new DefaultTableCellRenderer();
        breakpointRenderer.setBackground(Color.RED);
        breakpointRenderer.setForeground(Color.WHITE);
        centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        centerHighlightRenderer = new DefaultTableCellRenderer();
        centerHighlightRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        centerHighlightRenderer.setBackground(Color.YELLOW);
        centerBreakpointRenderer = new DefaultTableCellRenderer();
        centerBreakpointRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        centerBreakpointRenderer.setBackground(Color.RED);
        centerBreakpointRenderer.setForeground(Color.WHITE);
        highlightRowNum = -1;
        this.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent evt) {
                if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() > 1 && getSelectedRowCount() == 1) {
                    setBreakPoint(getSelectedRow());
                }
            }
        });
    }

    public void setConfig(UIConfig config) {
        this.config = config;
    }

    @Override
    public TableCellRenderer getCellRenderer(int row, int column) {
        if (convertRowIndexToModel(row) == highlightRowNum) {
            if (convertColumnIndexToModel(column) == 1) {
                return highlightRenderer;
            } else {
                return centerHighlightRenderer;
            }
        } else if (config.breakpoints.contains(convertRowIndexToModel(row))) {
            if (convertColumnIndexToModel(column) == 1) {
                return breakpointRenderer;
            } else {
                return centerBreakpointRenderer;
            }
        } else {
            return super.getCellRenderer(row, column);
        }
    }

    public void update() {
        getColumnModel().getColumn(0).setPreferredWidth(70);
        getColumnModel().getColumn(0).setMaxWidth(300);
        getColumnModel().getColumn(3).setPreferredWidth(70);
        getColumnModel().getColumn(3).setMaxWidth(300);
        //getColumnModel().getColumn(1).setCellRenderer(highlightRenderer);
        getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
        getColumnModel().getColumn(2).setCellRenderer(centerRenderer);
        getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
    }

    public void highlight(int rowIndex) {
        highlightRowNum = rowIndex;
    //getSelectionModel().setSelectionInterval(rowIndex, rowIndex);
    }

    private void setBreakPoint(int position) {
        if (!config.breakpoints.add(position)) {
            config.breakpoints.remove(position);
        }
        clearSelection();
        update();
    }
    private DefaultTableCellRenderer highlightRenderer;
    private DefaultTableCellRenderer breakpointRenderer;
    private DefaultTableCellRenderer centerRenderer;
    private DefaultTableCellRenderer centerHighlightRenderer;
    private DefaultTableCellRenderer centerBreakpointRenderer;
    private int highlightRowNum;
    private UIConfig config;
}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.default = void 0;

function _defineProperty(obj, key, value) {
  if (key in obj) {
    Object.defineProperty(obj, key, {
      value: value,
      enumerable: true,
      configurable: true,
      writable: true
    });
  } else {
    obj[key] = value;
  }
  return obj;
}

/* eslint-disable local/ban-types-eventually */
class ReporterDispatcher {
  constructor() {
    _defineProperty(this, '_reporters', void 0);

    this._reporters = [];
  }

  register(reporter) {
    this._reporters.push(reporter);
  }

  unregister(ReporterClass) {
    this._reporters = this._reporters.filter(
      reporter => !(reporter instanceof ReporterClass)
    );
  }

  async onTestFileResult(test, testResult, results) {
    for (const reporter of this._reporters) {
      if (reporter.onTestFileResult) {
        await reporter.onTestFileResult(test, testResult, results);
      } else if (reporter.onTestResult) {
        await reporter.onTestResult(test, testResult, results);
      }
    } // Release memory if unused later.

    testResult.coverage = undefined;
    testResult.console = undefined;
  }

  async onTestFileStart(test) {
    for (const reporter of this._reporters) {
      if (reporter.onTestFileStart) {
        await reporter.onTestFileStart(test);
      } else if (reporter.onTestStart) {
        await reporter.onTestStart(test);
      }
    }
  }

  async onRunStart(results, options) {
    for (const reporter of this._reporters) {
      reporter.onRunStart && (await reporter.onRunStart(results, options));
    }
  }

  async onTestCaseResult(test, testCaseResult) {
    for (const reporter of this._reporters) {
      if (reporter.onTestCaseResult) {
        await reporter.onTestCaseResult(test, testCaseResult);
      }
    }
  }

  async onRunComplete(contexts, results) {
    for (const reporter of this._reporters) {
      if (reporter.onRunComplete) {
        await reporter.onRunComplete(contexts, results);
      }
    }
  } // Return a list of last errors for every reporter

  getErrors() {
    return this._reporters.reduce((list, reporter) => {
      const error = reporter.getLastError && reporter.getLastError();
      return error ? list.concat(error) : list;
    }, []);
  }

  hasErrors() {
    return this.getErrors().length !== 0;
  }
}

exports.default = ReporterDispatcher;


text:
lightweight blogging server
using python and flask web framework


text:
using MFiles.VAF.Common;
using MFilesAPI;

namespace EventTracing
{
	/// <summary>
	/// A sample vault application which aids in tracing events and VAF lifecycle.
	/// </summary>
	public partial class VaultApplication
	{
		/// <inheritdoc />
		protected override void InitializeApplication(Vault vault)
		{
			SysUtils.ReportInfoToEventLog($"Begin InitializeApplication");
			base.InitializeApplication(vault);
			SysUtils.ReportInfoToEventLog($"End InitializeApplication");
		}

		/// <inheritdoc />
		protected override void InstallApplication(Vault vault)
		{
			SysUtils.ReportInfoToEventLog($"Begin InstallApplication");
			base.InstallApplication(vault);
			SysUtils.ReportInfoToEventLog($"End InstallApplication");
		}

		/// <inheritdoc />
		protected override void StartApplication()
		{
			SysUtils.ReportInfoToEventLog($"Begin StartApplication");
			base.StartApplication();
			SysUtils.ReportInfoToEventLog($"End StartApplication");
		}

		/// <inheritdoc />
		protected override void UninitializeApplication(Vault vault)
		{
			SysUtils.ReportInfoToEventLog($"Begin UninitializeApplication");
			base.UninitializeApplication(vault);
			SysUtils.ReportInfoToEventLog($"End UninitializeApplication");
		}

		/// <inheritdoc />
		protected override void UninstallApplication(Vault vault)
		{
			SysUtils.ReportInfoToEventLog($"Begin UninstallApplication");
			base.UninstallApplication(vault);
			SysUtils.ReportInfoToEventLog($"End UninstallApplication");
		}
	}
}


text:
<!--
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
-->
<obr>
  <require extend="false" filter="(service=org.apache.felix.shell.ShellService)" multiple="false" name="service" optional="false">Import Service org.apache.felix.shell.ShellService</require>
</obr>


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>at.irian.ankor.base (Ankor - Project 0.1 API)</title>
<meta name="date" content="2014-02-27">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package at.irian.ankor.base

Basic data types and helpers.

See: Description

Interface Summary

Interface
Description

BeanResolver

Abstraction for third-party bean factories like Spring
 or ManagedBeans.

Wrapper<T>

Marker interface for types that "wrap" some other objects.

Class Summary

Class
Description

ObjectUtils

Package at.irian.ankor.base Description

Basic data types and helpers.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2014. All rights reserved.


text:
package funcx

import (
	"reflect"
	"testing"

	"github.com/apache/beam/sdks/go/pkg/beam/core/typex"
)

func TestIsIter(t *testing.T) {
	tests := []struct {
		Fn  interface{}
		Exp bool
	}{
		{func(*int) {}, false},                                // no return
		{func() bool { return false }, false},                 // no value
		{func(*int) int { return 0 }, false},                  // no bool return
		{func(int) bool { return false }, false},              // no ptr value
		{func(*typex.EventTime) bool { return false }, false}, // no values
		{func(*int) bool { return false }, true},
		{func(*typex.EventTime, *int) bool { return false }, true},
		{func(*int, *string) bool { return false }, true},
		{func(*typex.Y, *typex.Z) bool { return false }, true},
		{func(*typex.EventTime, *int, *string) bool { return false }, true},
		{func(*int, *typex.Y, *typex.Z) bool { return false }, false},                   // too many values
		{func(*typex.EventTime, *int, *typex.Y, *typex.Z) bool { return false }, false}, // too many values
	}

	for _, test := range tests {
		val := reflect.TypeOf(test.Fn)
		if actual := IsIter(val); actual != test.Exp {
			t.Errorf("IsIter(%v) = %v, want %v", val, actual, test.Exp)
		}
	}
}

func TestIsReIter(t *testing.T) {
	tests := []struct {
		Fn  interface{}
		Exp bool
	}{
		{func() bool { return false }, false},                                      // not returning an Iter
		{func(*int) func(*int) bool { return nil }, false},                         // takes parameters
		{func(*int) (func(*int) bool, func(*int) bool) { return nil, nil }, false}, // too many iterators
		{func() func(*int) bool { return nil }, true},
		{func() func(*typex.EventTime, *int, *string) bool { return nil }, true},
	}

	for _, test := range tests {
		val := reflect.TypeOf(test.Fn)
		if actual := IsReIter(val); actual != test.Exp {
			t.Errorf("IsReIter(%v) = %v, want %v", val, actual, test.Exp)
		}
	}
}


text:
package com.amazonaws.services.cloudformation.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.cloudformation.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;

/**
 * SetStackPolicyRequest Marshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class SetStackPolicyRequestMarshaller implements Marshaller<Request<SetStackPolicyRequest>, SetStackPolicyRequest> {

    public Request<SetStackPolicyRequest> marshall(SetStackPolicyRequest setStackPolicyRequest) {

        if (setStackPolicyRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        Request<SetStackPolicyRequest> request = new DefaultRequest<SetStackPolicyRequest>(setStackPolicyRequest, "AmazonCloudFormation");
        request.addParameter("Action", "SetStackPolicy");
        request.addParameter("Version", "2010-05-15");
        request.setHttpMethod(HttpMethodName.POST);

        if (setStackPolicyRequest.getStackName() != null) {
            request.addParameter("StackName", StringUtils.fromString(setStackPolicyRequest.getStackName()));
        }

        if (setStackPolicyRequest.getStackPolicyBody() != null) {
            request.addParameter("StackPolicyBody", StringUtils.fromString(setStackPolicyRequest.getStackPolicyBody()));
        }

        if (setStackPolicyRequest.getStackPolicyURL() != null) {
            request.addParameter("StackPolicyURL", StringUtils.fromString(setStackPolicyRequest.getStackPolicyURL()));
        }

        return request;
    }

}


text:
package me.deftware.client.framework.chat;

import me.deftware.client.framework.chat.style.ChatColors;

import java.util.Arrays;

/**
 * @author Deftware
 */
public class LiteralChatMessage extends ChatMessage {

	public static final LiteralChatMessage EMPTY = new LiteralChatMessage("");

	public LiteralChatMessage(String text) {
		this(text, ChatColors.WHITE);
	}

	public LiteralChatMessage(String text, ChatColors color) {
		ChatSection section = new ChatSection(text);
		section.getStyle().setColor(color.getChatColor());
		sectionList.add(section);
	}

	public static LiteralChatMessage formatted(String text, Object... params) {
		return new LiteralChatMessage(String.format(text, params));
	}

	public static LiteralChatMessage[] of(String... text) {
		return Arrays.stream(text)
				.map(s -> s == null || s.isEmpty() ? EMPTY : new LiteralChatMessage(s))
				.toArray(LiteralChatMessage[]::new);
	}

}


text:
Attempt at using example code from ofxASR addon for openFrameworks.

# installation
Clone https://github.com/ludimation/ofxASR_example.git to "<openFrameworks>\apps\myApps\".

# dependencies
ofxASR--https://github.com/ludimation/ofxasr.git
* Download / clone locally to disk
* Navigate to "ofxASR" subdirectory and copy it to "<openFrameworks>\addons\" directory.

# notes
When using the project generator in Win32 to create a new visual studio project with ofxASR, it doesn't seem to link the sphinx ".lib" and ".dll" files properly--results in some compile errors, as well as some missing "dll" errors at runtime
  * "link" and "export" portions of the install xml file don't seem to work--only "include" entries were added properly to the sln.
  * Not sure how to fix the xml file, so I hacked in the necessary dependencies:
    * Added sphinx ".lib" files by hand.
    * Created a 'dlls" directory at the root level of the project and added a post-build macro to copy them to "bin".

Model resources are required in order to use ofxASR
* I tested both both the typical model resource pack and the complete english model resource pack.
* If you'd like to use others, see the FAQ on the addOn google code page--https://code.google.com/p/ofxasr/wiki/FAQ


text:
import { expect } from 'chai';
import { spec } from 'modules/playgroundxyzBidAdapter';
import { newBidder } from 'src/adapters/bidderFactory';
import { deepClone } from 'src/utils';

const URL = 'https://ads.playground.xyz/host-config/prebid?v=2';
const GDPR_CONSENT = 'XYZ-CONSENT';

describe('playgroundxyzBidAdapter', function () {
  const adapter = newBidder(spec);

  describe('inherited functions', function () {
    it('exists and is a function', function () {
      expect(adapter.callBids).to.exist.and.to.be.a('function');
    });
  });

  describe('isBidRequestValid', function () {
    let bid = {
      'bidder': 'playgroundxyz',
      'params': {
        'placementId': '10433394'
      },
      'adUnitCode': 'adunit-code',
      'sizes': [[300, 250], [320, 50]],
      'bidId': '30b31c1838de1e',
      'bidderRequestId': '22edbae2733bf6',
      'auctionId': '1d1a030790a475',
    };

    it('should return true when required params found', function () {
      expect(spec.isBidRequestValid(bid)).to.equal(true);
    });

    it('should return false when required params are not passed', function () {
      let bid = Object.assign({}, bid);
      delete bid.params;
      bid.params = {
        'placementId': 0
      };
      expect(spec.isBidRequestValid(bid)).to.equal(false);
    });
  });

  describe('buildRequests', function () {
    let bidRequests = [
      {
        'bidder': 'playgroundxyz',
        'params': {
          'placementId': '10433394'
        },
        'adUnitCode': 'adunit-code',
        'sizes': [[300, 250], [300, 600]],
        'bidId': '30b31c1838de1e',
        'bidderRequestId': '22edbae2733bf6',
        'auctionId': '1d1a030790a475',
      }
    ];

    it('sends bid request to ENDPOINT via POST', function () {
      let bidRequest = Object.assign([], bidRequests);

      const request = spec.buildRequests(bidRequest);
      const data = JSON.parse(request.data);
      const banner = data.imp[0].banner;

      expect(Object.keys(data.imp[0].ext)).to.have.members(['appnexus', 'pxyz']);
      expect([banner.w, banner.h]).to.deep.equal([300, 250]);
      expect(banner.format).to.deep.equal([{w: 300, h: 250}, {w: 300, h: 600}]);
      expect(request.url).to.equal(URL);
      expect(request.method).to.equal('POST');
    });
  })

  describe('interpretResponse', function () {
    let response = {
      'id': 'bidd_id',
      'seatbid': [ {
        'bid': [
          {
            'id': '4434762738980910431',
            'impid': '221f2bdc1fbc31',
            'price': 1,
            'adid': '91673066',
            'adm': '<script src=\'pgxyz\'></script>',
            'adomain': [ 'pg.xyz' ],
            'iurl': 'http://pgxyz.com/cr?id=91673066',
            'cid': 'c_id',
            'crid': 'c_rid',
            'h': 50,
            'w': 320,
            'ext': {
              'appnexus': {
                'brand_id': 1,
                'auction_id': 1087655594852566000,
                'bidder_id': 2,
                'bid_ad_type': 0
              }
            }
          }
        ],
        'seat': '4321'
      }],
      'bidid': '6894227111893743356',
      'cur': 'AUD'
    };

    let bidderRequest = {
      'bidderCode': 'playgroundxyz'
    };

    it('should get correct bid response', function () {
      let expectedResponse = [
        {
          'requestId': '221f2bdc1fbc31',
          'cpm': 1,
          'creativeId': 91673066,
          'width': 300,
          'height': 50,
          'ad': '<script src=\'pgxyz\'></script>',
          'mediaType': 'banner',
          'currency': 'AUD',
          'ttl': 300,
          'netRevenue': true
        }
      ];
      let result = spec.interpretResponse({ body: response }, {bidderRequest});
      expect(Object.keys(result[0])).to.have.members(Object.keys(expectedResponse[0]));
    });

    it('handles nobid response', function () {
      const response = undefined;
      let result = spec.interpretResponse({ body: response }, {bidderRequest});
      expect(result.length).to.equal(0);
    });
  });

  describe('buildRequests', function () {
    let bidRequests = [
      {
        'bidder': 'playgroundxyz',
        'params': {
          'publisherId': 'PUB_FAKE'
        },
        'adUnitCode': 'adunit-code',
        'sizes': [[300, 250]],
        'bidId': '321db112312as',
        'bidderRequestId': '23edabce2731sd6',
        'auctionId': '12as040790a475'
      }
    ];

    it('should not populate GDPR', function () {
      let bidRequest = Object.assign([], bidRequests);
      const request = spec.buildRequests(bidRequest);
      let data = JSON.parse(request.data);
      expect(data).to.not.have.property('user');
      expect(data).to.not.have.property('regs');
    });

    it('should populate GDPR and consent string when consetString is presented but not gdpApplies', function () {
      let bidRequest = Object.assign([], bidRequests);
      const request = spec.buildRequests(bidRequest, {gdprConsent: {consentString: GDPR_CONSENT}});
      let data = JSON.parse(request.data);
      expect(data.regs.ext.gdpr).to.equal(0);
      expect(data.user.ext.consent).to.equal('XYZ-CONSENT');
    });

    it('should populate GDPR and consent string when gdpr is set to true', function () {
      let bidRequest = Object.assign([], bidRequests);
      const request = spec.buildRequests(bidRequest, {gdprConsent: {gdprApplies: true, consentString: GDPR_CONSENT}});
      let data = JSON.parse(request.data);
      expect(data.regs.ext.gdpr).to.equal(1);
      expect(data.user.ext.consent).to.equal('XYZ-CONSENT');
    });

    it('should populate GDPR and consent string when gdpr is set to false', function () {
      let bidRequest = Object.assign([], bidRequests);
      const request = spec.buildRequests(bidRequest, {gdprConsent: {gdprApplies: false, consentString: GDPR_CONSENT}});
      let data = JSON.parse(request.data);
      expect(data.regs.ext.gdpr).to.equal(0);
      expect(data.user.ext.consent).to.equal('XYZ-CONSENT');
    });
  });

  describe('getUserSyncs', function () {
    const syncUrl = '//ib.adnxs.com/getuidnb?https://ads.playground.xyz/usersync?partner=appnexus&uid=$UID';

    describe('when iframeEnabled is true', function () {
      const syncOptions = {
        'iframeEnabled': true
      }
      it('should return one image type user sync pixel', function () {
        let result = spec.getUserSyncs(syncOptions);
        expect(result.length).to.equal(1);
        expect(result[0].type).to.equal('image')
        expect(result[0].url).to.equal(syncUrl);
      });
    });

    describe('when iframeEnabled is false', function () {
      const syncOptions = {
        'iframeEnabled': false
      }
      it('should return one image type user sync pixel', function () {
        let result = spec.getUserSyncs(syncOptions);
        expect(result.length).to.equal(1);
        expect(result[0].type).to.equal('image')
        expect(result[0].url).to.equal(syncUrl);
      });
    });
  })
});


text:
<?
   # $Id: login.php3,v 1.19 2001-09-28 00:05:38 dan Exp $
   #
   # Copyright (c) 1998-2001 DVL Software Limited

//echo "UserID = $UserID";
   require("./include/common.php");
   require("./include/freshports.php");
   require("./include/databaselogin.php");
//   require("./include/getvalues.php");

   freshports_Start("title",
               "freshports - new ports, applications",
               "FreeBSD, index, applications, ports");

//$Debug=1;

if ($Debug) echo 'origin = ' . rawurlencode($origin) . "'
\n";

$origin=rawurlencode($origin);

if ($submit) {
//   $Debug=1;
   // process form

   if ($Debug) {
      while (list($name, $value) = each($HTTP_POST_VARS)) {
         echo "$name = $value
\n";
      }
   }

   $OK = 1;

   $errors = "";
   $UserID = addslashes($UserID);

   // test for existance of user id
   $Cookie = UserToCookie($UserID);

   if ($Debug) {
      echo "Cookie = $Cookie
\n";
   }

   $sql = "select * from users where username = '$UserID'".
	  " and password = '$Password' ";

   if ($Debug) {
      echo "$sql
\n";
   }

   $result = mysql_query($sql, $db) or die('query failed ' . mysql_error());

   if (!mysql_numrows($result)) {
      $LoginFailed = 1;
   } else {

      if ($Debug) {
         echo "well, debug was on, so I would have taken you to '$origin'
\n";
      } else {
         SetCookie("visitor", $Cookie, time() + 60*60*24*120, '/');
         // Redirect browser to PHP web site
         if ($origin == "/index.php3") {
            $origin = "/";
         }
         header("Location: " . rawurldecode($origin));
         // Make sure that code below does not get executed when we redirect.
         exit;
      }
   }
}
?>

<title>freshports -- Login</title>
<meta name="description" content="freshports - new ports, applications">
<meta name="keywords" content="FreeBSD, index, applications, ports">

 <? //include("./include/header.php") ?>

<?
if ($LoginFailed) {
echo '

Login Failed!

The User ID and password you supplied could not be used to login.	This could be for one of the following reasons:

The login id is incorrect

The password is incorrect

Both of the above

If you need help, please ask in the forum.

';
}

echo '

';

echo '
';

echo '
Login Details
';

echo '
';
include ("./include/login.php");

echo "	";

echo"

";

echo '
Forgotten your password?';

?>

    <? include("./include/side-bars.php") ?>

<? include("./include/footer.php") ?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">


text:
package Motor;

import org.ros.message.MessageListener;

import MotorControl.RobotVelocityController;
import rss_msgs.MotionMsg;

public class MotorListener implements MessageListener<MotionMsg> {

    private RobotVelocityController controller;

    public MotorListener(RobotVelocityController rvc){
	controller = rvc;
    }

    @Override
	public void onNewMessage(rss_msgs.MotionMsg msg){

	//System.out.println("got velocity command: " + msg.translationalVelocity + ", " + msg.rotationalVelocity);

	double left = msg.getTranslationalVelocity();
	double right = msg.getTranslationalVelocity();

	left -= msg.getRotationalVelocity();
	right += msg.getRotationalVelocity();

	left *= 3.5;
	right *= 3.5;
	controller.setDesiredAngularVelocity(left, right);

    }
}


text:
/**
 *
 */
package grammar.model.nouns;

import grammar.model.Multiplicity;
import grammar.model.PseudoEnum;
import grammar.model.WordMatcher;
import grammar.model.factory.NounClassFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class NounForm implements PseudoEnum<NounForm> {
	private static final Map<String, NounForm> INSTANCE_MAP = new HashMap<String, NounForm>();
	private static final Set<NounForm> INSTANCES = new HashSet<NounForm>();

	private static int sequenceGenerator = 0;

	private final int sequence;
	private final Multiplicity multiplicity;
	private final List<NounClass> nounClasses;
	private final String text;
	private Noun noun;

	public NounForm(Multiplicity multiplicity, List<NounClass> nounClasses,
			String text) {
		if (nounClasses.size() == 0)
			throw new IllegalArgumentException("No noun class defined for noun form "+text+".");

		sequence = sequenceGenerator++;
		this.multiplicity = multiplicity;
		this.nounClasses = Collections.unmodifiableList(nounClasses);
		this.text = text;

		INSTANCE_MAP.put(text, this);
		INSTANCES.add(this);
	}

	void setNoun(Noun noun) {
		this.noun = noun;
	}

	public Noun getNoun() {
		return noun;
	}

	public static NounForm[] getForms(NounClass nounClass, Multiplicity multiplicity) {
		Set<NounForm> f = new HashSet<NounForm>();

		for (NounForm nounForm : INSTANCE_MAP.values()) {
			if (nounClass == null || nounForm.getNounClasses().equals(nounClass)) {
				if (multiplicity == null || nounForm.getMultiplicity().equals(multiplicity)) {
					 f.add(nounForm);
				}
			}
		}
		return f.toArray(new NounForm[]{});
	}

	public WordMatcher getNounClassMatcher() {
		try {
			return NounClassFactory.getInstance().getClosestMatch(text).getNounMatcher(text);
		}
		catch (IllegalArgumentException iae) {
			return null;
		}
	}

	public int ordinal() {
		return sequence;
	}

	public int compareTo(NounForm o) {
		return ordinal() - o.ordinal();
	}

	public static NounForm[] values() {
		return INSTANCES.toArray(new NounForm[]{});
	}

	public static NounForm valueOf(String key) {
		NounForm m = INSTANCE_MAP.get(key);
		if (m == null)
			throw new IllegalArgumentException("No such NounForm: '"+key+"'.");
		return m;
	}

	public boolean isRegular() {
		return getRegularityCategory().equals(RegularityCategory.REGULAR);
	}

	public boolean isException() {
		return getRegularityCategory().equals(RegularityCategory.EXCEPTION);
	}

	public boolean isUncovered() {
		return getRegularityCategory().equals(RegularityCategory.NOT_COVERED);
	}

	private RegularityCategory getRegularityCategory() {
		try {
			NounClass guess = NounClass.guessGender(getText());
			return nounClasses.size() > 1 ? RegularityCategory.EXCEPTION :
				(nounClasses.get(0).equals(guess) ? RegularityCategory.REGULAR : RegularityCategory.EXCEPTION);
		}
		catch (IllegalArgumentException e) {
			return RegularityCategory.NOT_COVERED;
		}
	}

	public Multiplicity getMultiplicity() {
		return multiplicity;
	}

	public List<NounClass> getNounClasses() {
		return Collections.unmodifiableList(nounClasses);
	}

	public String getText() {
		return text;
	}

	public String toString() {
		return getText();
	}

	public enum RegularityCategory {
		REGULAR, NOT_COVERED, EXCEPTION
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + sequence;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof NounForm))
			return false;
		final NounForm other = (NounForm) obj;
		if (sequence != other.sequence)
			return false;
		return true;
	}
}


text:
package apollo.config;

import apollo.datamodel.*;

import java.util.*;
  /**
   * areOverlapping determines if two SeqFeatureIs overlap using the
   * currently defined gene definition (from Config.getGeneDefinition().
   * Obviously this method can be called with FeatureSets such as
   * Genes or Transcripts - it should handle such cases.
   */
public interface OverlapI {

  public boolean areOverlapping(SeqFeatureI sa,SeqFeatureI sb);

}


text:
<?php

namespace Platformsh\Cli\Command;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class UserDeleteCommand extends PlatformCommand
{

    protected function configure()
    {
        $this
          ->setName('user:delete')
          ->setDescription('Delete a user')
          ->addArgument('email', InputArgument::REQUIRED, "The user's email address");
        $this->addProjectOption();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!$this->validateInput($input, $output)) {
            return 1;
        }

        $project = $this->getSelectedProject();

        $email = $input->getArgument('email');
        foreach ($project->getUsers() as $user) {
            $account = $user->getAccount();
            if ($account['email'] === $email) {
                $selectedUser = $user;
                break;
            }
        }
        if (empty($selectedUser)) {
            $output->writeln("User not found: <error>$email</error>");
            return 1;
        }

        /** @var \Platformsh\Cli\Helper\PlatformQuestionHelper $questionHelper */
        $questionHelper = $this->getHelper('question');

        if (!$questionHelper->confirm("Are you sure you want to delete the user <info>$email</info>?", $input, $output)) {
            return 1;
        }

        $selectedUser->delete();

        $output->writeln("User <info>$email</info> deleted");
        return 0;
    }

}


text:
title: "Notes on VAEs"
---

I prepared these [slides]({{ site.url }}/images/vae_notes.pdf) for
a reading group lecture on variational autoencoders and sequence-to-sequence
modeling. My aim was to provide some visual intuition without sacrificing
mathematical precision. I hope you enjoy the notes, feel free to use the images
in any of your work.

<figure>
        <img src="{{ site.url }}/images/vae_screenshot.png">
</figure>


text:
<?php

namespace IronBound\DB\Table\Column;

use IronBound\DB\Saver\CommentSaver;
use IronBound\DB\Table\Column\Contracts\Savable;
use IronBound\DB\Table\ForeignKey\DeleteConstrainable;
use IronBound\DB\Table\Table;
use IronBound\DB\WP\Comments;

/**
 * Class ForeignComment
 * @package IronBound\DB\Table\Column
 */
class ForeignComment extends BaseColumn implements Foreign, DeleteConstrainable {

	/**
	 * ForeignComment constructor.
	 *
	 * @param string $name Column name.
	 */
	public function __construct( $name ) {
		parent::__construct( $name );
	}

	/**
	 * @inheritDoc
	 */
	public function get_foreign_table() {
		return new Comments();
	}

	/**
	 * @inheritDoc
	 */
	public function get_foreign_table_column_name() {
		return 'comment_ID';
	}

	/**
	 * @inheritDoc
	 */
	public function get_definition() {
		return "{$this->name} bigint(20) unsigned NOT NULL";
	}

	/**
	 * @inheritDoc
	 */
	public function get_mysql_type() {
		return 'BIGINT';
	}

	/**
	 * @inheritDoc
	 */
	public function convert_raw_to_value( $raw ) {
		return get_comment( $raw );
	}

	/**
	 * @inheritDoc
	 */
	public function prepare_for_storage( $value ) {

		if ( $value instanceof \WP_Comment || $value instanceof \stdClass ) {
			return $value->comment_ID;
		}

		return absint( $value );
	}

	/**
	 * @inheritDoc
	 */
	public function register_delete_callback( $callback ) {

		add_action( 'delete_comment', function ( $comment_id ) use ( $callback ) {
			$callback( $comment_id, get_comment( $comment_id ) );
		} );
	}
}


text:
<!DOCTYPE html>
<title>SpeechSynthesisUtterance basics</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>
const DEFAULTS = {
  text: '',
  lang: '',
  voice: null,
  volume: 1,
  rate: 1,
  pitch: 1,
};

for (const prop in DEFAULTS) {
  test(function() {
    const utt = new SpeechSynthesisUtterance();
    assert_equals(utt[prop], DEFAULTS[prop], prop);
  }, `new SpeechSynthesisUtterance() default ${prop}`);
}

test(function() {
  const utt = new SpeechSynthesisUtterance("hello");
  assert_equals(utt.text, 'hello', 'text');
  // check that the other properties retain their defaults
  for (const prop in DEFAULTS) {
    if (prop != 'text') {
      assert_equals(utt[prop], DEFAULTS[prop], prop);
    }
  }
}, 'new SpeechSynthesisUtterance("hello") text and defaults');

test(function() {
  const utt = new SpeechSynthesisUtterance(null);
  assert_equals(utt.text, 'null');
}, 'new SpeechSynthesisUtterance(null)');

test(function() {
  const utt = new SpeechSynthesisUtterance(undefined);
  // See https://github.com/w3c/speech-api/pull/48.
  assert_equals(utt.text, '');
}, 'new SpeechSynthesisUtterance(undefined)');

test(function() {
  const utt = new SpeechSynthesisUtterance();
  utt.text = 'word';
  assert_equals(utt.text, 'word');
}, 'SpeechSynthesisUtterance text setter');

// TODO: setters https://github.com/w3c/speech-api/issues/29
</script>


text:
'use strict';

exports.Button = require('./component/Button');
exports.Check = require('./component/Check');
exports.CheckGroup = require('./component/CheckGroup');
exports.ColorPicker = require('./component/ColorPicker');
exports.Input = require('./component/Input');
exports.Link = require('./component/Link');
exports.Menu = require('./component/Menu');
exports.Radio = require('./component/Radio');
exports.Select = require('./component/Select');
exports.SelectMultiple = require('./component/SelectMultiple');
exports.Spin = require('./component/Spin');
exports.Textarea = require('./component/Textarea');
exports.Tooltip = require('./component/Tooltip');
exports.Tumbler = require('./component/Tumbler');


text:
=begin
#EVE Swagger Interface

#An OpenAPI for EVE Online

OpenAPI spec version: 0.4.6.dev11

Generated by: https://github.com/swagger-api/swagger-codegen.git

=end

require 'spec_helper'
require 'json'
require 'date'

# Unit tests for ESIClient::GetStatusOk
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'GetStatusOk' do
  before do
    # run before each test
    @instance = ESIClient::GetStatusOk.new
  end

  after do
    # run after each test
  end

  describe 'test an instance of GetStatusOk' do
    it 'should create an instact of GetStatusOk' do
      expect(@instance).to be_instance_of(ESIClient::GetStatusOk)
    end
  end
  describe 'test attribute "players"' do
    it 'should work' do
       # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  describe 'test attribute "server_version"' do
    it 'should work' do
       # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  describe 'test attribute "start_time"' do
    it 'should work' do
       # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

  describe 'test attribute "vip"' do
    it 'should work' do
       # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
    end
  end

end


text:
include!("../libbuild.rs");

fn main() { habitat::common(); }


text:
var mapnik = require('../');
var assert = require('assert');
var fs = require('fs');
var path = require('path');

var grid;
var view;

describe('mapnik.GridView ', function() {
    before(function(done) {
        grid = new mapnik.Grid(256, 256);
        view = grid.view(0, 0, 256, 256);
        done();
    });

    it('should be solid', function() {
        assert.equal(view.isSolidSync(), true);
    });

    it('should be solid (async)', function(done) {
        view.isSolid(function(err,solid,pixel) {
            assert.equal(solid, true);
            if (mapnik.versions.mapnik_number < 200100) {
                assert.equal(pixel, 0);
            } else {
                assert.ok(pixel == -1 * 0x7FFFFFFFFFFFFFFF || pixel == -2147483648);
                assert.ok(pixel.toFixed() == mapnik.Grid.base_mask.toFixed() || pixel == -2147483648);
            }
            done();
        });
    });

    it('should report grid base_mask value for pixel', function() {
        var pixel = view.getPixel(0, 0);
        if (mapnik.versions.mapnik_number < 200100) {
            assert.equal(pixel, 0);
        } else {
            assert.ok(pixel == -1 * 0x7FFFFFFFFFFFFFFF || pixel == -2147483648);
            assert.ok(pixel.toFixed() == mapnik.Grid.base_mask.toFixed() || pixel == -2147483648);
        }
    });

    it('should be painted after rendering', function(done) {
        var map = new mapnik.Map(256, 256);
        map.loadSync('./test/stylesheet.xml');
        map.zoomAll();
        var options = {'layer': 0,
                       'fields': ['NAME']
                      };
        var grid = new mapnik.Grid(map.width, map.height, {key: '__id__'});
        map.render(grid, options, function(err, grid) {
            var view = grid.view(0, 0, 256, 256);
            assert.equal(view.isSolidSync(), false);
            // hit alaska (USA is id 207)
            assert.equal(view.getPixel(25, 100), 207);
            view.isSolid(function(err,solid,pixel){
                assert.equal(solid, false);
                assert.equal(pixel, undefined);
                done();
            });
        });
    });
});


text:
# How to read a file

This example below will show you how to build complex pipelines to read files without ever loading the whole file in memory, allowing you to read any file's size.

This example below looks for a user in a csv file with a score above `100`.

```php
use Innmind\Immutable\{
    Sequence,
    Str,
};

$lines = Sequence::lazy(function(callable $registerCleanup) {
    $handle = \fopen('users.csv', 'r');
    $registerCleanup(fn() => \fclose($handle));

    while (!\feof($handle)) {
        yield (string) \fgets($handle);
    }

    \fclose($handle);
});
/** @var Maybe<User> */
$user = $lines
    ->map(fn(string $line) => Str::of($line))
    ->map(fn(Str $line) => $line->trim())
    ->filter(fn(Str $line) => !$line->empty())
    ->filter(fn(Str $line) => $line->contains(','))
    ->map(fn(Str $line) => $line->split(','))
    ->map(fn(Sequence $columns) => User::of($columns)) // ficticious class
    ->find(fn(User $user) => $user->score() > 100);
```

The final `$user` variable is an instance of `Maybe` because the user may or may not exist.

If a user is found before the end of the file the sequence will stop reading the file and call the function passed to `$registerCleanup` allowing you to close the file handle properly.

Since this is a lazy sequence the file is iterated over only when trying to extract a concrete value, in this case via `->find()`. This means that even though the pipeline contains multiple steps the file is read only once. This decoupling between reading the file and building a pipeline to compute a value allows you to split the construction of the pipeline across multiple layers in your application without worrying about performance.

The other advantage of this technique is that it allows to read files that may not fit in memory.

## Merging multiple files in a single pipeline

The lazyness described above still works when you combine multiple lazy sequences.

```php
$openFile = fn(string $name) => function(callable $registerCleanup) use ($name) {
    $handle = \fopen($name, 'r');
    $registerCleanup(fn() => \fclose($handle));

    while (!\feof($handle)) {
        yield (string) \fgets($handle);
    }

    \fclose($handle);
};

$users = Sequence::lazy($openFile('users1.csv'))
    ->append(Sequence::lazy($openFile('users2.csv')))
    ->append(Sequence::lazy($openFile('users3.csv')));

/** @var callable(Sequence<string>): Maybe<User> $findUser */
$findUser = function(Sequence $users): Maybe {
    // todo build a pipeline to find a user
};

$user = $findUser($users);
```

Here we create a sequence that will sequentially read the 3 files `users1.csv`, `users2.csv` and `users3.csv` but the `$findUser` function is not aware of where the data comes from. This composition will open `users2.csv` only if the user is not found in `users1.csv`.

In this example the 3 sources are all files but you could mix the sources with different generators, for example you could combine from a file with another one coming from a database.


text:
'use strict';Object.defineProperty(exports, "__esModule", { value: true });var _jestUtil;

function _load_jestUtil() {return _jestUtil = require('jest-util');}var _istanbulApi;
function _load_istanbulApi() {return _istanbulApi = require('istanbul-api');}var _chalk;
function _load_chalk() {return _chalk = _interopRequireDefault(require('chalk'));}var _isCi;
function _load_isCi() {return _isCi = _interopRequireDefault(require('is-ci'));}var _istanbulLibCoverage;
function _load_istanbulLibCoverage() {return _istanbulLibCoverage = _interopRequireDefault(require('istanbul-lib-coverage'));}var _istanbulLibSourceMaps;
function _load_istanbulLibSourceMaps() {return _istanbulLibSourceMaps = _interopRequireDefault(require('istanbul-lib-source-maps'));}var _pify;
function _load_pify() {return _pify = _interopRequireDefault(require('pify'));}var _workerFarm;
function _load_workerFarm() {return _workerFarm = _interopRequireDefault(require('worker-farm'));}var _base_reporter;
function _load_base_reporter() {return _base_reporter = _interopRequireDefault(require('./base_reporter'));}var _coverage_worker;

function _load_coverage_worker() {return _coverage_worker = _interopRequireDefault(require('./coverage_worker'));}var _path;
function _load_path() {return _path = _interopRequireDefault(require('path'));}var _glob;
function _load_glob() {return _glob = _interopRequireDefault(require('glob'));}function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _asyncToGenerator(fn) {return function () {var gen = fn.apply(this, arguments);return new Promise(function (resolve, reject) {function step(key, arg) {try {var info = gen[key](arg);var value = info.value;} catch (error) {reject(error);return;}if (info.done) {resolve(value);} else {return Promise.resolve(value).then(function (value) {step("next", value);}, function (err) {step("throw", err);});}}return step("next");});};}  // eslint-disable-next-line import/default
const FAIL_COLOR = (_chalk || _load_chalk()).default.bold.red;const RUNNING_TEST_COLOR = (_chalk || _load_chalk()).default.bold.dim;const isInteractive = process.stdout.isTTY && !(_isCi || _load_isCi()).default;class CoverageReporter extends (_base_reporter || _load_base_reporter()).default {

  constructor(globalConfig) {
    super();
    this._coverageMap = (_istanbulLibCoverage || _load_istanbulLibCoverage()).default.createCoverageMap({});
    this._globalConfig = globalConfig;
    this._sourceMapStore = (_istanbulLibSourceMaps || _load_istanbulLibSourceMaps()).default.createSourceMapStore();
  }

  onTestResult(
  test,
  testResult,
  aggregatedResults)
  {
    if (testResult.coverage) {
      this._coverageMap.merge(testResult.coverage);
      // Remove coverage data to free up some memory.
      delete testResult.coverage;

      Object.keys(testResult.sourceMaps).forEach(sourcePath => {
        let coverage, inputSourceMap;
        try {
          coverage = this._coverageMap.fileCoverageFor(sourcePath);var _coverage$toJSON =
          coverage.toJSON();inputSourceMap = _coverage$toJSON.inputSourceMap;
        } finally {
          if (inputSourceMap) {
            this._sourceMapStore.registerMap(sourcePath, inputSourceMap);
          } else {
            this._sourceMapStore.registerURL(
            sourcePath,
            testResult.sourceMaps[sourcePath]);

          }
        }
      });
    }
  }

  onRunComplete(
  contexts,
  aggregatedResults)
  {var _this = this;return _asyncToGenerator(function* () {
      yield _this._addUntestedFiles(_this._globalConfig, contexts);
      let map = _this._coverageMap;
      let sourceFinder;
      if (_this._globalConfig.mapCoverage) {var _sourceMapStore$trans =
        _this._sourceMapStore.transformCoverage(map);map = _sourceMapStore$trans.map;sourceFinder = _sourceMapStore$trans.sourceFinder;
      }

      const reporter = (0, (_istanbulApi || _load_istanbulApi()).createReporter)();
      try {
        if (_this._globalConfig.coverageDirectory) {
          reporter.dir = _this._globalConfig.coverageDirectory;
        }

        let coverageReporters = _this._globalConfig.coverageReporters || [];
        if (
        !_this._globalConfig.useStderr &&
        coverageReporters.length &&
        coverageReporters.indexOf('text') === -1)
        {
          coverageReporters = coverageReporters.concat(['text-summary']);
        }

        reporter.addAll(coverageReporters);
        reporter.write(map, sourceFinder && { sourceFinder });
        aggregatedResults.coverageMap = map;
      } catch (e) {
        console.error(
        (_chalk || _load_chalk()).default.red(`
        Failed to write coverage reports:
        ERROR: ${e.toString()}
        STACK: ${e.stack}
      `));

      }

      _this._checkThreshold(_this._globalConfig, map);})();
  }

  _addUntestedFiles(globalConfig, contexts) {
    const files = [];
    contexts.forEach(context => {
      const config = context.config;
      if (
      globalConfig.collectCoverageFrom &&
      globalConfig.collectCoverageFrom.length)
      {
        context.hasteFS.
        matchFilesWithGlob(globalConfig.collectCoverageFrom, config.rootDir).
        forEach(filePath =>
        files.push({
          config,
          path: filePath }));

      }
    });
    if (!files.length) {
      return Promise.resolve();
    }

    if (isInteractive) {
      process.stderr.write(
      RUNNING_TEST_COLOR('Running coverage on untested files...'));

    }

    let worker;
    let farm;
    if (this._globalConfig.maxWorkers <= 1) {
      worker = (0, (_pify || _load_pify()).default)((_coverage_worker || _load_coverage_worker()).default);
    } else {
      farm = (0, (_workerFarm || _load_workerFarm()).default)(
      {
        autoStart: true,
        maxConcurrentCallsPerWorker: 1,
        maxConcurrentWorkers: this._globalConfig.maxWorkers,
        maxRetries: 2 },

      require.resolve('./coverage_worker'));

      worker = (0, (_pify || _load_pify()).default)(farm);
    }
    const instrumentation = [];
    files.forEach(fileObj => {
      const filename = fileObj.path;
      const config = fileObj.config;
      if (!this._coverageMap.data[filename]) {
        const promise = worker({
          config,
          globalConfig,
          path: filename }).

        then(result => {
          if (result) {
            this._coverageMap.addFileCoverage(result.coverage);
            if (result.sourceMapPath) {
              this._sourceMapStore.registerURL(
              filename,
              result.sourceMapPath);

            }
          }
        }).
        catch(error => {
          console.error((_chalk || _load_chalk()).default.red(error.message));
        });
        instrumentation.push(promise);
      }
    });

    const cleanup = () => {
      if (isInteractive) {
        (0, (_jestUtil || _load_jestUtil()).clearLine)(process.stderr);
      }
      if (farm) {
        (_workerFarm || _load_workerFarm()).default.end(farm);
      }
    };

    return Promise.all(instrumentation).
    then(cleanup).
    catch(cleanup);
  }

  _checkThreshold(globalConfig, map) {
    if (globalConfig.coverageThreshold) {
      function check(name, thresholds, actuals) {
        return [
        'statements',
        'branches',
        'lines',
        'functions'].
        reduce((errors, key) => {
          const actual = actuals[key].pct;
          const actualUncovered = actuals[key].total - actuals[key].covered;
          const threshold = thresholds[key];

          if (threshold != null) {
            if (threshold < 0) {
              if (threshold * -1 < actualUncovered) {
                errors.push(
                `Jest: Uncovered count for ${key} (${actualUncovered})` +
                `exceeds ${name} threshold (${-1 * threshold})`);

              }
            } else if (actual < threshold) {
              errors.push(
              `Jest: Coverage for ${key} (${actual}` +
              `%) does not meet ${name} threshold (${threshold}%)`);

            }
          }
          return errors;
        }, []);
      }

      const expandedThresholds = {};
      Object.keys(globalConfig.coverageThreshold).forEach(filePathOrGlob => {
        if (filePathOrGlob !== 'global') {
          const pathArray = (_glob || _load_glob()).default.sync(filePathOrGlob);
          pathArray.forEach(filePath => {
            expandedThresholds[(_path || _load_path()).default.resolve(filePath)] =
            globalConfig.coverageThreshold[filePathOrGlob];
          });
        } else {
          expandedThresholds.global = globalConfig.coverageThreshold.global;
        }
      });

      const filteredCoverageSummary = map.
      files().
      filter(
      filePath => Object.keys(expandedThresholds).indexOf(filePath) === -1).

      map(filePath => map.fileCoverageFor(filePath)).
      reduce((summary, fileCov) => {
        return summary === undefined || summary === null ?
        summary = fileCov.toSummary() :
        summary.merge(fileCov.toSummary());
      }, undefined);

      const errors = [].concat.apply(
      [],
      Object.keys(expandedThresholds).
      map(thresholdKey => {
        if (thresholdKey === 'global') {
          if (filteredCoverageSummary !== undefined) {
            return check(
            'global',
            expandedThresholds.global,
            filteredCoverageSummary);

          } else {
            return [];
          }
        } else {
          if (map.files().indexOf(thresholdKey) !== -1) {
            return check(
            thresholdKey,
            expandedThresholds[thresholdKey],
            map.fileCoverageFor(thresholdKey).toSummary());

          } else {
            return [
            `Jest: Coverage data for ${thresholdKey} was not found.`];

          }
        }
      }).
      filter(errorArray => {
        return (
          errorArray !== undefined &&
          errorArray !== null &&
          errorArray.length > 0);

      }));

      if (errors.length > 0) {
        this.log(`${FAIL_COLOR(errors.join('\n'))}`);
        this._setError(new Error(errors.join('\n')));
      }
    }
  }

  // Only exposed for the internal runner. Should not be used
  getCoverageMap() {
    return this._coverageMap;
  }}exports.default = CoverageReporter;


text:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace DAC
{
    class UDP
    {
        private static Boolean closeListener = true;
        public static Boolean CloseListener
        {
            get { return closeListener; }
        }
        private static UdpClient listener = null;
        private static IPAddress sendToAddress = null;
        private static IPEndPoint sendingEndPoint = null;
        private static IPEndPoint listenerEndPoint = null;
        private static Socket sendingSocket = null;
        private static readonly string newline = Environment.NewLine;
        private static string receivedData2 = "";

        #region comments
        // Create a socket object. This is the fundamental device used to network
        // communications. When creating this object we specify:
        //
        // Internetwork:    We use the internet communications protocol
        // Dgram:           We use datagrams or broadcast to everyone rather than send to
        //                  a specific listener
        // UDP:             the messages are to be formated as user datagram protocal.
        //                  The last two seem to be a bit redundant.
        #endregion

        public static void UDPSender(string ipAdress, int port, string textToSend)
        {
            #region comments
            // create an address object and populate it with the IP address that we will use
            // in sending at data to. This particular address ends in 255 meaning we will send
            // to all devices whose address begins with 192.168.2.
            #endregion

            ipAdress = ipAdress.Substring(0, ipAdress.LastIndexOf(".") + 1) + "255"; // 127.0.0.1 -> 127.0.0.255

            sendingSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sendToAddress = IPAddress.Parse(ipAdress);
            sendingEndPoint = new IPEndPoint(sendToAddress, port);

            byte[] send_buffer = Encoding.ASCII.GetBytes(textToSend);

            try
            {
                sendingSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 0); // ???
                sendingSocket.SendTo(send_buffer, sendingEndPoint);
                sendingSocket.Close();
            }
            catch (Exception e)
            {
                ImportExport.LogMessage("Send Exception: " + e.Message, true);
            }
        }

        public static void StartListener(int listenPort)
        {
            try
            {
                listener = new UdpClient(listenPort);
            }
            catch
            {
                return;
            }
            listenerEndPoint = new IPEndPoint(IPAddress.Any, listenPort);

            byte[] receiveByteArray;

            try
            {
                ImportExport.LogMessage("Listener started on Port " + listenPort + "...", true);
                closeListener = false;

                while (!closeListener)
                {
                    receiveByteArray = listener.Receive(ref listenerEndPoint);

                    if (receiveByteArray.Length > 0)
                    {
                        if (FormMain.receivedData.Length == 0)
                        {
                            FormMain.receivedData = ":" + Encoding.ASCII.GetString(receiveByteArray, 0, receiveByteArray.Length) + ":";

                            if (FormMain.receivedData.Length > 4 && FormMain.logDetail)
                                ImportExport.LogMessage("Received   package: " + FormMain.receivedData, true);
                        }
                        else
                        {
                            receivedData2 = Encoding.ASCII.GetString(receiveByteArray, 0, receiveByteArray.Length);
                            FormMain.receivedData += ":" + receivedData2.Substring(receivedData2.IndexOf("*") + 1) + ":";

                            if (FormMain.receivedData.Length > 4 && FormMain.logDetail)
                                ImportExport.LogMessage("+ Received package: " + FormMain.receivedData, true);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ImportExport.LogMessage("Listener Exception: " + e.Message, true);
            }
            finally
            {
                ListenerClose();
            }
        }

        public static void ListenerClose()
        {
            try
            {
                closeListener = true;
                listener.Close();
            }
            catch (Exception e)
            {
                ImportExport.LogMessage("ListenerClose ... " + e.ToString(), true);
            }
        }
    }
}