text:
package net.sf.qualitytest.blueprint;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.text.MessageFormat;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import net.sf.qualitycheck.Check;
import net.sf.qualitycheck.Throws;
import net.sf.qualitycheck.exception.IllegalNullArgumentException;
import net.sf.qualitytest.ModifierBits;
import net.sf.qualitytest.blueprint.configuration.DefaultBlueprintConfiguration;
import net.sf.qualitytest.blueprint.configuration.RandomBlueprintConfiguration;
import net.sf.qualitytest.blueprint.invocationhandler.ProxyInvocationHandler;
import net.sf.qualitytest.blueprint.invocationhandler.RefreshingBlueprintInvocationHandler;
import net.sf.qualitytest.exception.BlueprintException;
import net.sf.qualitytest.exception.NoPublicConstructorException;

/**
 * Blueprinting is a technique that makes writing test easier. For unit-testing you often need data-objects, where the
 * actual content of the objects does not matter. {@code Blueprint} creates data-objects filled with random or defined
 * data automatically based on the "Blue-Print" which is the Class itself.
 *

 * Blueprinting makes tests more maintainable as they depend less on test-data. Imagine, you add a new required
 * attribute to a class. Usually, you have to add this to all tests using this class. With blueprinting you just have to
 * add it to certain tests where the contents of the logic does actually matter. Most of the time the randomly generated
 * value by {@code Blueprint} is just fine.
 *

 * {@code Blueprint} is similar to C#'s AutoFixture (https://github.com/AutoFixture/AutoFixture#readme).
 *

 * A simple example:
 *
 *

 * final BlueprintConfiguration config = new RandomBlueprintConfiguration().with("email", "mail@example.com");
 * final User user = Blueprint.construct(User.class, config);
 *

 *
 * or simpler
 *
 *

 * final User user = Blueprint.random().with("email", "mail@example.com").construct(User.class);
 *

 *
 * {@code Blueprint} offers two custom configurations. A {@code DefaultBlueprintConfiguration} which fills any object
 * using default, empty or 0 values. The second configuration, {@code RandomBlueprintConfiguration} will always generate
 * a random value. Both fill child objects using a deep-tree-search.
 *

 * Utilities for collections can be found in {@code CollectionBlueprint}.
 *
 * @see DefaultBlueprintConfiguration
 * @see RandomBlueprintConfiguration
 *
 * @author Dominik Seichter
 */
public final class Blueprint {

	private static final BlueprintConfiguration DEFAULT_CONFIG = new DefaultBlueprintConfiguration();

	/**
	 * Blueprint a Java-Bean.
	 *
	 * This method will call the default constructor and fill all setters using blueprints.
	 *
	 * @param <T>
	 * @param clazz
	 *            a class, which must have a default constructor.
	 * @param config
	 *            a BlueprintConfiguration
	 * @param session
	 *            A {@code BlueprintSession}
	 * @return a blue printed instance of {@code T}
	 */
	@Throws(IllegalNullArgumentException.class)
	private static <T> T bean(@Nonnull final Class<T> clazz, @Nonnull final BlueprintConfiguration config,
			@Nonnull final BlueprintSession session) {
		Check.notNull(clazz, "clazz");
		Check.notNull(config, "config");
		Check.notNull(session, "sesion");

		final T obj = safeNewInstance(session, clazz);
		blueprintPublicMethods(obj, clazz, config, session);
		blueprintPublicAttributes(obj, clazz, config, session);
		return obj;
	}

	/**
	 * Blueprint all attributes of an object.
	 *

	 * Static fields are ignored.
	 *
	 * @param <T>
	 *            type of object
	 * @param obj
	 *            Instance of the object
	 * @param clazz
	 *            Class of the object
	 * @param config
	 *            Configuration to apply
	 * @param session
	 *            A {@code BlueprintSession}
	 */
	private static <T> void blueprintAllAttributes(final T obj, final Class<T> clazz, final BlueprintConfiguration config,
			final BlueprintSession session) {
		for (final Field f : clazz.getDeclaredFields()) {
			final boolean isStatic = ModifierBits.isModifierBitSet(f.getModifiers(), Modifier.STATIC);
			if (!isStatic) {
				blueprintField(obj, f, config, session);
			}
		}
	}

	/**
	 * Blueprint a field.
	 *
	 * @param that
	 *            Instance of the object
	 * @param field
	 *            Accessible field
	 * @param config
	 *            configuration to use.
	 * @param session
	 *            A {@code BlueprintSession}
	 */
	private static void blueprintField(final Object that, final Field field, final BlueprintConfiguration config,
			final BlueprintSession session) {
		CreationStrategy<?> creator = config.findCreationStrategyForField(field);
		if (creator == null) {
			creator = config.findCreationStrategyForType(field.getType());
		}
		final Object value = blueprintObject(field.getType(), config, creator, session);

		final String action = MessageFormat.format("Setting field {0} to {1}.", field.getName(), value);
		SafeInvoke.invoke(new BlueprintExceptionRunnable<Object>(session, action) {
			@Override
			public Object runInternal() throws Exception {
				field.setAccessible(true);
				field.set(that, value);
				return null;
			}
		}, BlueprintException.class);

	}

	/**
	 * Blueprint a method.
	 *
	 * @param that
	 *            Instance of the object
	 * @param m
	 *            setter method
	 * @param config
	 *            configuration to use.
	 * @param session
	 *            A {@code BlueprintSession}
	 */
	private static void blueprintMethod(final Object that, final Method m, final BlueprintConfiguration config,
			final BlueprintSession session) {
		final CreationStrategy<?> creator = config.findCreationStrategyForMethod(m);
		if (creator != null) {
			final Class<?>[] parameterTypes = m.getParameterTypes();
			final Object[] values = new Object[parameterTypes.length];
			for (int i = 0; i < parameterTypes.length; i++) {
				values[i] = creator.createValue(parameterTypes[i], config, session);
			}

			final String action = MessageFormat.format("Invoking method {0} with arguments {1}.", m.getName(), values);
			SafeInvoke.invoke(new BlueprintExceptionRunnable<Object>(session, action) {
				@Override
				public Object runInternal() throws Exception {
					m.setAccessible(true);
					m.invoke(that, values);
					return null;
				}

			}, BlueprintException.class);
		}
	}

	@Nullable
	@SuppressWarnings({ "unchecked" })
	private static <T> T blueprintObject(@Nonnull final Class<T> clazz, @Nonnull final BlueprintConfiguration config,
			@Nullable final CreationStrategy<?> creator, @Nonnull final BlueprintSession session) {
		final boolean cycle = session.push(clazz);
		final T ret;
		if (cycle) {
			ret = (T) config.handleCycle(session, clazz);
		} else {
			if (creator != null) {
				ret = (T) creator.createValue(clazz, config, session);
			} else if (clazz.isInterface()) {
				ret = (T) proxy(clazz, config, session);
			} else if (hasPublicDefaultConstructor(clazz)) {
				ret = bean(clazz, config, session);
			} else {
				ret = immutable(clazz, config, session);
			}
		}
		session.pop();
		return ret;
	}

	/**
	 * Blueprint all public attributes in an object.
	 *
	 * Does nothing if {@code config.isWithPublicAttributes} is false.
	 *
	 * Static fields are ignored.
	 *
	 * @param <T>
	 *            type of object
	 * @param obj
	 *            Instance of the object
	 * @param clazz
	 *            Class of the object
	 * @param config
	 *            Configuration to apply
	 * @param session
	 *            A {@code BlueprintSession}
	 */
	private static <T> void blueprintPublicAttributes(final T obj, final Class<T> clazz, final BlueprintConfiguration config,
			final BlueprintSession session) {
		if (!config.isWithPublicAttributes()) {
			return;
		}

		for (final Field f : clazz.getFields()) {
			final boolean isStatic = ModifierBits.isModifierBitSet(f.getModifiers(), Modifier.STATIC);
			final boolean isFinal = ModifierBits.isModifierBitSet(f.getModifiers(), Modifier.FINAL);
			if (!isStatic && !isFinal) {
				blueprintField(obj, f, config, session);
			}
		}
	}

	/**
	 * Blueprint all non static public method in an object.
	 *
	 * @param <T>
	 *            type of object
	 * @param obj
	 *            Instance of the object
	 * @param clazz
	 *            Class of the object
	 * @param config
	 *            Configuration to apply
	 * @param session
	 *            A {@code BlueprintSession}
	 */
	private static <T> void blueprintPublicMethods(final T obj, final Class<T> clazz, final BlueprintConfiguration config,
			final BlueprintSession session) {
		for (final Method m : clazz.getMethods()) {
			if (isRelevant(m)) {
				blueprintMethod(obj, m, config, session);
			}
		}
	}

	/**
	 * Construct a Java-Object using a class as a blueprint.
	 *
	 * If the object has a default constructor, it will be called and all setters will be called. If the object does not
	 * have a default constructor the first constructor is called and filled with all parameters. Afterwards all setters
	 * will be called.
	 *
	 * @param <T>
	 * @param clazz
	 *            a class
	 * @return a blue printed instance of {@code T}
	 */
	@Nullable
	@Throws(IllegalNullArgumentException.class)
	public static <T> T construct(@Nonnull final Class<T> clazz) {
		Check.notNull(clazz, "clazz");

		return Blueprint.construct(clazz, DEFAULT_CONFIG, new BlueprintSession());
	}

	/**
	 * Construct a Java-Object using a class as a blueprint.
	 *
	 * If the object has a default constructor, it will be called and all setters will be called. If the object does not
	 * have a default constructor the first constructor is called and filled with all parameters. Afterwards all setters
	 * will be called.
	 *
	 * @param <T>
	 * @param clazz
	 *            a class
	 * @param config
	 *            a {@code BlueprintConfiguration}
	 * @return a blue printed instance of {@code T}
	 */
	@Nullable
	@Throws(IllegalNullArgumentException.class)
	public static <T> T construct(@Nonnull final Class<T> clazz, @Nonnull final BlueprintConfiguration config) {
		Check.notNull(clazz, "clazz");
		Check.notNull(config, "config");

		return Blueprint.construct(clazz, config, new BlueprintSession());
	}

	/**
	 * Construct a Java-Object using a class as a blueprint.
	 *
	 * If the object has a default constructor, it will be called and all setters will be called. If the object does not
	 * have a default constructor the first constructor is called and filled with all parameters. Afterwards all setters
	 * will be called.
	 *
	 * @param <T>
	 * @param clazz
	 *            a class
	 * @param config
	 *            a {@code BlueprintConfiguration}
	 * @param session
	 *            a {@code BlueprintSession}
	 * @return a blue printed instance of {@code T}
	 */
	@Nullable
	@Throws(IllegalNullArgumentException.class)
	public static <T> T construct(@Nonnull final Class<T> clazz, @Nonnull final BlueprintConfiguration config,
			@Nonnull final BlueprintSession session) {
		Check.notNull(clazz, "clazz");
		Check.notNull(config, "config");
		Check.notNull(session, "session");

		final CreationStrategy<?> creator = config.findCreationStrategyForType(clazz);
		return blueprintObject(clazz, config, creator, session);
	}

	/**
	 * Return a new configuration for default blueprinting with zero or empty default values.
	 *
	 * @return a new {@code DefaultBlueprintConfiguration}
	 */
	public static BlueprintConfiguration def() {
		return new DefaultBlueprintConfiguration();
	}

	/**
	 * Find the first public constructor in a class.
	 *
	 * @param <T>
	 *            type parameter of the class and constructor.
	 * @param clazz
	 *            the class object
	 */
	private static <T> Constructor<?> findFirstPublicConstructor(final Class<T> clazz) {
		final Constructor<?>[] constructors = clazz.getConstructors();
		for (final Constructor<?> c : constructors) {
			return c;
		}
		return null;
	}

	/**
	 * Test if a class has a public default constructor (i.e. a public constructor without constructor arguments).
	 *
	 * @param clazz
	 *            the class object.
	 * @return true if the class has a public default constructor.
	 */
	private static boolean hasPublicDefaultConstructor(final Class<?> clazz) {
		final Constructor<?>[] constructors = clazz.getConstructors();
		for (final Constructor<?> c : constructors) {
			if (c.getParameterTypes().length == 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Blueprint an immutable class based on the constructor parameters of the first public constructor.
	 *
	 * @param <T>
	 *            type parameter of the blueprinted class
	 * @param clazz
	 *            the class object
	 * @param config
	 *            the configuration
	 * @param session
	 *            A {@code BlueprintSession}
	 * @return a new blueprint of the class with all constructor parameters to filled.
	 */
	private static <T> T immutable(final Class<T> clazz, final BlueprintConfiguration config, final BlueprintSession session) {
		final Constructor<?> constructor = findFirstPublicConstructor(clazz);
		if (constructor == null) {
			final BlueprintException b = new NoPublicConstructorException(clazz.getSimpleName());
			final String action = MessageFormat.format("Finding public constructor in {0}", clazz.getName());
			session.setLastAction(action);
			b.setSession(session);
			throw b;
		}

		final Class<?>[] parameterTypes = constructor.getParameterTypes();
		final Object[] parameters = new Object[parameterTypes.length];
		for (int i = 0; i < parameterTypes.length; i++) {
			parameters[i] = construct(parameterTypes[i], config, session);
		}

		@SuppressWarnings("unchecked")
		final T obj = (T) safeNewInstance(session, constructor, parameters);
		blueprintAllAttributes(obj, clazz, config, session);

		return obj;
	}

	/**
	 * Check if a method is setter according to the java
	 *
	 * @param m
	 *            a method
	 * @return true if this is a setter method
	 */
	protected static boolean isRelevant(final Method m) {
		final boolean isNotStatic = !ModifierBits.isModifierBitSet(m.getModifiers(), Modifier.STATIC);
		final boolean isPublic = ModifierBits.isModifierBitSet(m.getModifiers(), Modifier.PUBLIC);
		return isNotStatic && isPublic;
	}

	/**
	 * Create a proxy for an interface, which does nothing.
	 *
	 * @param <T>
	 *            Class of the interface
	 * @param iface
	 *            an interace
	 * @param config
	 *            {@code BlueprintConfiguration}
	 * @param session
	 *            {@code BlueprintSession}
	 * @return a new dynamic proxy
	 */
	@SuppressWarnings("unchecked")
	private static <T> T proxy(final Class<T> iface, final BlueprintConfiguration config, final BlueprintSession session) {
		ProxyInvocationHandler invocationHandler = config.findInvocationHandlerForClass(iface);
		if (invocationHandler == null) {
			invocationHandler = new RefreshingBlueprintInvocationHandler();
		}

		final InvocationHandler handler = new BlueprintInvocationHandler(config, session, invocationHandler);
		return (T) Proxy.newProxyInstance(iface.getClassLoader(), new Class[] { iface }, handler);
	}

	/**
	 * Return a new configuration for random blueprinting.
	 *
	 * @return a new {@code RandomBlueprintConfiguration}
	 */
	public static BlueprintConfiguration random() {
		return new RandomBlueprintConfiguration();
	}

	/**
	 * Create a new instance of a class without having to care about the checked exceptions. The class must have an
	 * accessible default constructor.
	 *
	 * @param <T>
	 *            type parameter of the class to create
	 * @param clazz
	 *            class-object
	 * @return a new instance of the class
	 *
	 * @throws BlueprintException
	 *             in case of any error
	 */
	private static <T> T safeNewInstance(final BlueprintSession session, final Class<T> clazz) {
		final String action = MessageFormat.format("Creating clazz {0} with default constructor.", clazz.getName());
		return SafeInvoke.invoke(new BlueprintExceptionRunnable<T>(session, action) {

			@Override
			public T runInternal() throws Exception {
				return (T) clazz.newInstance();
			}
		}, BlueprintException.class);
	}

	/**
	 * Create a new instance of a class without having to care about the checked exceptions using a given constructor.
	 *
	 * @param constructor
	 *            constructor to call
	 * @param parameters
	 *            constructor arguments
	 * @throws BlueprintException
	 *             in case of any error
	 */
	@SuppressWarnings("unchecked")
	private static <T> T safeNewInstance(final BlueprintSession session, final Constructor<?> constructor, final Object[] parameters) {
		final String action = MessageFormat.format("Creating clazz {0} with constructor {1}.", constructor.getClass().getName(),
				constructor.toGenericString());
		return SafeInvoke.invoke(new BlueprintExceptionRunnable<T>(session, action) {

			@Override
			public T runInternal() throws Exception {
				return (T) constructor.newInstance(parameters);
			}
		}, BlueprintException.class);
	}

	/**
	 * Attention: This class is not intended to create objects from it.
	 */
	private Blueprint() {
		// This class is not intended to create objects from it.
	}
}


text:
package com.amazonaws.services.elasticbeanstalk;

import javax.annotation.Generated;

import com.amazonaws.services.elasticbeanstalk.model.*;
import com.amazonaws.*;

/**
 * Abstract implementation of {@code AWSElasticBeanstalk}. Convenient method forms pass through to the corresponding
 * overload that takes a request object, which throws an {@code UnsupportedOperationException}.
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AbstractAWSElasticBeanstalk implements AWSElasticBeanstalk {

    protected AbstractAWSElasticBeanstalk() {
    }

    @Override
    public void setEndpoint(String endpoint) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public void setRegion(com.amazonaws.regions.Region region) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public AbortEnvironmentUpdateResult abortEnvironmentUpdate(AbortEnvironmentUpdateRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public AbortEnvironmentUpdateResult abortEnvironmentUpdate() {
        return abortEnvironmentUpdate(new AbortEnvironmentUpdateRequest());
    }

    @Override
    public ApplyEnvironmentManagedActionResult applyEnvironmentManagedAction(ApplyEnvironmentManagedActionRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public CheckDNSAvailabilityResult checkDNSAvailability(CheckDNSAvailabilityRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ComposeEnvironmentsResult composeEnvironments(ComposeEnvironmentsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public CreateApplicationResult createApplication(CreateApplicationRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public CreateApplicationVersionResult createApplicationVersion(CreateApplicationVersionRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public CreateConfigurationTemplateResult createConfigurationTemplate(CreateConfigurationTemplateRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public CreateEnvironmentResult createEnvironment(CreateEnvironmentRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public CreatePlatformVersionResult createPlatformVersion(CreatePlatformVersionRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public CreateStorageLocationResult createStorageLocation(CreateStorageLocationRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public CreateStorageLocationResult createStorageLocation() {
        return createStorageLocation(new CreateStorageLocationRequest());
    }

    @Override
    public DeleteApplicationResult deleteApplication(DeleteApplicationRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeleteApplicationVersionResult deleteApplicationVersion(DeleteApplicationVersionRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeleteConfigurationTemplateResult deleteConfigurationTemplate(DeleteConfigurationTemplateRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeleteEnvironmentConfigurationResult deleteEnvironmentConfiguration(DeleteEnvironmentConfigurationRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DeletePlatformVersionResult deletePlatformVersion(DeletePlatformVersionRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeAccountAttributesResult describeAccountAttributes(DescribeAccountAttributesRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeApplicationVersionsResult describeApplicationVersions(DescribeApplicationVersionsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeApplicationVersionsResult describeApplicationVersions() {
        return describeApplicationVersions(new DescribeApplicationVersionsRequest());
    }

    @Override
    public DescribeApplicationsResult describeApplications(DescribeApplicationsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeApplicationsResult describeApplications() {
        return describeApplications(new DescribeApplicationsRequest());
    }

    @Override
    public DescribeConfigurationOptionsResult describeConfigurationOptions(DescribeConfigurationOptionsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeConfigurationSettingsResult describeConfigurationSettings(DescribeConfigurationSettingsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeEnvironmentHealthResult describeEnvironmentHealth(DescribeEnvironmentHealthRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeEnvironmentManagedActionHistoryResult describeEnvironmentManagedActionHistory(DescribeEnvironmentManagedActionHistoryRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeEnvironmentManagedActionsResult describeEnvironmentManagedActions(DescribeEnvironmentManagedActionsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeEnvironmentResourcesResult describeEnvironmentResources(DescribeEnvironmentResourcesRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeEnvironmentsResult describeEnvironments(DescribeEnvironmentsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeEnvironmentsResult describeEnvironments() {
        return describeEnvironments(new DescribeEnvironmentsRequest());
    }

    @Override
    public DescribeEventsResult describeEvents(DescribeEventsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribeEventsResult describeEvents() {
        return describeEvents(new DescribeEventsRequest());
    }

    @Override
    public DescribeInstancesHealthResult describeInstancesHealth(DescribeInstancesHealthRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public DescribePlatformVersionResult describePlatformVersion(DescribePlatformVersionRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ListAvailableSolutionStacksResult listAvailableSolutionStacks(ListAvailableSolutionStacksRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ListAvailableSolutionStacksResult listAvailableSolutionStacks() {
        return listAvailableSolutionStacks(new ListAvailableSolutionStacksRequest());
    }

    @Override
    public ListPlatformVersionsResult listPlatformVersions(ListPlatformVersionsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ListTagsForResourceResult listTagsForResource(ListTagsForResourceRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public RebuildEnvironmentResult rebuildEnvironment(RebuildEnvironmentRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public RequestEnvironmentInfoResult requestEnvironmentInfo(RequestEnvironmentInfoRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public RestartAppServerResult restartAppServer(RestartAppServerRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public RetrieveEnvironmentInfoResult retrieveEnvironmentInfo(RetrieveEnvironmentInfoRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public SwapEnvironmentCNAMEsResult swapEnvironmentCNAMEs(SwapEnvironmentCNAMEsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public SwapEnvironmentCNAMEsResult swapEnvironmentCNAMEs() {
        return swapEnvironmentCNAMEs(new SwapEnvironmentCNAMEsRequest());
    }

    @Override
    public TerminateEnvironmentResult terminateEnvironment(TerminateEnvironmentRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public UpdateApplicationResult updateApplication(UpdateApplicationRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public UpdateApplicationResourceLifecycleResult updateApplicationResourceLifecycle(UpdateApplicationResourceLifecycleRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public UpdateApplicationVersionResult updateApplicationVersion(UpdateApplicationVersionRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public UpdateConfigurationTemplateResult updateConfigurationTemplate(UpdateConfigurationTemplateRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public UpdateEnvironmentResult updateEnvironment(UpdateEnvironmentRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public UpdateTagsForResourceResult updateTagsForResource(UpdateTagsForResourceRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public ValidateConfigurationSettingsResult validateConfigurationSettings(ValidateConfigurationSettingsRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public void shutdown() {
        throw new java.lang.UnsupportedOperationException();
    }

    @Override
    public com.amazonaws.ResponseMetadata getCachedResponseMetadata(com.amazonaws.AmazonWebServiceRequest request) {
        throw new java.lang.UnsupportedOperationException();
    }

}

redpajama_set_name: RedPajamaGithub


text:
layout: kanji-remain
v4: 2047
kanji: 髭
keyword: beard
strokes: 17
on-yomi: シ
permalink: /rtk/髭/
---

## Koohii stories:

1) [astridtops] 14-8-2006(62): "Please stop and sit down to look to the painting up there", the tour guide says. "We don't know exactly who is on the painting, but from the shape of the hair and the distinctive beard, we think they meant to depict President Lincoln.".

2) [Yozora] 21-9-2009(23): A beard is hair that, instead of wanting it SHAPED like your friends, you grow it LONG so that you can STOP, SIT DOWN and scratch it thoughtful while considering this here and that there.

3) [Raichu] 7-7-2008(12): If you remember hair on the head is 髪 . But when my mother sees the state of my beard, she says, "What is this!?".

4) [Shingo] 7-9-2010(5): The hair that you shape (with your hand) when you stop and sit down is your beard.

5) [NeoGlitch] 19-1-2012(4): I was eating my soup when I saw a hairy shape in it. I stopped my spoon immediately, and yelled outraged "What's this here?!! Then the cook arrived and said: "Oh, that's my detachable beard... sorry, my bad :(" (+jabberwockychortles).


text:
#include "qnetworkaccessftpbackend_p.h"
#include "qnetworkaccessmanager_p.h"
#include "QtNetwork/qauthenticator.h"
#include "private/qnoncontiguousbytedevice_p.h"

#ifndef QT_NO_FTP

QT_BEGIN_NAMESPACE

enum {
    DefaultFtpPort = 21
};

static QByteArray makeCacheKey(const QUrl &url)
{
    QUrl copy = url;
    copy.setPort(url.port(DefaultFtpPort));
    return "ftp-connection:" +
        copy.toEncoded(QUrl::RemovePassword | QUrl::RemovePath | QUrl::RemoveQuery |
                       QUrl::RemoveFragment);
}

QNetworkAccessBackend *
QNetworkAccessFtpBackendFactory::create(QNetworkAccessManager::Operation op,
                                        const QNetworkRequest &request) const
{
    // is it an operation we know of?
    switch (op) {
    case QNetworkAccessManager::GetOperation:
    case QNetworkAccessManager::PutOperation:
        break;

    default:
        // no, we can't handle this operation
        return 0;
    }

    QUrl url = request.url();
    if (url.scheme().compare(QLatin1String("ftp"), Qt::CaseInsensitive) == 0)
        return new QNetworkAccessFtpBackend;
    return 0;
}

class QNetworkAccessCachedFtpConnection: public QFtp, public QNetworkAccessCache::CacheableObject
{
    // Q_OBJECT
public:
    QNetworkAccessCachedFtpConnection()
    {
        setExpires(true);
        setShareable(false);
    }

    void dispose()
    {
        connect(this, SIGNAL(done(bool)), this, SLOT(deleteLater()));
        close();
    }
};

QNetworkAccessFtpBackend::QNetworkAccessFtpBackend()
    : ftp(0), uploadDevice(0), totalBytes(0), helpId(-1), sizeId(-1), mdtmId(-1),
    supportsSize(false), supportsMdtm(false), state(Idle)
{
}

QNetworkAccessFtpBackend::~QNetworkAccessFtpBackend()
{
    //if backend destroyed while in use, then abort (this is the code path from QNetworkReply::abort)
    if (ftp && state != Disconnecting)
        ftp->abort();
    disconnectFromFtp();
}

void QNetworkAccessFtpBackend::open()
{
#ifndef QT_NO_NETWORKPROXY
    QNetworkProxy proxy;
    foreach (const QNetworkProxy &p, proxyList()) {
        // use the first FTP proxy
        // or no proxy at all
        if (p.type() == QNetworkProxy::FtpCachingProxy
            || p.type() == QNetworkProxy::NoProxy) {
            proxy = p;
            break;
        }
    }

    // did we find an FTP proxy or a NoProxy?
    if (proxy.type() == QNetworkProxy::DefaultProxy) {
        // unsuitable proxies
        error(QNetworkReply::ProxyNotFoundError,
              tr("No suitable proxy found"));
        finished();
        return;
    }

#endif

    QUrl url = this->url();
    if (url.path().isEmpty()) {
        url.setPath(QLatin1String("/"));
        setUrl(url);
    }
    if (url.path().endsWith(QLatin1Char('/'))) {
        error(QNetworkReply::ContentOperationNotPermittedError,
              tr("Cannot open %1: is a directory").arg(url.toString()));
        finished();
        return;
    }
    state = LoggingIn;

    QNetworkAccessCache* objectCache = QNetworkAccessManagerPrivate::getObjectCache(this);
    QByteArray cacheKey = makeCacheKey(url);
    if (!objectCache->requestEntry(cacheKey, this,
                             SLOT(ftpConnectionReady(QNetworkAccessCache::CacheableObject*)))) {
        ftp = new QNetworkAccessCachedFtpConnection;
#ifndef QT_NO_BEARERMANAGEMENT
        //copy network session down to the QFtp
        ftp->setProperty("_q_networksession", property("_q_networksession"));
#endif
#ifndef QT_NO_NETWORKPROXY
        if (proxy.type() == QNetworkProxy::FtpCachingProxy)
            ftp->setProxy(proxy.hostName(), proxy.port());
#endif
        ftp->connectToHost(url.host(), url.port(DefaultFtpPort));
        ftp->login(url.userName(), url.password());

        objectCache->addEntry(cacheKey, ftp);
        ftpConnectionReady(ftp);
    }

    // Put operation
    if (operation() == QNetworkAccessManager::PutOperation) {
        uploadDevice = QNonContiguousByteDeviceFactory::wrap(createUploadByteDevice());
        uploadDevice->setParent(this);
    }
}

void QNetworkAccessFtpBackend::closeDownstreamChannel()
{
    state = Disconnecting;
    if (operation() == QNetworkAccessManager::GetOperation)
        ftp->abort();
}

void QNetworkAccessFtpBackend::downstreamReadyWrite()
{
    if (state == Transferring && ftp && ftp->bytesAvailable())
        ftpReadyRead();
}

void QNetworkAccessFtpBackend::ftpConnectionReady(QNetworkAccessCache::CacheableObject *o)
{
    ftp = static_cast<QNetworkAccessCachedFtpConnection *>(o);
    connect(ftp, SIGNAL(done(bool)), SLOT(ftpDone()));
    connect(ftp, SIGNAL(rawCommandReply(int,QString)), SLOT(ftpRawCommandReply(int,QString)));
    connect(ftp, SIGNAL(readyRead()), SLOT(ftpReadyRead()));

    // is the login process done already?
    if (ftp->state() == QFtp::LoggedIn)
        ftpDone();

    // no, defer the actual operation until after we've logged in
}

void QNetworkAccessFtpBackend::disconnectFromFtp()
{
    state = Disconnecting;

    if (ftp) {
        disconnect(ftp, 0, this, 0);

        QByteArray key = makeCacheKey(url());
        QNetworkAccessManagerPrivate::getObjectCache(this)->releaseEntry(key);

        ftp = 0;
    }
}

void QNetworkAccessFtpBackend::ftpDone()
{
    // the last command we sent is done
    if (state == LoggingIn && ftp->state() != QFtp::LoggedIn) {
        if (ftp->state() == QFtp::Connected) {
            // the login did not succeed
            QUrl newUrl = url();
            newUrl.setUserInfo(QString());
            setUrl(newUrl);

            QAuthenticator auth;
            authenticationRequired(&auth);

            if (!auth.isNull()) {
                // try again:
                newUrl.setUserName(auth.user());
                ftp->login(auth.user(), auth.password());
                return;
            }

            error(QNetworkReply::AuthenticationRequiredError,
                  tr("Logging in to %1 failed: authentication required")
                  .arg(url().host()));
        } else {
            // we did not connect
            QNetworkReply::NetworkError code;
            switch (ftp->error()) {
            case QFtp::HostNotFound:
                code = QNetworkReply::HostNotFoundError;
                break;

            case QFtp::ConnectionRefused:
                code = QNetworkReply::ConnectionRefusedError;
                break;

            default:
                code = QNetworkReply::ProtocolFailure;
                break;
            }

            error(code, ftp->errorString());
        }

        // we're not connected, so remove the cache entry:
        QByteArray key = makeCacheKey(url());
        QNetworkAccessManagerPrivate::getObjectCache(this)->removeEntry(key);

        disconnect(ftp, 0, this, 0);
        ftp->dispose();
        ftp = 0;

        state = Disconnecting;
        finished();
        return;
    }

    // check for errors:
    if (ftp->error() != QFtp::NoError) {
        QString msg;
        if (operation() == QNetworkAccessManager::GetOperation)
            msg = tr("Error while downloading %1: %2");
        else
            msg = tr("Error while uploading %1: %2");
        msg = msg.arg(url().toString(), ftp->errorString());

        if (state == Statting)
            // file probably doesn't exist
            error(QNetworkReply::ContentNotFoundError,  msg);
        else
            error(QNetworkReply::ContentAccessDenied, msg);

        disconnectFromFtp();
        finished();
    }

    if (state == LoggingIn) {
        state = CheckingFeatures;
        if (operation() == QNetworkAccessManager::GetOperation) {
            // send help command to find out if server supports "SIZE" and "MDTM"
            QString command = url().path();
            command.prepend(QLatin1String("%1 "));
            helpId = ftp->rawCommand(QLatin1String("HELP")); // get supported commands
        } else {
            ftpDone();
        }
    } else if (state == CheckingFeatures) {
        state = Statting;
        if (operation() == QNetworkAccessManager::GetOperation) {
            // logged in successfully, send the stat requests (if supported)
            QString command = url().path();
            command.prepend(QLatin1String("%1 "));
            if (supportsSize) {
                ftp->rawCommand(QLatin1String("TYPE I"));
                sizeId = ftp->rawCommand(command.arg(QLatin1String("SIZE"))); // get size
            }
            if (supportsMdtm)
                mdtmId = ftp->rawCommand(command.arg(QLatin1String("MDTM"))); // get modified time
            if (!supportsSize && !supportsMdtm)
                ftpDone();      // no commands sent, move to the next state
        } else {
            ftpDone();
        }
    } else if (state == Statting) {
        // statted successfully, send the actual request
        emit metaDataChanged();
        state = Transferring;

        QFtp::TransferType type = QFtp::Binary;
        if (operation() == QNetworkAccessManager::GetOperation) {
            setCachingEnabled(true);
            ftp->get(url().path(), 0, type);
        } else {
            ftp->put(uploadDevice, url().path(), type);
        }

    } else if (state == Transferring) {
        // upload or download finished
        disconnectFromFtp();
        finished();
    }
}

void QNetworkAccessFtpBackend::ftpReadyRead()
{
    QByteArray data = ftp->readAll();
    QByteDataBuffer list;
    list.append(data);
    data.clear(); // important because of implicit sharing!
    writeDownstreamData(list);
}

void QNetworkAccessFtpBackend::ftpRawCommandReply(int code, const QString &text)
{
    //qDebug() << "FTP reply:" << code << text;
    int id = ftp->currentId();

    if ((id == helpId) && ((code == 200) || (code == 214))) {     // supported commands
        // the "FEAT" ftp command would be nice here, but it is not part of the
        // initial FTP RFC 959, neither ar "SIZE" nor "MDTM" (they are all specified
        // in RFC 3659)
        if (text.contains(QLatin1String("SIZE"), Qt::CaseSensitive))
            supportsSize = true;
        if (text.contains(QLatin1String("MDTM"), Qt::CaseSensitive))
            supportsMdtm = true;
    } else if (code == 213) {          // file status
        if (id == sizeId) {
            // reply to the size command
            setHeader(QNetworkRequest::ContentLengthHeader, text.toLongLong());
#ifndef QT_NO_DATESTRING
        } else if (id == mdtmId) {
            QDateTime dt = QDateTime::fromString(text, QLatin1String("yyyyMMddHHmmss"));
            setHeader(QNetworkRequest::LastModifiedHeader, dt);
#endif
        }
    }
}

QT_END_NAMESPACE

#endif // QT_NO_FTP


text:
/*
 * $Id$
 * $URL$
 */

package org.subethamail.web.action;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.java.Log;

import org.subethamail.web.Backend;
import org.subethamail.web.action.auth.AuthAction;

/**
 * Deletes a role.
 *
 * @author Jeff Schnitzer
 */
@Log
public class RoleDelete extends AuthAction
{
	/** The role to delete */
	@Getter @Setter Long deleteRoleId;

	/** Convert all members who had that role to this role */
	@Getter @Setter Long convertToRoleId;

	/** This is filled in afterwards so we know where to redirect to */
	@Getter @Setter Long listId;

	/** */
	public void execute() throws Exception
	{
		this.listId = Backend.instance().getListMgr().deleteRole(this.deleteRoleId, this.convertToRoleId);
	}
}


text:
<manifest package="hearsilent.quickyee"
          xmlns:android="http://schemas.android.com/apk/res/android">

	<application
		android:allowBackup="true"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:supportsRtl="true"
		android:theme="@style/AppTheme">

		<service
			android:name=".QuickSettingTileService"
			android:icon="@drawable/ic_yeeeeeeee"
			android:label="@string/app_name"
			android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
			<intent-filter>
				<action android:name="android.service.quicksettings.action.QS_TILE"/>
			</intent-filter>
		</service>
	</application>

</manifest>


text:
require 'pattern_deployer/pattern/connection'
require 'pattern_deployer/pattern/config'
require 'pattern_deployer/pattern/database_config'
require 'pattern_deployer/pattern/pattern'
require 'pattern_deployer/pattern/reference'
require 'pattern_deployer/pattern/web_server_config'


text:
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Data;
using QuantConnect.Interfaces;

namespace QuantConnect.Algorithm.CSharp
{
    /// <summary>
    /// Regression test algorithm simply fetch and compare data of minute resolution around daylight saving period
    /// reproduces issue reported in GB issue GH issue https://github.com/QuantConnect/Lean/issues/4925
    /// related issues https://github.com/QuantConnect/Lean/issues/3707; https://github.com/QuantConnect/Lean/issues/4630
    /// </summary>
    public class FillForwardEnumeratorOutOfOrderBarRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
    {
        private decimal _exptectedClose = 84.09m;
        private DateTime _exptectedTime = new DateTime(2008, 3, 10, 9, 30, 0);
        private Symbol _shy;

        /// <summary>
        /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
        /// </summary>
        public override void Initialize()
        {
            SetStartDate(2008, 3, 7);
            SetEndDate(2008, 3, 10);
            _shy = AddEquity("SHY", Resolution.Minute).Symbol;
            // just to make debugging easier, less subscriptions
            SetBenchmark(time => 1);
        }

        public override void OnData(Slice slice)
        {
            var trackingBar = slice.Bars.Values.FirstOrDefault(s => s.Time.Equals(_exptectedTime));

            if (trackingBar != null)
            {
                if (!Portfolio.Invested)
                {
                    SetHoldings(_shy, 1);
                }

                if (trackingBar.Close != _exptectedClose)
                {
                    throw new Exception(
                        $"Bar at {_exptectedTime.ToStringInvariant()} closed at price {trackingBar.Close.ToStringInvariant()}; expected {_exptectedClose.ToStringInvariant()}");
                }
            }
        }

        /// <summary>
        /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
        /// </summary>
        public bool CanRunLocally { get; } = true;

        /// <summary>
        /// This is used by the regression test system to indicate which languages this algorithm is written in.
        /// </summary>
        public Language[] Languages { get; } = { Language.CSharp };

        /// <summary>
        /// Data Points count of all timeslices of algorithm
        /// </summary>
        public long DataPoints => 1561;

        /// <summary>
        /// Data Points count of the algorithm history
        /// </summary>
        public int AlgorithmHistoryDataPoints => 0;

        /// <summary>
        /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
        /// </summary>
        public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
        {
            {"Total Trades", "1"},
            {"Average Win", "0%"},
            {"Average Loss", "0%"},
            {"Compounding Annual Return", "16.086%"},
            {"Drawdown", "0.100%"},
            {"Expectancy", "0"},
            {"Net Profit", "0.148%"},
            {"Sharpe Ratio", "9.758"},
            {"Probabilistic Sharpe Ratio", "0%"},
            {"Loss Rate", "0%"},
            {"Win Rate", "0%"},
            {"Profit-Loss Ratio", "0"},
            {"Alpha", "0"},
            {"Beta", "0"},
            {"Annual Standard Deviation", "0.014"},
            {"Annual Variance", "0"},
            {"Information Ratio", "9.758"},
            {"Tracking Error", "0.014"},
            {"Treynor Ratio", "0"},
            {"Total Fees", "$5.93"},
            {"Estimated Strategy Capacity", "$150000.00"},
            {"Lowest Capacity Asset", "SHY 2T"},
            {"Fitness Score", "0.499"},
            {"Kelly Criterion Estimate", "0"},
            {"Kelly Criterion Probability Value", "0"},
            {"Sortino Ratio", "79228162514264337593543950335"},
            {"Return Over Maximum Drawdown", "-105.726"},
            {"Portfolio Turnover", "0.998"},
            {"Total Insights Generated", "0"},
            {"Total Insights Closed", "0"},
            {"Total Insights Analysis Completed", "0"},
            {"Long Insight Count", "0"},
            {"Short Insight Count", "0"},
            {"Long/Short Ratio", "100%"},
            {"Estimated Monthly Alpha Value", "$0"},
            {"Total Accumulated Estimated Alpha Value", "$0"},
            {"Mean Population Estimated Insight Value", "$0"},
            {"Mean Population Direction", "0%"},
            {"Mean Population Magnitude", "0%"},
            {"Rolling Averaged Population Direction", "0%"},
            {"Rolling Averaged Population Magnitude", "0%"},
            {"OrderListHash", "5315f54b62b2eaf9d587602137d641a5"}
        };
    }
}


text:
from django import template
from django.utils.encoding import force_unicode

import ttag
from ttag.core import BaseTag, DeclarativeArgsMetaclass
from ttag.tests.setup import models

register = template.Library()

class SelfRegisteringMetaclass(DeclarativeArgsMetaclass):

    def __new__(cls, name, bases, attrs):
        cls = DeclarativeArgsMetaclass.__new__(cls, name, bases, attrs)
        parents = [b for b in bases if isinstance(b, DeclarativeArgsMetaclass)]
        if parents:
            register.tag(cls._meta.name, cls)
        return cls

class TestTag(BaseTag):
    __metaclass__ = SelfRegisteringMetaclass

class NamedArg(TestTag):
    limit = ttag.IntegerArg(default=5, named=True)

    def output(self, data):
        if 'limit' in data:
            return 'The limit is %d' % data['limit']
        return 'No limit was specified'

class NamedKeywordArg(NamedArg):
    limit = ttag.IntegerArg(keyword=True)

class NoArgument(TestTag):

    def output(self, data):
        return 'No arguments here'

class Positional(TestTag):
    limit = ttag.IntegerArg()

    def output(self, data):
        return '%s' % data['limit']

class PositionalMixed(TestTag):
    limit = ttag.IntegerArg(default=5)
    as_ = ttag.BasicArg(named=True)

    def render(self, context):
        data = self.resolve(context)
        context[data['as']] = data['limit']
        return ''

class PositionalMixedkw(TestTag):
    value = ttag.Arg(required=False, null=True)
    default = ttag.Arg(keyword=True)

    def output(self, data):
        return unicode(data.get('value') or data['default'])

class PositionalOptional(TestTag):
    start = ttag.IntegerArg()
    finish = ttag.IntegerArg(required=False)

    def output(self, data):
        if 'finish' in data:
            start, finish = data['start'], data['finish']
        else:
            start, finish = 0, data['start']
        return ','.join([str(i) for i in range(start, finish)])

class PositionalOptionalMixed(TestTag):
    start = ttag.IntegerArg()
    finish = ttag.IntegerArg(required=False)
    step = ttag.IntegerArg(named=True)

    def output(self, data):
        if 'finish' in data:
            start, finish = data['start'], data['finish']
        else:
            start, finish = 0, data['start']
        return ','.join([str(i) for i in range(start, finish, data['step'])])

class ArgumentType(TestTag):
    age = ttag.IntegerArg(required=False, named=True)
    name_ = ttag.StringArg(required=False, named=True)
    url = ttag.ModelInstanceArg(model=models.Link, required=False, named=True)
    date = ttag.DateArg(required=False, named=True)
    time = ttag.TimeArg(required=False, named=True)
    datetime = ttag.DateTimeArg(required=False, named=True)
    flag = ttag.BooleanArg()

    def output(self, data):
        order = 'name age url date time datetime'.split()
        values = [unicode(data[x]) for x in order if x in data]
        if 'flag' in data:
            values.append('flag_is_set')
        return u' '.join(values)

class Constant(TestTag):
    start = ttag.Arg()
    to = ttag.ConstantArg()
    finish = ttag.Arg()

    def output(self, data):
        return '%s - %s' % (data['start'], data['finish'])

class KeywordsEcho(TestTag):
    keywords = ttag.KeywordsArg()

    def output(self, data):
        keywords = data['keywords'].items()
        return ', '.join('%s: %s' % (key, value) for key, value in keywords)

class DotCombine(TestTag):
    args = ttag.MultiArg()

    def output(self, data):
        args = [force_unicode(arg) for arg in data['args']]
        return '.'.join(args)

class DotCombineDefault(DotCombine):
    default = ttag.Arg(named=True)

    def output(self, data):
        args = [arg and force_unicode(arg) or data['default']
                for arg in data['args']]
        return '.'.join(args)

class Repeat(TestTag):
    count = ttag.IntegerArg()

    class Meta:
        block = True
        end_block = 'done'

    def render(self, context):
        data = self.resolve(context)
        output = []
        for i in range(data['count']):
            context.push()
            output.append(self.nodelist.render(context))
            context.pop()
        return ''.join(output)

class RepeatWithEmpty(TestTag):
    count = ttag.IntegerArg()

    class Meta:
        block = {'empty': False}
        end_block = 'stop'

    def render(self, context):
        data = self.resolve(context)
        if not data['count']:
            return self.nodelist_empty.render(context)
        output = []
        for i in range(data['count']):
            context.push()
            output.append(self.nodelist.render(context))
            context.pop()
        return ''.join(output)

class BaseInclude(TestTag):
    """
    A tag for testing KeywordsArg.
    """

    def output(self, data):
        out = 'including %s' % data['template']
        if data.get('with'):
            with_bits = data['with'].items()
            with_bits.sort(key=lambda bit: bit[0])
            out += ' with %s' % ' and '.join(['%s = %s' % (k, v)
                                              for k, v in with_bits])
        return out

class IncludeCompact(BaseInclude):
    template = ttag.Arg()
    with_ = ttag.KeywordsArg(named=True, required=False)

class IncludeVerbose(BaseInclude):
    template = ttag.Arg()
    with_ = ttag.KeywordsArg(named=True, required=False, compact=False,
                             verbose=True)

class IncludeMixed(BaseInclude):
    template = ttag.Arg()
    with_ = ttag.KeywordsArg(named=True, required=False, verbose=True)


text:
package stubrn.stubs;

/**
 *
 */
public class ExperimentalTest {

}


text:
package id.zelory.codepolitan.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import id.zelory.benih.view.BenihImageView;

/**
 * Created on : August 30, 2015
 * Author     : zetbaitsu
 * Name       : Zetra
 * Email      : zetra@mail.ugm.ac.id
 * GitHub     : https://github.com/zetbaitsu
 * LinkedIn   : https://id.linkedin.com/in/zetbaitsu
 */
public class CodePolitanImageView extends BenihImageView
{
    public CodePolitanImageView(Context context)
    {
        super(context);
    }

    public CodePolitanImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public CodePolitanImageView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    public void setImageUrl(String url, ImageView errorImageView)
    {
        Glide.with(getContext())
                .load(url)
                .listener(new RequestListener<String, GlideDrawable>()
                {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource)
                    {
                        errorImageView.setVisibility(VISIBLE);
                        setVisibility(INVISIBLE);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource)
                    {
                        setVisibility(VISIBLE);
                        errorImageView.setVisibility(GONE);
                        return false;
                    }
                })
                .into(this);
    }
}


text:
<?php

namespace insolita\wgadminlte;

use yii\bootstrap\Widget;
use yii\helpers\Html;

/**
 *  Flash messages with AdminLte style and support multiple flash similar style
 *
 * @example
 *    add in layout
 *    <?=\insolita\wgadminlte\FlashAlerts::widget([]);?>
 *
 *   In controllers
 *    Yii::$app->session->setFlash('warning','Message1',true);
 *    Yii::$app->session->setFlash('warning-order','Message2');
 *    Yii::$app->session->setFlash('info1','Message3',true);
 *    Yii::$app->session->setFlash('info2','Message4',true);
 */
class FlashAlerts extends Widget
{
	const TYPE_DANGER = 'danger';
	const TYPE_INFO = 'info';
	const TYPE_SUCCESS = 'success';
	const TYPE_WARNING = 'warning';
	/**@var boolean - Show close button for alert* */
	public $closable = true;
	/**@var boolean - Encode flash messages?* */
	public $encode = true;
	/**@var boolean - Wrap message in  tag?* */
	public $bold = true;
	public $successIcon = '';
	public $errorIcon = '';
	public $warningIcon = '';
	public $infoIcon = '';
	public $successTitle = 'Успешно!';
	public $errorTitle = 'Ошибка!';
	public $warningTitle = 'Внимание!';
	public $infoTitle = 'К сведению!';
	private $_classes;
	private $_keyparts;
	private $_icons;
	private $_titles;

	public function init()
	{
		$this->_classes = ['success' => 'success', 'error' => 'danger', 'info' => 'info', 'warning' => 'warning'];
		$this->_keyparts = array_keys($this->_classes);
		$this->_icons = [
			'success' => $this->successIcon,
			'error'   => $this->errorIcon,
			'info'    => $this->infoIcon,
			'warning' => $this->warningIcon,
		];
		$this->_titles = [
			'success' => $this->successTitle,
			'error'   => $this->errorTitle,
			'info'    => $this->infoTitle,
			'warning' => $this->warningTitle,
		];
	}

	public function run()
	{
		$allflash = \Yii::$app->session->getAllFlashes();
		$msg = '';
		foreach ($allflash as $key => $mess)
		{
			$fk = 'info';
			foreach ($this->_keyparts as $kp)
			{
				if (strpos($key, $kp) !== false)
				{
					$fk = $kp;
					break;
				}
			}

			Html::addCssClass($this->options, 'alert');
			Html::addCssClass($this->options, 'alert-' . $this->_classes[$fk]);
			if ($this->closable)
			{
				Html::addCssClass($this->options, 'alert-dismissable');
			}
			if (is_array($mess))
			{
				foreach ($mess as $submess)
				{
					$msg .= $this->buildMessage($fk,$submess);
				}
			}
			elseif($mess)
			{
				$msg .= $this->buildMessage($fk,$mess);
			}
		}
		return $msg;
	}

	protected function buildMessage($fk, $text)
	{
		$text = !$this->encode ? $text : Html::encode($text);
		return Html::tag(
			'div',
			$this->_icons[$fk]
			. (!$this->closable ? ''
				: '<button class="close" aria-hidden="true" data-dismiss="alert" type="button">×</button>')
			. ($this->_titles[$fk] ? Html::tag('b', $this->_titles[$fk]) : '') . ' '
			. (!$this->bold ? $text : Html::tag('b', $text))
			, $this->options
		);
	}

}


text:
<?php

namespace Symfony\Tests\Component\DependencyInjection\ParameterBag;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

class ParameterBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::__construct
     */
    public function testConstructor()
    {
        $bag = new ParameterBag($parameters = array(
            'foo' => 'foo',
            'bar' => 'bar',
        ));
        $this->assertEquals($parameters, $bag->all(), '__construct() takes an array of parameters as its first argument');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::clear
     */
    public function testClear()
    {
        $bag = new ParameterBag($parameters = array(
            'foo' => 'foo',
            'bar' => 'bar',
        ));
        $bag->clear();
        $this->assertEquals(array(), $bag->all(), '->clear() removes all parameters');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::get
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::set
     */
    public function testGetSet()
    {
        $bag = new ParameterBag(array('foo' => 'bar'));
        $bag->set('bar', 'foo');
        $this->assertEquals('foo', $bag->get('bar'), '->set() sets the value of a new parameter');

        $bag->set('foo', 'baz');
        $this->assertEquals('baz', $bag->get('foo'), '->set() overrides previously set parameter');

        $bag->set('Foo', 'baz1');
        $this->assertEquals('baz1', $bag->get('foo'), '->set() converts the key to lowercase');
        $this->assertEquals('baz1', $bag->get('FOO'), '->get() converts the key to lowercase');

        try {
            $bag->get('baba');
            $this->fail('->get() throws an \InvalidArgumentException if the key does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->get() throws an \InvalidArgumentException if the key does not exist');
            $this->assertEquals('The parameter "baba" must be defined.', $e->getMessage(), '->get() throws an \InvalidArgumentException if the key does not exist');
        }
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::has
     */
    public function testHas()
    {
        $bag = new ParameterBag(array('foo' => 'bar'));
        $this->assertTrue($bag->has('foo'), '->has() returns true if a parameter is defined');
        $this->assertTrue($bag->has('Foo'), '->has() converts the key to lowercase');
        $this->assertFalse($bag->has('bar'), '->has() returns false if a parameter is not defined');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolveValue
     */
    public function testResolveValue()
    {
        $bag = new ParameterBag(array());
        $this->assertEquals('foo', $bag->resolveValue('foo'), '->resolveValue() returns its argument unmodified if no placeholders are found');

        $bag = new ParameterBag(array('foo' => 'bar'));
        $this->assertEquals('I\'m a bar', $bag->resolveValue('I\'m a %foo%'), '->resolveValue() replaces placeholders by their values');
        $this->assertEquals(array('bar' => 'bar'), $bag->resolveValue(array('%foo%' => '%foo%')), '->resolveValue() replaces placeholders in keys and values of arrays');
        $this->assertEquals(array('bar' => array('bar' => array('bar' => 'bar'))), $bag->resolveValue(array('%foo%' => array('%foo%' => array('%foo%' => '%foo%')))), '->resolveValue() replaces placeholders in nested arrays');
        $this->assertEquals('I\'m a %foo%', $bag->resolveValue('I\'m a %%foo%%'), '->resolveValue() supports % escaping by doubling it');
        $this->assertEquals('I\'m a bar %foo bar', $bag->resolveValue('I\'m a %foo% %%foo %foo%'), '->resolveValue() supports % escaping by doubling it');

        $bag = new ParameterBag(array('foo' => true));
        $this->assertTrue($bag->resolveValue('%foo%') === true, '->resolveValue() replaces arguments that are just a placeholder by their value without casting them to strings');

        $bag = new ParameterBag(array());
        try {
            $bag->resolveValue('%foobar%', array());
            $this->fail('->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter');
            $this->assertEquals('The parameter "foobar" must be defined.', $e->getMessage(), '->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter');
        }

        try {
            $bag->resolveValue('foo %foobar% bar', array());
            $this->fail('->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter');
            $this->assertEquals('The parameter "foobar" must be defined.', $e->getMessage(), '->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter');
        }
    }
}


text:
using System;

namespace Chutzpah.Compilers
{
    public interface IJavaScriptCompiler : IDisposable
    {
        string Compile(string source, params object[] args);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using MvcLocalization.WebApp.Infrastructure;

namespace MvcLocalization.WebApp.Controllers
{
    public class BaseController : Controller
    {
        protected override void ExecuteCore()
        {
            CurrentLanguageStore store = new CurrentLanguageStore();
            LanguageKey key = store.GetPreferredLanguage();
            CultureInfo language = new CultureInfo(key.ToString());

            Thread.CurrentThread.CurrentCulture = language;
            Thread.CurrentThread.CurrentUICulture = language;
            base.ExecuteCore();
        }

    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.

using System.Threading.Tasks;
using System.Collections.Generic;

namespace MyDriving.Interfaces
{
    public interface IGeocoder
    {
        Task<IEnumerable<Position>> GetPositionsForAddressAsync(string address);
        Task<IEnumerable<string>> GetAddressesForPositionAsync(Position position);
    }

    public class Position
    {
        public double Latitude { get; set; }
        public double Longitude { get; set; }
    }
}


text:
import * as types from '../mutation-types';

let state = {
    todos: new Map()
}

// function filterTodos(state, type) {
//     return state.todos ? {
//         done: [...state.todos.values()].filter(todo => ((todo.get('type') === type) && (todo.get('status') === true))).sort((todo1, todo2) => {return todo2.updatedAt - todo1.updatedAt}),
//         undone: [...state.todos.values()].filter(todo => ((todo.get('type') === type) && (todo.get('status') === false))).sort((todo1, todo2) => {return todo2.updatedAt - todo1.updatedAt}),
//     } : {};
// }

// let getters = {
//     ImpEmg: function(state) {
//         return filterTodos(state, 'ImpEmg')
//     },
//     ImpNotEmg: function(state) {
//         return filterTodos(state, 'ImpNotEmg')
//     },
//     NotImpEmg: function(state) {
//         return filterTodos(state, 'NotImpEmg')
//     },
//     NotImpNotEmg: function(state) {
//         return filterTodos(state, 'NotImpNotEmg')
//     },
// }

let actions = {
    initTodos({ commit }, todos) {
        commit(types.INIT_TODO, todos);
    },
    addTodo({ commit }, todo) {
        // commit(types.ADD_TODO, todo);
        commit(types.SET_TODO, todo);
    },
    deleteTodo({ commit, state }, todoID) {
        console.log(state);
        if ((state.todos instanceof Map) && todoID) {
            let todo = state.todos.get(todoID);
            return todo.set('enable',false).save().then((changedTodo)=>{
                commit(types.REMOVE_TODO, changedTodo.id)
                return changedTodo;
            },(err)=>{
                console.log(err);
                return err
            })
        }
    },
    setTodoStatus({ commit }, todoInfo) {
        let todo = state.todos.get(todoInfo.id);
        todo.set('status', todoInfo.status).save().then((changedTodo) => {
            commit(types.SET_TODO, changedTodo);
        },(err)=>{
        	console.log(err);
        })
    },
    setTodo({ commit }, todo){
        return todo.save().then((changedTodo)=>{
            commit(types.SET_TODO, changedTodo);
            return changedTodo
        },(err)=>{
            console.log(err);
            return err
        })
    }
}

let mutations = {
    [types.INIT_TODO](state, todos) {
        let mapTodo = new Map();
        todos.forEach((todo) => {
            mapTodo.set(todo.id, todo)
        })
        state.todos = mapTodo;
    },
    [types.ADD_TODO](state, todo) {
        if ((state.todos instanceof Map) && todo.id) {
            state.todos.set(todo.id, todo)
        }
    },
    [types.REMOVE_TODO](state, todoID) {
        if ((state.todos instanceof Map) && state.todos.has(todoID)) {
            let todos = new Map(state.todos.entries());
            todos.delete(todoID);
            state.todos = todos;
        }
    },
    [types.SET_TODO](state, todo) {
        if ((state.todos instanceof Map) && todo.id) {
            let todos = new Map(state.todos.entries());
            todos.set(todo.id, todo);
            state.todos = todos;
        }
    }
};

export default {
    namespaced: true,
    /* eslint-disable */
    actions,
    // getters,
    mutations,
    state,
}


text:
from fractions import Fraction

def IsCancellingDigitFraction(numerator, denominator):
    #Do they share a digit in both numerator and denominator?
    f = Fraction(numerator, denominator)
    numeratorStr = str(numerator)
    denominatorStr = str(denominator)
    for nd in str(numeratorStr):
        if nd in denominatorStr:
            if denominatorStr.replace(nd,'',1) == '0':
                continue
            reducedFraction = Fraction(int(numeratorStr.replace(nd,'',1)), \
                                       int(denominatorStr.replace(nd,'',1)))
            if reducedFraction == f:
                return True
    return False

product = Fraction(1)
for numerator in range(10,100):
    for denominator in range(numerator+1, 100):
        if (numerator % 10 == 0 and denominator % 10 == 0):
            continue
        if(IsCancellingDigitFraction(numerator, denominator)):
            print ("%d / %d" % (numerator,denominator))
            product *= Fraction(numerator,denominator)

print(product.denominator)


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Web.UI.HtmlControls
{
  public partial class HtmlTableRow : HtmlContainerControl
  {
    #region Methods and constructors
    protected override System.Web.UI.ControlCollection CreateControlCollection()
    {
      return default(System.Web.UI.ControlCollection);
    }

    public HtmlTableRow()
    {
    }

    protected internal override void RenderChildren(System.Web.UI.HtmlTextWriter writer)
    {
    }

    protected override void RenderEndTag(System.Web.UI.HtmlTextWriter writer)
    {
    }
    #endregion

    #region Properties and indexers
    public string Align
    {
      get
      {
        return default(string);
      }
      set
      {
      }
    }

    public string BgColor
    {
      get
      {
        return default(string);
      }
      set
      {
      }
    }

    public string BorderColor
    {
      get
      {
        return default(string);
      }
      set
      {
      }
    }

    public virtual new HtmlTableCellCollection Cells
    {
      get
      {
        return default(HtmlTableCellCollection);
      }
    }

    public string Height
    {
      get
      {
        return default(string);
      }
      set
      {
      }
    }

    public override string InnerHtml
    {
      get
      {
        return default(string);
      }
      set
      {
      }
    }

    public override string InnerText
    {
      get
      {
        return default(string);
      }
      set
      {
      }
    }

    public string VAlign
    {
      get
      {
        return default(string);
      }
      set
      {
      }
    }
    #endregion
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false">
    <file url="file://$PROJECT_DIR$/.idea/copyright" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/src/main/kotlin/net/loxal/example/kotlin/characters/main.kt" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/src/main/resource/index.html" charset="UTF-8" />
    <file url="PROJECT" charset="UTF-8" />
  </component>
</project>


text:
package com.facebook.animated.gif;

import javax.annotation.concurrent.ThreadSafe;

import java.nio.ByteBuffer;

import com.facebook.common.internal.DoNotStrip;
import com.facebook.common.internal.Preconditions;
import com.facebook.common.soloader.SoLoaderShim;
import com.facebook.imagepipeline.animated.base.AnimatedDrawableFrameInfo;
import com.facebook.imagepipeline.animated.base.AnimatedDrawableFrameInfo.BlendOperation;
import com.facebook.imagepipeline.animated.base.AnimatedImage;
import com.facebook.imagepipeline.animated.factory.AnimatedImageDecoder;

/**
 * A representation of a GIF image. An instance of this class will hold a copy of the encoded
 * data in memory along with the parsed header data. Frames are decoded on demand via
 * {@link GifFrame}.
 */
@ThreadSafe
@DoNotStrip
public class GifImage implements AnimatedImage, AnimatedImageDecoder {

  private static final int LOOP_COUNT_FOREVER = 0;
  private static final int LOOP_COUNT_MISSING = -1;

  private volatile static boolean sInitialized;

  // Accessed by native methods
  @SuppressWarnings("unused")
  @DoNotStrip
  private long mNativeContext;

  private static synchronized void ensure() {
    if (!sInitialized) {
      sInitialized = true;
      SoLoaderShim.loadLibrary("gifimage");
    }
  }

  /**
   * Creates a {@link GifImage} from the specified encoded data. This will throw if it fails
   * to create. This is meant to be called on a worker thread.
   *
   * @param source the data to the image (a copy will be made)
   */
  public static GifImage create(byte[] source) {
    ensure();
    Preconditions.checkNotNull(source);

    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(source.length);
    byteBuffer.put(source);
    byteBuffer.rewind();

    return nativeCreateFromDirectByteBuffer(byteBuffer);
  }

  public static GifImage create(long nativePtr, int sizeInBytes) {
    ensure();
    Preconditions.checkArgument(nativePtr != 0);
    return nativeCreateFromNativeMemory(nativePtr, sizeInBytes);
  }

  @Override
  public AnimatedImage decode(long nativePtr, int sizeInBytes) {
    return GifImage.create(nativePtr, sizeInBytes);
  }

  @DoNotStrip
  public GifImage() {
  }

  /**
   * Constructs the image with the native pointer. This is called by native code.
   *
   * @param nativeContext the native pointer
   */
  @DoNotStrip
  GifImage(long nativeContext) {
    mNativeContext = nativeContext;
  }

  @Override
  protected void finalize() {
    nativeFinalize();
  }

  @Override
  public void dispose() {
    nativeDispose();
  }

  @Override
  public int getWidth() {
    return nativeGetWidth();
  }

  @Override
  public int getHeight() {
    return nativeGetHeight();
  }

  @Override
  public int getFrameCount() {
    return nativeGetFrameCount();
  }

  @Override
  public int getDuration() {
    return nativeGetDuration();
  }

  @Override
  public int[] getFrameDurations() {
    return nativeGetFrameDurations();
  }

  @Override
  public int getLoopCount() {
    // If a GIF image has no Netscape 2.0 loop extension, it is meant to play once and then stop. A
    // loop count of 0 indicates an endless looping of the animation. Any loop count X>0 indicates
    // that the animation shall be repeated X times, resulting in the animation to play X+1 times.
    final int loopCount = nativeGetLoopCount();
    switch (loopCount) {
      case LOOP_COUNT_FOREVER:
        return AnimatedImage.LOOP_COUNT_INFINITE;

      case LOOP_COUNT_MISSING:
        return 1;

      default:
        return loopCount + 1;
    }
  }

  @Override
  public GifFrame getFrame(int frameNumber) {
    return nativeGetFrame(frameNumber);
  }

  @Override
  public boolean doesRenderSupportScaling() {
    return false;
  }

  @Override
  public int getSizeInBytes() {
    return nativeGetSizeInBytes();
  }

  @Override
  public AnimatedDrawableFrameInfo getFrameInfo(int frameNumber) {
    GifFrame frame = getFrame(frameNumber);
    try {
      return new AnimatedDrawableFrameInfo(
          frameNumber,
          frame.getXOffset(),
          frame.getYOffset(),
          frame.getWidth(),
          frame.getHeight(),
          BlendOperation.BLEND_WITH_PREVIOUS,
          fromGifDisposalMethod(frame.getDisposalMode()));
    } finally {
      frame.dispose();
    }
  }

  private static AnimatedDrawableFrameInfo.DisposalMethod fromGifDisposalMethod(int disposalMode) {
    if (disposalMode == 0 /* DISPOSAL_UNSPECIFIED */) {
      return AnimatedDrawableFrameInfo.DisposalMethod.DISPOSE_DO_NOT;
    } else if (disposalMode == 1 /* DISPOSE_DO_NOT */) {
      return AnimatedDrawableFrameInfo.DisposalMethod.DISPOSE_DO_NOT;
    } else if (disposalMode == 2 /* DISPOSE_BACKGROUND */) {
      return AnimatedDrawableFrameInfo.DisposalMethod.DISPOSE_TO_BACKGROUND;
    } else if (disposalMode == 3 /* DISPOSE_PREVIOUS */) {
      return AnimatedDrawableFrameInfo.DisposalMethod.DISPOSE_TO_PREVIOUS;
    } else {
      return AnimatedDrawableFrameInfo.DisposalMethod.DISPOSE_DO_NOT;
    }
  }

  private static native GifImage nativeCreateFromDirectByteBuffer(ByteBuffer buffer);
  private static native GifImage nativeCreateFromNativeMemory(long nativePtr, int sizeInBytes);
  private native int nativeGetWidth();
  private native int nativeGetHeight();
  private native int nativeGetDuration();
  private native int nativeGetFrameCount();
  private native int[] nativeGetFrameDurations();
  private native int nativeGetLoopCount();
  private native GifFrame nativeGetFrame(int frameNumber);
  private native int nativeGetSizeInBytes();
  private native void nativeDispose();
  private native void nativeFinalize();
}


text:
"""Piecewise polynomial Chebyshev approximation to a given f(x)."""
from typing import Callable, List, Optional, Union
import numpy as np
from numpy.polynomial.chebyshev import Chebyshev

from qiskit.circuit import QuantumRegister, AncillaRegister
from qiskit.circuit.library.blueprintcircuit import BlueprintCircuit
from qiskit.circuit.exceptions import CircuitError

from .piecewise_polynomial_pauli_rotations import PiecewisePolynomialPauliRotations

class PiecewiseChebyshev(BlueprintCircuit):
    r"""Piecewise Chebyshev approximation to an input function.

    For a given function :math:`f(x)` and degree :math:`d`, this class implements a piecewise
    polynomial Chebyshev approximation on :math:`n` qubits to :math:`f(x)` on the given intervals.
    All the polynomials in the approximation are of degree :math:`d`.

    The values of the parameters are calculated according to [1] and see [2] for a more
    detailed explanation of the circuit construction and how it acts on the qubits.

    Examples:

        .. jupyter-execute::

            import numpy as np
            from qiskit import QuantumCircuit
            from qiskit.circuit.library.arithmetic.piecewise_chebyshev import PiecewiseChebyshev
            f_x, degree, breakpoints, num_state_qubits = lambda x: np.arcsin(1 / x), 2, [2, 4], 2
            pw_approximation = PiecewiseChebyshev(f_x, degree, breakpoints, num_state_qubits)
            pw_approximation._build()
            qc = QuantumCircuit(pw_approximation.num_qubits)
            qc.h(list(range(num_state_qubits)))
            qc.append(pw_approximation.to_instruction(), qc.qubits)
            qc.draw(output='mpl')

    References:

        [1]: Haener, T., Roetteler, M., & Svore, K. M. (2018).
             Optimizing Quantum Circuits for Arithmetic.
             `arXiv:1805.12445 <http://arxiv.org/abs/1805.12445>`_
        [2]: Carrera Vazquez, A., Hiptmair, H., & Woerner, S. (2022).
             Enhancing the Quantum Linear Systems Algorithm Using Richardson Extrapolation.
             `ACM Transactions on Quantum Computing 3, 1, Article 2 <https://doi.org/10.1145/3490631>`_
    """

    def __init__(
        self,
        f_x: Union[float, Callable[[int], float]],
        degree: Optional[int] = None,
        breakpoints: Optional[List[int]] = None,
        num_state_qubits: Optional[int] = None,
        name: str = "pw_cheb",
    ) -> None:
        r"""
        Args:
            f_x: the function to be approximated. Constant functions should be specified
             as f_x = constant.
            degree: the degree of the polynomials.
                Defaults to ``1``.
            breakpoints: the breakpoints to define the piecewise-linear function.
                Defaults to the full interval.
            num_state_qubits: number of qubits representing the state.
            name: The name of the circuit object.
        """
        super().__init__(name=name)

        # define internal parameters
        self._num_state_qubits = None

        # Store parameters
        self._f_x = f_x
        self._degree = degree if degree is not None else 1
        self._breakpoints = breakpoints if breakpoints is not None else [0]

        self._polynomials = None

        self.num_state_qubits = num_state_qubits

    def _check_configuration(self, raise_on_failure: bool = True) -> bool:
        """Check if the current configuration is valid."""
        valid = True

        if self._f_x is None:
            valid = False
            if raise_on_failure:
                raise AttributeError("The function to be approximated has not been set.")

        if self._degree is None:
            valid = False
            if raise_on_failure:
                raise AttributeError("The degree of the polynomials has not been set.")

        if self._breakpoints is None:
            valid = False
            if raise_on_failure:
                raise AttributeError("The breakpoints have not been set.")

        if self.num_state_qubits is None:
            valid = False
            if raise_on_failure:
                raise AttributeError("The number of qubits has not been set.")

        if self.num_qubits < self.num_state_qubits + 1:
            valid = False
            if raise_on_failure:
                raise CircuitError(
                    "Not enough qubits in the circuit, need at least "
                    "{}.".format(self.num_state_qubits + 1)
                )

        return valid

    @property
    def f_x(self) -> Union[float, Callable[[int], float]]:
        """The function to be approximated.

        Returns:
            The function to be approximated.
        """
        return self._f_x

    @f_x.setter
    def f_x(self, f_x: Optional[Union[float, Callable[[int], float]]]) -> None:
        """Set the function to be approximated.

        Note that this may change the underlying quantum register, if the number of state qubits
        changes.

        Args:
            f_x: The new function to be approximated.
        """
        if self._f_x is None or f_x != self._f_x:
            self._invalidate()
            self._f_x = f_x

            self._reset_registers(self.num_state_qubits)

    @property
    def degree(self) -> int:
        """The degree of the polynomials.

        Returns:
            The degree of the polynomials.
        """
        return self._degree

    @degree.setter
    def degree(self, degree: Optional[int]) -> None:
        """Set the error tolerance.

        Note that this may change the underlying quantum register, if the number of state qubits
        changes.

        Args:
            degree: The new degree.
        """
        if self._degree is None or degree != self._degree:
            self._invalidate()
            self._degree = degree

            self._reset_registers(self.num_state_qubits)

    @property
    def breakpoints(self) -> List[int]:
        """The breakpoints for the piecewise approximation.

        Returns:
            The breakpoints for the piecewise approximation.
        """
        breakpoints = self._breakpoints

        # it the state qubits are set ensure that the breakpoints match beginning and end
        if self.num_state_qubits is not None:
            num_states = 2**self.num_state_qubits

            # If the last breakpoint is < num_states, add the identity polynomial
            if breakpoints[-1] < num_states:
                breakpoints = breakpoints + [num_states]

            # If the first breakpoint is > 0, add the identity polynomial
            if breakpoints[0] > 0:
                breakpoints = [0] + breakpoints

        return breakpoints

    @breakpoints.setter
    def breakpoints(self, breakpoints: Optional[List[int]]) -> None:
        """Set the breakpoints for the piecewise approximation.

        Note that this may change the underlying quantum register, if the number of state qubits
        changes.

        Args:
            breakpoints: The new breakpoints for the piecewise approximation.
        """
        if self._breakpoints is None or breakpoints != self._breakpoints:
            self._invalidate()
            self._breakpoints = breakpoints if breakpoints is not None else [0]

            self._reset_registers(self.num_state_qubits)

    @property
    def polynomials(self) -> List[List[float]]:
        """The polynomials for the piecewise approximation.

        Returns:
            The polynomials for the piecewise approximation.

        Raises:
            TypeError: If the input function is not in the correct format.
        """
        if self.num_state_qubits is None:
            return [[]]

        # note this must be the private attribute since we handle missing breakpoints at
        # 0 and 2 ^ num_qubits here (e.g. if the function we approximate is not defined at 0
        # and the user takes that into account we just add an identity)
        breakpoints = self._breakpoints
        # Need to take into account the case in which no breakpoints were provided in first place
        if breakpoints == [0]:
            breakpoints = [0, 2**self.num_state_qubits]

        num_intervals = len(breakpoints)

        # Calculate the polynomials
        polynomials = []
        for i in range(0, num_intervals - 1):
            # Calculate the polynomial approximating the function on the current interval
            try:
                # If the function is constant don't call Chebyshev (not necessary and gives errors)
                if isinstance(self.f_x, (float, int)):
                    # Append directly to list of polynomials
                    polynomials.append([self.f_x])
                else:
                    poly = Chebyshev.interpolate(
                        self.f_x, self.degree, domain=[breakpoints[i], breakpoints[i + 1]]
                    )
                    # Convert polynomial to the standard basis and rescale it for the rotation gates
                    poly = 2 * poly.convert(kind=np.polynomial.Polynomial).coef
                    # Convert to list and append
                    polynomials.append(poly.tolist())
            except ValueError as err:
                raise TypeError(
                    " <lambda>() missing 1 required positional argument: '"
                    + self.f_x.__code__.co_varnames[0]
                    + "'."
                    + " Constant functions should be specified as 'f_x = constant'."
                ) from err

        # If the last breakpoint is < 2 ** num_qubits, add the identity polynomial
        if breakpoints[-1] < 2**self.num_state_qubits:
            polynomials = polynomials + [[2 * np.arcsin(1)]]

        # If the first breakpoint is > 0, add the identity polynomial
        if breakpoints[0] > 0:
            polynomials = [[2 * np.arcsin(1)]] + polynomials

        return polynomials

    @polynomials.setter
    def polynomials(self, polynomials: Optional[List[List[float]]]) -> None:
        """Set the polynomials for the piecewise approximation.

        Note that this may change the underlying quantum register, if the number of state qubits
        changes.

        Args:
            polynomials: The new breakpoints for the piecewise approximation.
        """
        if self._polynomials is None or polynomials != self._polynomials:
            self._invalidate()
            self._polynomials = polynomials

            self._reset_registers(self.num_state_qubits)

    @property
    def num_state_qubits(self) -> int:
        r"""The number of state qubits representing the state :math:`|x\rangle`.

        Returns:
            The number of state qubits.
        """
        return self._num_state_qubits

    @num_state_qubits.setter
    def num_state_qubits(self, num_state_qubits: Optional[int]) -> None:
        """Set the number of state qubits.

        Note that this may change the underlying quantum register, if the number of state qubits
        changes.

        Args:
            num_state_qubits: The new number of qubits.
        """
        if self._num_state_qubits is None or num_state_qubits != self._num_state_qubits:
            self._invalidate()
            self._num_state_qubits = num_state_qubits

            # Set breakpoints if they haven't been set
            if num_state_qubits is not None and self._breakpoints is None:
                self.breakpoints = [0, 2**num_state_qubits]

            self._reset_registers(num_state_qubits)

    def _reset_registers(self, num_state_qubits: Optional[int]) -> None:
        """Reset the registers."""
        self.qregs = []

        if num_state_qubits is not None:
            qr_state = QuantumRegister(num_state_qubits, "state")
            qr_target = QuantumRegister(1, "target")
            self.qregs = [qr_state, qr_target]

            num_ancillas = num_state_qubits
            if num_ancillas > 0:
                qr_ancilla = AncillaRegister(num_ancillas)
                self.add_register(qr_ancilla)

    def _build(self):
        """Build the circuit if not already build. The operation is considered successful
        when q_objective is :math:`|1>`"""
        if self._is_built:
            return

        super()._build()

        poly_r = PiecewisePolynomialPauliRotations(
            self.num_state_qubits, self.breakpoints, self.polynomials, name=self.name
        )

        # qr_state = self.qubits[: self.num_state_qubits]
        # qr_target = [self.qubits[self.num_state_qubits]]
        # qr_ancillas = self.qubits[self.num_state_qubits + 1 :]

        # Apply polynomial approximation
        self.append(poly_r.to_gate(), self.qubits)


text:
title:  "What do API Keys REALLY do?"
date:   2018-01-09 21:05:00
category: til
tags: [api, key, api key, what, do, api, keys, really, do, proxy, client, gateway, google, facebook, twitter, identity, authentication, authorization, auth]
---

TIL the true purpose of API keys: a simple yet important revelation!

Some definitions for overloaded terms that I will be using in this post:

`Client` = application built on top of public APIs.
`User` = A user of that Client app, that has an Identity registered with the public APIs.

and a **tl;dr** for those who don't want to read more:

- API keys identify a **client application** that is authorized to use the APIs.
- Authentication identifies a **user** to the APIs, so the API can return relevant data.

## The problem

This week at work, we ran in to some tricky system design questions about where pieces of user identification should live for a system of APIs we support.

We wanted to expose these APIs **publicly**, so interested users could build applications on top of them that provide additional business logic or different views than what we provide by default.

These APIs were authenticated using Auth0. A user who attempted to access the APIs needed to identify who they were via an authentication request, **so the APIs could perform role based authorization on future requests for data.** The authorization is critical to ensure that users are only seeing data they are permitted to see.

Additionally, we wanted to ensure that the APIs were not subject to DDOS attacks, and we wanted to set limits on the number of requests clients could make per day.

The solution? **Stick the APIs behind an API Gateway** which would perform `rate limiting` / `request throttling` on incoming requests. The gateway issues interested parties an `API key`, which identifies that requestor to the Gateway so it can keep track of it's request behavior.

But what's in an API key? What does this key, issued by the api gateway, really tell us about the requestor?

## API Keys Are for...

Think about times you've used API keys in the past... for Twitter, Facebook, Google APIs... you request an API key, go off and build an app on top of those APIs, and you forward the API key in all requests to those APIs **from your app**.

We realized the **from your app** piece was critical: an API key is meant to identify a **client app** that is using the APIs. In other words, an API key identifies a particular client of the API, *but tells nothing about the permissions or authorizations of a user of that client*.

API keys *can* contain information about which resources of the public API a client is able to access.

For example, maybe a user is building a client that leverages Google maps data. Their API key might permit them to access `maps` data, but the same key wouldn't allow them to access `calendar`.

A client that wanted to access `calendar` data could either request a different API key that permits calendar access, or they could request to extend the permissions of their `maps` key to also permit calendar.

Either of these solutions is possible through configuration in the API Gateway.

## So what about user identity?

If an API has a sense of user `identity`, and returns different data based on the permissions of the requesting user, a user of a client app should also be required to **authenticate with the API** to identify themselves.

This is possible to do through the client app, by offering a login page that makes the authentication request to the underlying APIs.

A public client app built on top of public apis could be accessed by anyone in the world, in theory. This is why it is critical to force the users of those apps to identify themselves to the underlying APIs, to ensure they are shown the correct data.

I hope it is clear from this example that user identity information should NOT be assumed in an API key.  An API key is just requested by a single person (generally the developer who is creating the app) so it is truly impossible and improper to attempt to identify users through an API key.

## Recap

So to recap:

- API keys identify a **client application** that is authorized to use the APIs.
- Authentication identifies a **user** to the APIs, so the API can return relevant data.

Clarity, thy name is API key!