text:
package com.yammer.dropwizard.json;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.cfg.HandlerInstantiator;
import com.fasterxml.jackson.databind.introspect.VisibilityChecker;
import com.fasterxml.jackson.databind.jsontype.SubtypeResolver;
import com.fasterxml.jackson.databind.jsontype.TypeResolverBuilder;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.SerializerFactory;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.text.DateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

/**
 * A factory class for {@link ObjectMapper}.
 *
 *
By default, ObjectMapperFactory is configured to:

 *

 *
Allow both C-style line and block comments.

 *
Not fail when encountering unknown properties.

 *
Use {@code snake_case} for property names when encoding and decoding
 *         classes annotated with {@link JsonSnakeCase}.

 *
Support Guava and Logback types.

 *

 */
@SuppressWarnings("UnusedDeclaration")
public class ObjectMapperFactory {
    private final List<Module> modules;
    private final Map<MapperFeature, Boolean> mapperFeatures;
    private final Map<DeserializationFeature, Boolean> deserializationFeatures;
    private final Map<SerializationFeature, Boolean> serializationFeatures;
    private final Map<JsonGenerator.Feature, Boolean> generatorFeatures;
    private final Map<JsonParser.Feature, Boolean> parserFeatures;
    private final Map<JsonFactory.Feature, Boolean> factoryFeatures;
    private final Map<PropertyAccessor, JsonAutoDetect.Visibility> visibilityRules;

    private AnnotationIntrospector annotationIntrospector;
    private DateFormat dateFormat;
    private PropertyNamingStrategy propertyNamingStrategy;
    private TypeResolverBuilder<?> defaultTyping;
    private FilterProvider filters;
    private HandlerInstantiator handlerInstantiator;
    private InjectableValues injectableValues;
    private Locale locale;
    private Map<Class<?>, Class<?>> mixinAnnotations;
    private JsonNodeFactory nodeFactory;
    private JsonInclude.Include serializationInclusion;
    private SerializerFactory serializerFactory;
    private DefaultSerializerProvider serializerProvider;
    private SubtypeResolver subtypeResolver;
    private TimeZone timeZone;
    private TypeFactory typeFactory;
    private VisibilityChecker<?> visibilityChecker;

    /**
     * Create a new ObjectMapperFactory.
     */
    public ObjectMapperFactory() {
        this.modules = Lists.newArrayList();
        this.mapperFeatures = Maps.newHashMap();
        this.deserializationFeatures = Maps.newHashMap();
        this.serializationFeatures = Maps.newHashMap();
        this.generatorFeatures = Maps.newHashMap();
        this.parserFeatures = Maps.newHashMap();
        this.factoryFeatures = Maps.newHashMap();
        this.visibilityRules = Maps.newLinkedHashMap();

        this.propertyNamingStrategy = AnnotationSensitivePropertyNamingStrategy.INSTANCE;

        enable(JsonParser.Feature.ALLOW_COMMENTS);
        disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        registerModule(new GuavaModule());
        registerModule(new LogbackModule());
        registerModule(new GuavaExtrasModule());
    }

    public AnnotationIntrospector getAnnotationIntrospector() {
        return annotationIntrospector;
    }

    public void setAnnotationIntrospector(AnnotationIntrospector annotationIntrospector) {
        this.annotationIntrospector = annotationIntrospector;
    }

    public DateFormat getDateFormat() {
        return dateFormat;
    }

    public void setDateFormat(DateFormat dateFormat) {
        this.dateFormat = dateFormat;
    }

    public TypeResolverBuilder<?> getDefaultTyping() {
        return defaultTyping;
    }

    public void setDefaultTyping(TypeResolverBuilder<?> defaultTyping) {
        this.defaultTyping = defaultTyping;
    }

    public FilterProvider getFilters() {
        return filters;
    }

    public void setFilters(FilterProvider filters) {
        this.filters = filters;
    }

    public HandlerInstantiator getHandlerInstantiator() {
        return handlerInstantiator;
    }

    public void setHandlerInstantiator(HandlerInstantiator handlerInstantiator) {
        this.handlerInstantiator = handlerInstantiator;
    }

    public InjectableValues getInjectableValues() {
        return injectableValues;
    }

    public void setInjectableValues(InjectableValues injectableValues) {
        this.injectableValues = injectableValues;
    }

    public Locale getLocale() {
        return locale;
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    public Map<Class<?>, Class<?>> getMixinAnnotations() {
        return mixinAnnotations;
    }

    public void setMixinAnnotations(Map<Class<?>, Class<?>> mixinAnnotations) {
        this.mixinAnnotations = mixinAnnotations;
    }

    public JsonNodeFactory getNodeFactory() {
        return nodeFactory;
    }

    public void setNodeFactory(JsonNodeFactory nodeFactory) {
        this.nodeFactory = nodeFactory;
    }

    public PropertyNamingStrategy getPropertyNamingStrategy() {
        return propertyNamingStrategy;
    }

    public void setPropertyNamingStrategy(PropertyNamingStrategy propertyNamingStrategy) {
        this.propertyNamingStrategy = propertyNamingStrategy;
    }

    public JsonInclude.Include getSerializationInclusion() {
        return serializationInclusion;
    }

    public void setSerializationInclusion(JsonInclude.Include serializationInclusion) {
        this.serializationInclusion = serializationInclusion;
    }

    public SerializerFactory getSerializerFactory() {
        return serializerFactory;
    }

    public void setSerializerFactory(SerializerFactory serializerFactory) {
        this.serializerFactory = serializerFactory;
    }

    public DefaultSerializerProvider getSerializerProvider() {
        return serializerProvider;
    }

    public void setSerializerProvider(DefaultSerializerProvider serializerProvider) {
        this.serializerProvider = serializerProvider;
    }

    public SubtypeResolver getSubtypeResolver() {
        return subtypeResolver;
    }

    public void setSubtypeResolver(SubtypeResolver subtypeResolver) {
        this.subtypeResolver = subtypeResolver;
    }

    public TimeZone getTimeZone() {
        return timeZone;
    }

    public void setTimeZone(TimeZone timeZone) {
        this.timeZone = timeZone;
    }

    public TypeFactory getTypeFactory() {
        return typeFactory;
    }

    public void setTypeFactory(TypeFactory typeFactory) {
        this.typeFactory = typeFactory;
    }

    public JsonAutoDetect.Visibility getVisibility(PropertyAccessor accessor) {
        return visibilityRules.get(accessor);
    }

    public void setVisibilityRules(PropertyAccessor accessor, JsonAutoDetect.Visibility visibility) {
        visibilityRules.put(accessor, visibility);
    }

    public VisibilityChecker<?> getVisibilityChecker() {
        return visibilityChecker;
    }

    public void setVisibilityChecker(VisibilityChecker<?> visibilityChecker) {
        this.visibilityChecker = visibilityChecker;
    }

    /**
     * Registers a module that can extend functionality provided by this class; for example, by
     * adding providers for custom serializers and deserializers.
     *
     * @param module Module to register
     * @see ObjectMapper#registerModule(Module)
     */
    public void registerModule(Module module) {
        modules.add(module);
    }

    /**
     * Returns true if the given {@link MapperFeature} is enabled.
     *
     * @param feature a given feature
     * @return {@code true} if {@code feature} is enabled
     * @see ObjectMapper#isEnabled(MapperFeature)
     */
    public boolean isEnabled(MapperFeature feature) {
        final Boolean enabled = mapperFeatures.get(feature);
        if (enabled != null) {
            return enabled;
        }
        return feature.enabledByDefault();
    }

    /**
     * Enables the given {@link MapperFeature}s.
     *
     * @param features a set of features to enable
     * @see ObjectMapper#enable(MapperFeature...)
     */
    public void enable(MapperFeature... features) {
        for (MapperFeature feature : features) {
            mapperFeatures.put(feature, Boolean.TRUE);
        }
    }

    /**
     * Disables the given {@link MapperFeature}s.
     *
     * @param features a set of features to disable
     * @see ObjectMapper#disable(MapperFeature...)
     */
    public void disable(MapperFeature... features) {
        for (MapperFeature feature : features) {
            mapperFeatures.put(feature, Boolean.FALSE);
        }
    }

    /**
     * Returns true if the given {@link DeserializationFeature} is enabled.
     *
     * @param feature a given feature
     * @return {@code true} if {@code feature} is enabled
     * @see ObjectMapper#isEnabled(DeserializationFeature)
     */
    public boolean isEnabled(DeserializationFeature feature) {
        final Boolean enabled = deserializationFeatures.get(feature);
        if (enabled != null) {
            return enabled;
        }
        return feature.enabledByDefault();
    }

    /**
     * Enables the given {@link DeserializationFeature}s.
     *
     * @param features a set of features to enable
     * @see ObjectMapper#enable(DeserializationFeature)
     */
    public void enable(DeserializationFeature... features) {
        for (DeserializationFeature feature : features) {
            deserializationFeatures.put(feature, Boolean.TRUE);
        }
    }

    /**
     * Disables the given {@link DeserializationFeature}s.
     *
     * @param features a set of features to disable
     * @see ObjectMapper#disable(DeserializationFeature)
     */
    public void disable(DeserializationFeature... features) {
        for (DeserializationFeature feature : features) {
            deserializationFeatures.put(feature, Boolean.FALSE);
        }
    }

    /**
     * Returns true if the given {@link SerializationFeature} is enabled.
     *
     * @param feature a given feature
     * @return {@code true} if {@code feature} is enabled
     * @see ObjectMapper#isEnabled(SerializationFeature)
     */
    public boolean isEnabled(SerializationFeature feature) {
        final Boolean enabled = serializationFeatures.get(feature);
        if (enabled != null) {
            return enabled;
        }
        return feature.enabledByDefault();
    }

    /**
     * Enables the given {@link SerializationFeature}s.
     *
     * @param features a set of features to enable
     * @see ObjectMapper#enable(SerializationFeature)
     */
    public void enable(SerializationFeature... features) {
        for (SerializationFeature feature : features) {
            serializationFeatures.put(feature, Boolean.TRUE);
        }
    }

    /**
     * Disables the given {@link SerializationFeature}s.
     *
     * @param features a set of features to disable
     * @see ObjectMapper#disable(SerializationFeature)
     */
    public void disable(SerializationFeature... features) {
        for (SerializationFeature feature : features) {
            serializationFeatures.put(feature, Boolean.FALSE);
        }
    }

    /**
     * Returns true if the given {@link JsonGenerator.Feature} is enabled.
     *
     * @param feature a given feature
     * @return {@code true} if {@code feature} is enabled
     * @see ObjectMapper#isEnabled(JsonGenerator.Feature)
     */
    public boolean isEnabled(JsonGenerator.Feature feature) {
        final Boolean enabled = generatorFeatures.get(feature);
        if (enabled != null) {
            return enabled;
        }
        return feature.enabledByDefault();
    }

    /**
     * Enables the given {@link JsonGenerator.Feature}s.
     *
     * @param features a set of features to enable
     * @see JsonFactory#enable(JsonGenerator.Feature)
     */
    public void enable(JsonGenerator.Feature... features) {
        for (JsonGenerator.Feature feature : features) {
            generatorFeatures.put(feature, Boolean.TRUE);
        }
    }

    /**
     * Disables the given {@link JsonGenerator.Feature}s.
     *
     * @param features a set of features to disable
     * @see JsonFactory#disable(JsonGenerator.Feature)
     */
    public void disable(JsonGenerator.Feature... features) {
        for (JsonGenerator.Feature feature : features) {
            generatorFeatures.put(feature, Boolean.FALSE);
        }
    }

    /**
     * Returns true if the given {@link JsonParser.Feature} is enabled.
     *
     * @param feature a given feature
     * @return {@code true} if {@code feature} is enabled
     * @see ObjectMapper#isEnabled(JsonParser.Feature)
     */
    public boolean isEnabled(JsonParser.Feature feature) {
        final Boolean enabled = parserFeatures.get(feature);
        if (enabled != null) {
            return enabled;
        }
        return feature.enabledByDefault();
    }

    /**
     * Enables the given {@link JsonParser.Feature}s.
     *
     * @param features a set of features to enable
     * @see JsonFactory#enable(JsonParser.Feature)
     */
    public void enable(JsonParser.Feature... features) {
        for (JsonParser.Feature feature : features) {
            parserFeatures.put(feature, Boolean.TRUE);
        }
    }

    /**
     * Disables the given {@link JsonParser.Feature}s.
     *
     * @param features a set of features to disable
     * @see JsonFactory#disable(JsonParser.Feature)
     */
    public void disable(JsonParser.Feature... features) {
        for (JsonParser.Feature feature : features) {
            parserFeatures.put(feature, Boolean.FALSE);
        }
    }

    /**
     * Returns true if the given {@link JsonFactory.Feature} is enabled.
     *
     * @param feature a given feature
     * @return {@code true} if {@code feature} is enabled
     * @see ObjectMapper#isEnabled(JsonFactory.Feature)
     */
    public boolean isEnabled(JsonFactory.Feature feature) {
        final Boolean enabled = factoryFeatures.get(feature);
        if (enabled != null) {
            return enabled;
        }
        return feature.enabledByDefault();
    }

    /**
     * Enables the given {@link JsonFactory.Feature}s.
     *
     * @param features a set of features to enable
     * @see JsonFactory#enable(JsonFactory.Feature)
     */
    public void enable(JsonFactory.Feature... features) {
        for (JsonFactory.Feature feature : features) {
            factoryFeatures.put(feature, Boolean.TRUE);
        }
    }

    /**
     * Disables the given {@link JsonFactory.Feature}s.
     *
     * @param features a set of features to disable
     * @see JsonFactory#disable(JsonFactory.Feature)
     */
    public void disable(JsonFactory.Feature... features) {
        for (JsonFactory.Feature feature : features) {
            factoryFeatures.put(feature, Boolean.FALSE);
        }
    }

    /**
     * Builds a new {@link ObjectMapper} instance with the given {@link JsonFactory} instance.
     *
     * @param factory a {@link JsonFactory}
     * @return a configured {@link ObjectMapper} instance
     */
    public ObjectMapper build(JsonFactory factory) {
        final ObjectMapper mapper = new ObjectMapper(factory);

        for (Module module : modules) {
            mapper.registerModule(module);
        }

        for (Map.Entry<MapperFeature, Boolean> entry : mapperFeatures.entrySet()) {
            mapper.configure(entry.getKey(), entry.getValue());
        }

        for (Map.Entry<DeserializationFeature, Boolean> entry : deserializationFeatures.entrySet()) {
            mapper.configure(entry.getKey(), entry.getValue());
        }

        for (Map.Entry<SerializationFeature, Boolean> entry : serializationFeatures.entrySet()) {
            mapper.configure(entry.getKey(), entry.getValue());
        }

        for (Map.Entry<JsonGenerator.Feature, Boolean> entry : generatorFeatures.entrySet()) {
            mapper.getFactory().configure(entry.getKey(), entry.getValue());
        }

        for (Map.Entry<JsonParser.Feature, Boolean> entry : parserFeatures.entrySet()) {
            mapper.getFactory().configure(entry.getKey(), entry.getValue());
        }

        for (Map.Entry<JsonFactory.Feature, Boolean> entry : factoryFeatures.entrySet()) {
            mapper.getFactory().configure(entry.getKey(), entry.getValue());
        }

        if (annotationIntrospector != null) {
            mapper.setAnnotationIntrospector(annotationIntrospector);
        }

        if (dateFormat != null) {
            mapper.setDateFormat(dateFormat);
        }

        if (defaultTyping != null) {
            mapper.setDefaultTyping(defaultTyping);
        }

        if (filters != null) {
            mapper.setFilters(filters);
        }

        if (handlerInstantiator != null) {
            mapper.setHandlerInstantiator(handlerInstantiator);
        }

        if (injectableValues != null) {
            mapper.setInjectableValues(injectableValues);
        }

        if (locale != null) {
            mapper.setLocale(locale);
        }

        if (mixinAnnotations != null) {
            mapper.setMixInAnnotations(mixinAnnotations);
        }

        if (nodeFactory != null) {
            mapper.setNodeFactory(nodeFactory);
        }

        if (propertyNamingStrategy != null) {
            mapper.setPropertyNamingStrategy(propertyNamingStrategy);
        }

        if (serializationInclusion != null) {
            mapper.setSerializationInclusion(serializationInclusion);
        }

        if (serializerFactory != null) {
            mapper.setSerializerFactory(serializerFactory);
        }

        if (serializerProvider != null) {
            mapper.setSerializerProvider(serializerProvider);
        }

        if (subtypeResolver != null) {
            mapper.setSubtypeResolver(subtypeResolver);
        }

        if (timeZone != null) {
            mapper.setTimeZone(timeZone);
        }

        if (typeFactory != null) {
            mapper.setTypeFactory(typeFactory);
        }

        for (Map.Entry<PropertyAccessor, JsonAutoDetect.Visibility> rule : visibilityRules.entrySet()) {
            mapper.setVisibility(rule.getKey(), rule.getValue());
        }

        if (visibilityChecker != null) {
            mapper.setVisibilityChecker(visibilityChecker);
        }

        return mapper;
    }

    /**
     * Builds a new {@link ObjectMapper} instance with a default {@link JsonFactory} instance.
     *
     * @return a configured {@link ObjectMapper} instance
     */
    public ObjectMapper build() {
        return build(new JsonFactory());
    }

    /**
     * Creates a copy of {@code this}.
     *
     * @return a copy of {@code this}
     */
    public ObjectMapperFactory copy() {
        final ObjectMapperFactory factory = new ObjectMapperFactory();

        factory.modules.addAll(modules);
        factory.mapperFeatures.putAll(mapperFeatures);
        factory.deserializationFeatures.putAll(deserializationFeatures);
        factory.serializationFeatures.putAll(serializationFeatures);
        factory.generatorFeatures.putAll(generatorFeatures);
        factory.parserFeatures.putAll(parserFeatures);
        factory.factoryFeatures.putAll(factoryFeatures);
        factory.visibilityRules.putAll(visibilityRules);

        factory.annotationIntrospector = annotationIntrospector;
        factory.dateFormat = dateFormat;
        factory.defaultTyping = defaultTyping;
        factory.filters = filters;
        factory.handlerInstantiator = handlerInstantiator;
        factory.injectableValues = injectableValues;
        factory.locale = locale;
        factory.mixinAnnotations = mixinAnnotations;
        factory.nodeFactory = nodeFactory;
        factory.propertyNamingStrategy = propertyNamingStrategy;
        factory.serializationInclusion = serializationInclusion;
        factory.serializerFactory = serializerFactory;
        factory.serializerProvider = serializerProvider;
        factory.subtypeResolver = subtypeResolver;
        factory.timeZone = timeZone;
        factory.visibilityChecker = visibilityChecker;

        return factory;
    }
}


text:
package edu.berkeley.nlp.util;

import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

/**
 * Filters contains some simple implementations of the Filter interface.
 *
 * @author Christopher Manning
 * @version 1.0
 */
public class Filters {

	/**
	 * Nothing to instantiate
	 */
	private Filters() {
	}

	/**
	 * The acceptFilter accepts everything.
	 */
	public static Filter acceptFilter() {
		return new CategoricalFilter(true);
	}

	public static <T> Filter<T> acceptFilter(Class<T> name) {
		return new CategoricalFilter<T>(true);
	}

	public static <T> Filter<T> acceptFilter(T dummyObject) {
		return new CategoricalFilter<T>(true);
	}

	/**
	 * The rejectFilter accepts nothing.
	 */
	public static Filter rejectFilter() {
		return new CategoricalFilter(false);
	}

	private static final class CategoricalFilter<T> implements Filter<T> {

		private final boolean judgment;

		private CategoricalFilter(boolean judgment) {
			this.judgment = judgment;
		}

		/**
		 * Checks if the given object passes the filter.
		 *
		 * @param obj
		 *            an object to test
		 */
		public boolean accept(T obj) {
			return judgment;
		}
	}

	/**
	 * The collectionAcceptFilter accepts a certain collection.
	 */
	public static <T> Filter<T> collectionAcceptFilter(T[] objs) {
		return new CollectionAcceptFilter<T>(Arrays.asList(objs), true);
	}

	/**
	 * The collectionAcceptFilter accepts a certain collection.
	 */
	public static <T> Filter<T> collectionAcceptFilter(Collection<T> objs) {
		return new CollectionAcceptFilter<T>(objs, true);
	}

	/**
	 * The collectionRejectFilter rejects a certain collection.
	 */
	public static <T> Filter<T> collectionRejectFilter(T[] objs) {
		return new CollectionAcceptFilter<T>(Arrays.asList(objs), false);
	}

	/**
	 * The collectionRejectFilter rejects a certain collection.
	 */
	public static <T> Filter<T> collectionRejectFilter(Collection<T> objs) {
		return new CollectionAcceptFilter<T>(objs, false);
	}

	private static final class CollectionAcceptFilter<T> implements Filter<T>,
			Serializable {

		private static final long serialVersionUID = 1L;
		private final Collection<T> args;
		private final boolean judgment;

		private CollectionAcceptFilter(Collection<T> c, boolean judgment) {
			this.args = new HashSet<T>(c);
			this.judgment = judgment;
		}

		/**
		 * Checks if the given object passes the filter.
		 *
		 * @param obj
		 *            an object to test
		 */
		public boolean accept(T obj) {
			if (args.contains(obj)) {
				return judgment;
			} else {
				return !judgment;
			}
		}
	}

	/**
	 * Filter that accepts only when both filters accept (AND).
	 */
	public static <T> Filter<T> andFilter(Filter<T> f1, Filter<T> f2) {
		return (new CombinedFilter<T>(f1, f2, true));
	}

	/**
	 * Filter that accepts when either filter accepts (OR).
	 */
	public static <T> Filter<T> orFilter(Filter<T> f1, Filter<T> f2) {
		return (new CombinedFilter<T>(f1, f2, false));
	}

	/**
	 * Conjunction or disjunction of two filters.
	 */
	private static class CombinedFilter<T> implements Filter<T> {
		private Filter<T> f1, f2;
		private boolean conjunction; // and vs. or

		public CombinedFilter(Filter<T> f1, Filter<T> f2, boolean conjunction) {
			this.f1 = f1;
			this.f2 = f2;
			this.conjunction = conjunction;
		}

		public boolean accept(T o) {
			if (conjunction) {
				return (f1.accept(o) && f2.accept(o));
			}
			return (f1.accept(o) || f2.accept(o));
		}
	}

	/**
	 * Filter that does the opposite of given filter (NOT).
	 */
	public static <T> Filter<T> notFilter(Filter<T> filter) {
		return (new NegatedFilter<T>(filter));
	}

	/**
	 * Filter that's either negated or normal as specified.
	 */
	public static <T> Filter<T> switchedFilter(Filter<T> filter, boolean negated) {
		return (new NegatedFilter<T>(filter, negated));
	}

	/**
	 * Negation of a filter.
	 */
	private static class NegatedFilter<T> implements Filter<T> {
		private Filter<T> filter;
		private boolean negated;

		public NegatedFilter(Filter<T> filter, boolean negated) {
			this.filter = filter;
			this.negated = negated;
		}

		public NegatedFilter(Filter<T> filter) {
			this(filter, true);
		}

		public boolean accept(T o) {
			return (negated ^ filter.accept(o)); // xor
		}
	}

	/**
	 * Applies the given filter to each of the given elems, and returns the list
	 * of elems that were accepted. The runtime type of the returned array is
	 * the same as the passed in array.
	 */
	public static <T> Object[] filter(T[] elems, Filter<T> filter) {
		List<T> filtered = new ArrayList<T>();
		for (int i = 0; i < elems.length; i++) {
			if (filter.accept(elems[i])) {
				filtered.add(elems[i]);
			}
		}
		return (filtered.toArray((Object[]) Array.newInstance(elems.getClass()
				.getComponentType(), filtered.size())));
	}

	/**
	 * Removes all elems in the given Collection that aren't accepted by the
	 * given Filter.
	 */
	public static <T> void retainAll(Collection<T> elems, Filter<T> filter) {
		for (T elem : elems) {
			if (!filter.accept(elem)) {
				elems.remove(elem);
			}
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
/*
JWT stands for JSON Web Token.
The package creates, serves, and verifies JWT used by HTTP clients.

JWT user ID and access rights are stored in documents of collection "jwt", each document record should look like:
{
    "user": "user_name",
    "pass": "password_plain_text",
    "endpoints": [
        "create",
        "drop",
        "insert",
        "query",
        "update",
        "other_api_endpoint_names..."
    ],
    "collections: [
        "collection_name_A",
        "collection_name_B",
        "other_collection_names..."
    ]
}

A JWT document record allows a user identity identified by "user" and "pass" to call the specified API endpoints
on the specified collections.

The JWT identity collection "jwt", along with a special user identity "admin", are created upon startup.
If they are missing, they will be re-created automatically upon startup.

The special user identity "admin" allows access to all features and collection data. Its default password is empty string.
*/

package httpapi

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"

	"github.com/HouzuoGuo/tiedot/db"
	"github.com/HouzuoGuo/tiedot/tdlog"
	jwt "github.com/dgrijalva/jwt-go"
)

var (
	privateKey []byte //openssl genrsa -out rsa 1024
	publicKey  []byte //openssl rsa -in rsa -pubout > rsa.pub
)

const (
	// JWT Record and claim
	JWT_COL_NAME         = "jwt"
	JWT_USER_ATTR        = "user"
	JWT_PASS_ATTR        = "pass"
	JWT_ENDPOINTS_ATTR   = "endpoints"
	JWT_COLLECTIONS_ATTR = "collections"
	JWT_USER_ADMIN       = "admin"
	// JWT claim
	JWT_EXPIRY = "exp"
)

// If necessary, create the JWT identity collection, indexes, and the default/special user identity "admin".
func jwtInitSetup() {
	// Create collection
	if HttpDB.Use(JWT_COL_NAME) == nil {
		if err := HttpDB.Create(JWT_COL_NAME); err != nil {
			tdlog.Panicf("JWT: failed to create JWT identity collection - %v", err)
		}
	}
	jwtCol := HttpDB.Use(JWT_COL_NAME)
	// Create indexes on ID attribute
	indexPaths := make(map[string]struct{})
	for _, oneIndex := range jwtCol.AllIndexes() {
		indexPaths[strings.Join(oneIndex, db.INDEX_PATH_SEP)] = struct{}{}
	}
	if _, exists := indexPaths[JWT_USER_ATTR]; !exists {
		if err := jwtCol.Index([]string{JWT_USER_ATTR}); err != nil {
			tdlog.Panicf("JWT: failed to create collection index - %v", err)
		}
	}
	// Create default user "admin"
	adminQuery := map[string]interface{}{
		"eq": JWT_USER_ADMIN,
		"in": []interface{}{JWT_USER_ATTR}}
	adminQueryResult := make(map[int]struct{})
	if err := db.EvalQuery(adminQuery, jwtCol, &adminQueryResult); err != nil {
		tdlog.Panicf("JWT: failed to query admin user ID - %v", err)
	}
	if len(adminQueryResult) == 0 {
		if _, err := jwtCol.Insert(map[string]interface{}{
			JWT_USER_ATTR:        JWT_USER_ADMIN,
			JWT_PASS_ATTR:        "",
			JWT_COLLECTIONS_ATTR: []interface{}{},
			JWT_ENDPOINTS_ATTR:   []interface{}{}}); err != nil {
			tdlog.Panicf("JWT: failed to create default admin user - %v", err)
		}
		tdlog.Notice("JWT: successfully initialized DB for JWT features. The default user 'admin' has been created.")
	}
}

// Enforce must-revalidate cache control, and configure response headers for CORS operation.
func addCommonJwtRespHeaders(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate")
	if origin := r.Header.Get("Origin"); origin != "" {
		w.Header().Set("Access-Control-Allow-Origin", origin)
	}
	w.Header().Set("Access-Control-Expose-Headers", "Authorization")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}

// Verify user identity and hand out a JWT.
func getJWT(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	addCommonJwtRespHeaders(w, r)
	// Verify identity
	user := r.FormValue(JWT_USER_ATTR)
	if user == "" {
		http.Error(w, "Please pass JWT 'user' parameter", http.StatusBadRequest)
		return
	}
	jwtCol := HttpDB.Use(JWT_COL_NAME)
	if jwtCol == nil {
		http.Error(w, "Server is missing JWT identity collection, please restart the server.", http.StatusInternalServerError)
		return
	}
	userQuery := map[string]interface{}{
		"eq": user,
		"in": []interface{}{JWT_USER_ATTR}}
	userQueryResult := make(map[int]struct{})
	if err := db.EvalQuery(userQuery, jwtCol, &userQueryResult); err != nil {
		tdlog.CritNoRepeat("Query failed in JWT identity collection : %v", err)
		http.Error(w, "Query failed in JWT identity collection", http.StatusInternalServerError)
		return
	}
	// Verify password
	pass := r.FormValue(JWT_PASS_ATTR)
	for recID, _ := range userQueryResult {
		rec, err := jwtCol.Read(recID)
		if err != nil {
			break
		}
		if rec[JWT_PASS_ATTR] != pass {
			tdlog.CritNoRepeat("JWT: identitify verification failed from request sent by %s", r.RemoteAddr)
			break
		}
		// Successful password match
		token := jwt.New(jwt.GetSigningMethod("RS256"))
		token.Claims[JWT_USER_ATTR] = rec[JWT_USER_ATTR]
		token.Claims[JWT_COLLECTIONS_ATTR] = rec[JWT_COLLECTIONS_ATTR]
		token.Claims[JWT_ENDPOINTS_ATTR] = rec[JWT_ENDPOINTS_ATTR]
		token.Claims[JWT_EXPIRY] = time.Now().Add(time.Hour * 72).Unix()
		var tokenString string
		var e error
		if tokenString, e = token.SignedString(privateKey); e != nil {
			panic(e)
		}
		w.Header().Set("Authorization", "Bearer "+tokenString)
		w.WriteHeader(http.StatusOK)
		return
	}
	// ... password mismatch
	http.Error(w, "Invalid password", http.StatusUnauthorized)
}

// Verify user's JWT.
func checkJWT(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	addCommonJwtRespHeaders(w, r)
	t, err := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
		return publicKey, nil
	})
	if t == nil || !t.Valid {
		http.Error(w, fmt.Sprintf("{\"error\": \"%s %s\"}", "JWT not valid,", err), http.StatusUnauthorized)
	} else {
		w.WriteHeader(http.StatusOK)
	}
}

// Enable JWT authorization check on the HTTP handler function.
func jwtWrap(originalHandler http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		addCommonJwtRespHeaders(w, r)
		t, _ := jwt.ParseFromRequest(r, func(token *jwt.Token) (interface{}, error) {
			return publicKey, nil
		})
		if t == nil || !t.Valid {
			http.Error(w, "", http.StatusUnauthorized)
			return
		} else if t.Claims[JWT_USER_ATTR] == JWT_USER_ADMIN {
			originalHandler(w, r)
			return
		}
		var url = strings.TrimPrefix(r.URL.Path, "/")
		var col = r.FormValue("col")
		if !sliceContainsStr(t.Claims[JWT_ENDPOINTS_ATTR], url) {
			http.Error(w, "", http.StatusUnauthorized)
			return
		} else if col != "" && !sliceContainsStr(t.Claims[JWT_COLLECTIONS_ATTR], col) {
			http.Error(w, "", http.StatusUnauthorized)
			return
		}
		originalHandler(w, r)
	}
}

// Return true if the string appears in string slice.
func sliceContainsStr(possibleSlice interface{}, str string) bool {
	switch possibleSlice.(type) {
	case []string:
		for _, elem := range possibleSlice.([]string) {
			if elem == str {
				return true
			}
		}
	}
	return false
}

func ServeJWTEnabledEndpoints(jwtPubKey, jwtPrivateKey string) {
	var e error
	if publicKey, e = ioutil.ReadFile(jwtPubKey); e != nil {
		tdlog.Panicf("JWT: Failed to read public key file - %s", e)
	} else if privateKey, e = ioutil.ReadFile(jwtPrivateKey); e != nil {
		tdlog.Panicf("JWT: Failed to read private key file - %s", e)
	}

	jwtInitSetup()

	// collection management (stop-the-world)
	http.HandleFunc("/create", jwtWrap(Create))
	http.HandleFunc("/rename", jwtWrap(Rename))
	http.HandleFunc("/drop", jwtWrap(Drop))
	http.HandleFunc("/all", jwtWrap(All))
	http.HandleFunc("/scrub", jwtWrap(Scrub))
	http.HandleFunc("/sync", jwtWrap(Sync))
	// query
	http.HandleFunc("/query", jwtWrap(Query))
	http.HandleFunc("/count", jwtWrap(Count))
	// document management
	http.HandleFunc("/insert", jwtWrap(Insert))
	http.HandleFunc("/get", jwtWrap(Get))
	http.HandleFunc("/getpage", jwtWrap(GetPage))
	http.HandleFunc("/update", jwtWrap(Update))
	http.HandleFunc("/delete", jwtWrap(Delete))
	http.HandleFunc("/approxdoccount", jwtWrap(ApproxDocCount))
	// index management (stop-the-world)
	http.HandleFunc("/index", jwtWrap(Index))
	http.HandleFunc("/indexes", jwtWrap(Indexes))
	http.HandleFunc("/unindex", jwtWrap(Unindex))
	// misc
	http.HandleFunc("/shutdown", jwtWrap(Shutdown))
	http.HandleFunc("/dump", jwtWrap(Dump))
	// does not require JWT auth
	http.HandleFunc("/getjwt", getJWT)
	http.HandleFunc("/checkjwt", checkJWT)

	tdlog.Noticef("JWT is enabled. API endpoints require JWT authorization.")
}


text:
Backlog.Iteration = DS.Model.extend({
    stories: DS.hasMany('story'),
    project: DS.belongsTo('project'),
    startDate: DS.attr('string'),
    isComplete: DS.attr('boolean'),
    velocity: function() {
        var stories = this.get('stories');
        return stories.reduce(function(previousValue, story){
            return previousValue + story.get('size');
        }, 0);
    }.property('stories.@each.size')
});

Backlog.Iteration.FIXTURES = [
    {id: 1, startDate: '2013-10-14', isComplete: false, stories: [1,2,3], project: 1},
    {id: 2, startDate: '2013-09-30', isComplete: true, stories: [4,5,6], project: 1}
];


text:
using Microsoft.Xna.Framework;

namespace AIWorld.Steering
{
    public interface ISteeringBehavior
    {
        Vector3 Calculate(GameTime gameTime);
    }
}


text:
__author__    = "Andre Merzky, Ole Weidner"
__copyright__ = "Copyright 2012-2013, The SAGA Project"
__license__   = "MIT"

''' Unit tests for saga.engine.logger.py
'''

from saga.utils.logger        import getLogger
from saga.utils.logger.logger import _Logger

import radical.utils as ru

############################# BEGIN UNIT TESTS ################################
##
def test_singleton():
    """ Test if the logger behaves like a singleton
    """
    # make sure singleton works
    assert getLogger()         == getLogger()
    assert getLogger('engine') == getLogger('engine')

def test_configurable():
    """ Test if the logger config options work
    """
    # make sure singleton works
    c = _Logger().get_config()

    assert c['ttycolor'].get_value() == True
    assert c['filters'].get_value() == []
    #assert c['level'].get_value() == 'CRITICAL'
    assert c['targets'].get_value() == ['STDOUT']

def test_logger():
    """ Print out some messages with different log levels
    """
    cl = getLogger('engine')
    cl = getLogger('engine')

    assert cl is not None
    cl.debug('debug')
    cl.info('info')
    cl.warning('warning')
    cl.error('error')
    cl.fatal('fatal')


text:
package party.pjc.blog.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesUtil {

	public static String getValue(String key){
		Properties prop =new Properties();
		InputStream in = new PropertiesUtil().getClass().getResourceAsStream("/lvcblog.properties");
		try {
			prop.load(in);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return (String) prop.get(key);
	}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Even_number_check
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    Console.Write("Въведете число ");
                    var n = int.Parse(Console.ReadLine());

                    if (n % 2 == 0)
                    {
                        Console.WriteLine($"Even number entered: {n}");
                        break;
                    }

                    Console.WriteLine("The number is not even.");
                    Console.Write("Въведете число ");
                    n = int.Parse(Console.ReadLine());
                }
                catch
                {
                    Console.WriteLine("Invalid number!");
                }
            }

        }
    }
}


text:
package com.marklogic.contentpump;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.util.ReflectionUtils;

import com.marklogic.mapreduce.ContentType;
import com.marklogic.mapreduce.DocumentURIWithSourceInfo;
import com.marklogic.mapreduce.MarkLogicConstants;
import com.marklogic.mapreduce.utilities.URIUtil;

/**
 * Abstract class of RecorderReader for import.
 * @author ali
 *
 * @param <VALUEIN>
 */
public abstract class ImportRecordReader<VALUEIN>
extends RecordReader<DocumentURIWithSourceInfo, VALUEIN>
implements ConfigConstants {
    public static final Log LOG = LogFactory.getLog(ImportRecordReader.class);
    protected DocumentURIWithSourceInfo key = new DocumentURIWithSourceInfo();
    protected VALUEIN value;
    protected String mode;
    protected boolean streaming = false;
    protected Configuration conf;
    protected String encoding;
    protected Path file;
    protected FileSystem fs;
    protected Iterator<FileSplit> iterator;
    private String srcId = null;
    protected String subId = "";

    /**
     * Apply URI replace option, encode URI if specified, apply URI prefix and
     * suffix configuration options and set the result as DocumentURI key.
     *
     * @param uri Source string of document URI.
     * @param line Line number in the source if applicable; 0 otherwise.
     * @param col Column number in the source if applicable; 0 otherwise.
     * @param encode Encode uri if set to true.
     *
     * @return true if key indicates the record is to be skipped; false
     * otherwise.
     */
    protected boolean setKey(String uri, int line, int col, boolean encode) {
        if (key == null) {
            key = new DocumentURIWithSourceInfo(uri, srcId);
        }
        // apply prefix, suffix and replace for URI
        if (uri != null && !uri.isEmpty()) {
            uri = URIUtil.applyUriReplace(uri, conf);
            key.setSkipReason("");
            if (encode) {
                try {
                    URI uriObj = new URI(null, null, null, 0, uri, null, null);
                    uri = uriObj.toString();
                } catch (URISyntaxException e) {
                    uri = null;
                    key.setSkipReason(e.getMessage());
                }
            }
            uri = URIUtil.applyPrefixSuffix(uri, conf);
        } else {
            key.setSkipReason("empty uri value");
        }
        key.setUri(uri);
        key.setSrcId(srcId);
        key.setSubId(subId);
        key.setColNumber(col);
        key.setLineNumber(line);

        if (LOG.isTraceEnabled()) {
            LOG.trace("Set key: " + key);
        }
        return key.isSkip();
    }

    /**
     * Set the result as DocumentURI key.
     *
     * @param line Line number in the source if applicable; -1 otherwise.
     * @param col Column number in the source if applicable; -1 otherwise.
     * @param reason
     *
     * @return true if key indicates the record is to be skipped; false
     * otherwise.
     */
    protected void setSkipKey(int line, int col, String reason) {
        if (key == null) {
            key = new DocumentURIWithSourceInfo("", srcId, subId, line, col);
        } else {
            key.setUri("");
            key.setSrcId(srcId);
            key.setSubId(subId);
            key.setColNumber(col);
            key.setLineNumber(line);
        }
        key.setSkipReason(reason);

        if (LOG.isTraceEnabled()) {
            LOG.trace("Set key: " + key);
        }
    }

    @Override
    public abstract void close() throws IOException;

    @Override
    public DocumentURIWithSourceInfo getCurrentKey() throws IOException,
        InterruptedException {
        return key;
    }

    @Override
    public VALUEIN getCurrentValue() throws IOException, InterruptedException {
        return value;
    }

    @Override
    public abstract float getProgress() throws IOException,
        InterruptedException;

    @Override
    public abstract void initialize(InputSplit arg0,
            TaskAttemptContext context)
    throws IOException, InterruptedException;

    @SuppressWarnings("unchecked")
    protected void initConfig(TaskAttemptContext context) {
        conf = context.getConfiguration();
        String type = conf.get(MarkLogicConstants.CONTENT_TYPE,
            MarkLogicConstants.DEFAULT_CONTENT_TYPE);
        if (!conf.getBoolean(MarkLogicConstants.OUTPUT_STREAMING, false)) {
            ContentType contentType = ContentType.valueOf(type);
            Class<? extends Writable> valueClass =
                contentType.getWritableClass();
            value = (VALUEIN) ReflectionUtils.newInstance(valueClass, conf);
        }
        encoding = conf.get(MarkLogicConstants.OUTPUT_CONTENT_ENCODING,
                DEFAULT_ENCODING);
    }

    @SuppressWarnings("unchecked")
    protected void configFileNameAsCollection(Configuration conf, Path file) {
        if (file == null) {
            return;
        }
        if (conf.getBoolean(CONF_OUTPUT_FILENAME_AS_COLLECTION, false)) {
            if (value instanceof ContentWithFileNameWritable) {
                ((ContentWithFileNameWritable<VALUEIN>) value)
                    .setFileName(file.getName());
            } else {
                Writable cvalue = new ContentWithFileNameWritable<>(
                    (VALUEIN) value, file.getName());
                value = (VALUEIN) cvalue;
            }
        }
    }

    protected String makeURIFromPath(Path file) {
        // get path portion of the file
       return file.toUri().getPath().toString();
    }

    protected String makeURIForZipEntry(Path zipFile, String val) {
        Path path = new Path(zipFile, val);
        return path.toUri().getPath();
    }

    @Override
    public abstract boolean nextKeyValue() throws IOException,
        InterruptedException;

    public Path getFile() {
        return file;
    }

    public void setFile(Path file) {
        this.file = file;
        srcId = file.toString();
    }

    public FSDataInputStream openFile(InputSplit inSplit,
            boolean configCol) throws IOException {
        while (true) {
            setFile(((FileSplit) inSplit).getPath());
            if (configCol) {
                configFileNameAsCollection(conf, file);
            }
            try {
                return fs.open(file);
            } catch (IllegalArgumentException e){
                LOG.error("Input file skipped, reason: " + e.getMessage());
                if (iterator != null &&
                        iterator.hasNext()) {
                    inSplit = iterator.next();
                } else {
                    return null;
                }
            }
        }
    }
}


text:
body {
  font-family: "Montserrat", Helvetica, Arial, sans-serif;
  font-size: 11px;
  margin: auto;
  position: relative;
  -moz-osx-font-smoothing: grayscale;
   -webkit-font-smoothing: antialiased;
}

.node {
  /*font: 10px sans-serif;*/
  line-height: 12px;
  overflow: hidden;
  position: absolute;
  text-indent: 2px;
}

.font-smoothing {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}


text:
package org.assertj.core.api;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchIllegalStateException;
import static org.assertj.core.api.Assertions_catchThrowable_Test.codeThrowing;
import static org.assertj.core.api.BDDAssertions.then;
import static org.assertj.core.util.AssertionsUtil.expectAssertionError;
import static org.mockito.Mockito.mock;

import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.junit.jupiter.api.Test;

class Assertions_catchIllegalStateException_Test {

  @Test
  void catchIllegalStateException_should_fail_with_good_message_if_wrong_type() {
    // GIVEN
    ThrowingCallable code = () -> catchIllegalStateException(raisingException("boom!!"));
    // WHEN
    AssertionError assertionError = expectAssertionError(code);
    // THEN
    assertThat(assertionError).hasMessageContainingAll(IllegalStateException.class.getName(), Exception.class.getName());
  }

  @Test
  void catchIllegalStateException_should_succeed_and_return_actual_instance_with_correct_class() {
    // GIVEN
    final IllegalStateException expected = new IllegalStateException("boom!!");
    // WHEN
    IllegalStateException actual = catchIllegalStateException(codeThrowing(expected));
    // THEN
    then(actual).isSameAs(expected);
  }

  @Test
  void catchIllegalStateException_should_succeed_and_return_null_if_no_exception_thrown() {
    // WHEN
    IllegalStateException actual = catchIllegalStateException(() -> {});
    // THEN
    then(actual).isNull();
  }

  @Test
  void catchIllegalStateException_should_catch_mocked_throwable() {
    // GIVEN
    IllegalStateException illegalStateException = mock(IllegalStateException.class);
    // WHEN
    Throwable actual = catchIllegalStateException(codeThrowing(illegalStateException));
    // THEN
    then(actual).isSameAs(illegalStateException);
  }

  static ThrowingCallable raisingException(final String reason) {
    return codeThrowing(new Exception(reason));
  }

}


text:
using System;

public static class Program {
    public static void Main (string[] args) {
        // NOTE: Empty elements are treated as the same as elements with no children by the DOM.
        // Thus, <child></child> can't be in this test.
        const string xml = @"<root><child>hello</child><child>world</child><child /></root>";

        var xr = Common.ReaderFromString(xml);
        xr.ReadStartElement();

        Console.WriteLine(xr.ReadElementContentAsString() ?? "<null>");

        Console.WriteLine(xr.ReadElementContentAsString() ?? "<null>");

        Console.WriteLine(xr.ReadElementContentAsString() ?? "<null>");
    }
}


text:
<?php

namespace SP\Crawler\Element;

class Radio extends Checkbox
{
    const CHECKED = "//input[@type='radio' and @name='%s' and @checked]";

    public function uncheckOthers()
    {
        $xpath = sprintf(Radio::CHECKED, $this->getName());

        foreach ($this->getReader()->query($xpath) as $radio) {
            $radio->removeAttribute('checked');
        }
    }

    public function click()
    {
        if ($this->hasAttribute('checked')) {
            $this->removeAttribute('checked');
        } else {
            $this->uncheckOthers();
            $this->setAttribute('checked', 'checked');
        }
    }
}


text:
import numpy
import sys
import os
from PIL import Image, ImageChops
import cPickle
import gzip
from skimage.feature import hog
import math

root = '../English/Img/'
bad = 'BadImag/Bmp/'
good = 'GoodImg/Bmp/'

USE_HND = True
suffix = ''
if USE_HND:
	root = 'lenet2/data/'
	bad = ''
	good = ''
	suffix = '_hnd'

HOG_TRAINING_DATA = 'data/hog_training_data' + suffix
HOG_TRAINING_LABELS = 'data/hog_training_labels' + suffix
HOG_TESTING_DATA = 'data/hog_testing_data' + suffix
HOG_TESTING_LABELS = 'data/hog_testing_labels' + suffix

IMG_TRAINING_DATA = 'data/img_training_data' + suffix
IMG_TRAINING_LABELS = 'data/img_training_labels' + suffix
IMG_TESTING_DATA = 'data/img_testing_data' + suffix
IMG_TESTING_LABELS = 'data/img_testing_labels' + suffix

IMG2D_TRAINING_DATA = 'data/img2d_training_data' + suffix
IMG2D_TRAINING_LABELS = 'data/img2d_training_labels' + suffix
IMG2D_TESTING_DATA = 'data/img2d_testing_data' + suffix
IMG2D_TESTING_LABELS = 'data/img2d_testing_labels' + suffix

HND_TRAINING_DATA = 'data/hnd_training_data' + suffix
HND_TRAINING_LABELS = 'data/hnd_training_labels' + suffix
HND_TESTING_DATA = 'data/hnd_testing_data' + suffix
HND_TESTING_LABELS = 'data/hnd_testing_labels' + suffix

TRAINING_DATA = ''
TRAINING_LABELS = ''
TESTING_DATA = ''
TESTING_LABELS = ''

#turn this flag on if we want to test on a harder data set
USE_BAD = False

# use this flag if we want to test on HOG feature vectors
HOG = False

#use this flag if we want to test on 1D feature vectors
ONE_D = True

training_data = []
training_labels = []
testing_data = []
testing_labels = []

NUM_CELLS = 144
FINAL_IMAGE_SIZE = 75

# Range endpoint should be 63, but leaving it as 2 for testing purposes.
for i in range (1, 63):
	print "Checking " + str(i)
	num = ''
	if i < 10:
		num = str(0) + str(i) + '/'
	else:
		num = str(i) + '/'

	if USE_BAD:
		sets = [bad, good]
	else:
		sets = [good]

	for data_set in sets:
		directory = root + data_set + "Sample0" + num
		files = os.listdir(directory)
		endpoints = []
		endpoints.append(len(files)/2)

		for j in range(len(files)):
			filename = directory + files[j]
			image = Image.open(open(filename))
			image = image.convert('L')

			# sketchy stuff from http://stackoverflow.com/questions/9103257/resize-image-maintaining-aspect-ratio-and-making-portrait-and-landscape-images-e
			dim = image.size

			max_length = max(dim)

			# 12 is sqrt(NUM_CELLS)
			cell_side = int(math.sqrt(NUM_CELLS))
			if (max(dim) % cell_side != 0):
				max_length = max(dim) + cell_side - (max(dim) % cell_side)

			size = (max_length, max_length)

			image.thumbnail(size, Image.ANTIALIAS)
			image_size = image.size
			#print image_size

			thumb = image.crop( (0, 0, size[0], size[1]) )

			offset_x = max( (size[0] - image_size[0]) / 2, 0 )
			offset_y = max( (size[1] - image_size[1]) / 2, 0 )

			img = ImageChops.offset(thumb, offset_x, offset_y)
			img = img.resize((FINAL_IMAGE_SIZE, FINAL_IMAGE_SIZE), Image.ANTIALIAS)

			img = numpy.asarray(img, dtype='float64')

			ppc = int(max_length / math.sqrt(NUM_CELLS))
			feature_vector = []

			if HOG:
				feature_vector = hog(img, orientations=8, pixels_per_cell=(ppc, ppc),
                    cells_per_block=(1, 1), visualise=False)
				print len(feature_vector)
				TRAINING_DATA = HOG_TRAINING_DATA
				TRAINING_LABELS = HOG_TRAINING_LABELS
				TESTING_DATA = HOG_TESTING_DATA
				TESTING_LABELS = HOG_TESTING_LABELS

			elif ONE_D:
				feature_vector = img.flatten()
				TRAINING_DATA = IMG_TRAINING_DATA
				TRAINING_LABELS = IMG_TRAINING_LABELS
				TESTING_DATA = IMG_TESTING_DATA
				TESTING_LABELS = IMG_TESTING_LABELS
			else:
				feature_vector = img
				print feature_vector.shape
				TRAINING_DATA = HND_TRAINING_DATA
				TRAINING_LABELS = HND_TRAINING_LABELS
				TESTING_DATA = HND_TESTING_DATA
				TESTING_LABELS = HND_TESTING_LABELS

			if j >= 0 and j < endpoints[0]:
				training_data.append(feature_vector)
				training_labels.append(i)
			elif j >= endpoints[0]:
				testing_data.append(feature_vector)
				testing_labels.append(i)

training_data = numpy.asarray(training_data)
training_labels = numpy.asarray(training_labels)
testing_data = numpy.asarray(testing_data)
testing_labels = numpy.asarray(testing_labels)

numpy.save(TRAINING_DATA, training_data)
numpy.save(TRAINING_LABELS, training_labels)
numpy.save(TESTING_DATA, testing_data)
numpy.save(TESTING_LABELS, testing_labels)


text:
package com.liuhao.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.liuhao.domain.User;

@Repository
public interface UserMapper {

	int addUser(User user);

	List<User> getUsers(User user);

	User getInfo(Integer id);

	int update(User user);

	//int isExistSameMobile(User user);

	//int isExistSameEmail(User user);

	int isExistSameAccount(User user);

	int changeStatus(User user);

	User getUserByAccount(User user);

	User getSingleUser(User user);

	int updatePassword(User user);

}


text:
require 'spec_helper'

describe Apiary::CLI do
  # Don't let Thor fold or truncate lines
  ENV['THOR_COLUMNS'] = '1000'

  # The documentation that ought to match the code
  READMETEXT = open('README.md', &:read)

  it 'has help' do
    help = open('|ruby bin/apiary help', &:read)
    expect(help).to include('Commands:')
    expect(help.lines.count).to be >= 5
  end

  it 'has README.md' do
    expect(READMETEXT).to include('apiary help')
    expect(READMETEXT.lines.count).to be >= 5
  end

  # Confirm that all subcommands are documented, verbatim
  ([''] + (open('|ruby bin/apiary help', 'r', &:readlines)
            .map { |l| /^ +apiary / =~ l ? l : nil }
            .map { |l| /^ *apiary help/ =~ l ? nil : l }
            .compact
            .map { |l| /^ *apiary ([^ ]*)/.match(l)[1] + ' ' }
          )
  ).each do |cmd|
    it "includes help #{cmd}in README.md" do
      puts cmd
      helptext = open("|ruby bin/apiary help #{cmd}", &:read)

      expect(helptext).to include("apiary #{cmd.strip}")
      expect(READMETEXT).to include("apiary #{cmd.strip}")
      expect(READMETEXT).to include(helptext)
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">

    <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css"
      integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous">

    <link rel="stylesheet"
      href="https://cdn.rawgit.com/konpa/devicon/df6431e323547add1b4cf45992913f15286456d3/devicon.min.css">

    <title>Calvin C. Ieong</title>

      You need to enable JavaScript to run this app.


text:
#pragma once

#include "QUICTypes.h"
#include "QUICKeyGenerator.h"

class QUICPacketProtectionKeyInfoProvider
{
public:
  virtual ~QUICPacketProtectionKeyInfoProvider() {}
  // Payload Protection (common)
  virtual const EVP_CIPHER *get_cipher(QUICKeyPhase phase) const = 0;
  virtual size_t get_tag_len(QUICKeyPhase phase) const           = 0;

  // Payload Protection (encryption)
  virtual bool is_encryption_key_available(QUICKeyPhase phase) const = 0;
  virtual const uint8_t *encryption_key(QUICKeyPhase phase) const    = 0;
  virtual size_t encryption_key_len(QUICKeyPhase phase) const        = 0;
  virtual const uint8_t *encryption_iv(QUICKeyPhase phase) const     = 0;
  virtual const size_t *encryption_iv_len(QUICKeyPhase phase) const  = 0;

  // Payload Protection (decryption)
  virtual bool is_decryption_key_available(QUICKeyPhase phase) const = 0;
  virtual const uint8_t *decryption_key(QUICKeyPhase phase) const    = 0;
  virtual size_t decryption_key_len(QUICKeyPhase phase) const        = 0;
  virtual const uint8_t *decryption_iv(QUICKeyPhase phase) const     = 0;
  virtual const size_t *decryption_iv_len(QUICKeyPhase phase) const  = 0;

  // Header Protection
  virtual const EVP_CIPHER *get_cipher_for_hp(QUICKeyPhase phase) const  = 0;
  virtual const uint8_t *encryption_key_for_hp(QUICKeyPhase phase) const = 0;
  virtual size_t encryption_key_for_hp_len(QUICKeyPhase phase) const     = 0;
  virtual const uint8_t *decryption_key_for_hp(QUICKeyPhase phase) const = 0;
  virtual size_t decryption_key_for_hp_len(QUICKeyPhase phase) const     = 0;
};

class QUICPacketProtectionKeyInfo : public QUICPacketProtectionKeyInfoProvider
{
public:
  enum class Context { SERVER, CLIENT };

  virtual ~QUICPacketProtectionKeyInfo() {}

  // FIXME This should be passed to the constructor but NetVC cannot pass it because it has set_context too.
  void set_context(Context ctx);

  void drop_keys(QUICKeyPhase phase);

  // Payload Protection (common)

  virtual const EVP_CIPHER *get_cipher(QUICKeyPhase phase) const override;
  virtual size_t get_tag_len(QUICKeyPhase phase) const override;
  virtual void set_cipher_initial(const EVP_CIPHER *cipher);
  virtual void set_cipher(const EVP_CIPHER *cipher, size_t tag_len);

  // Payload Protection (encryption)

  virtual bool is_encryption_key_available(QUICKeyPhase phase) const override;
  virtual void set_encryption_key_available(QUICKeyPhase phase);

  virtual const uint8_t *encryption_key(QUICKeyPhase phase) const override;
  virtual uint8_t *encryption_key(QUICKeyPhase phase);

  virtual size_t encryption_key_len(QUICKeyPhase phase) const override;

  virtual const uint8_t *encryption_iv(QUICKeyPhase phase) const override;
  virtual uint8_t *encryption_iv(QUICKeyPhase phase);

  virtual const size_t *encryption_iv_len(QUICKeyPhase phase) const override;
  virtual size_t *encryption_iv_len(QUICKeyPhase phase);

  // Payload Protection (decryption)

  virtual bool is_decryption_key_available(QUICKeyPhase phase) const override;
  virtual void set_decryption_key_available(QUICKeyPhase phase);

  virtual const uint8_t *decryption_key(QUICKeyPhase phase) const override;
  virtual uint8_t *decryption_key(QUICKeyPhase phase);

  virtual size_t decryption_key_len(QUICKeyPhase phase) const override;

  virtual const uint8_t *decryption_iv(QUICKeyPhase phase) const override;
  virtual uint8_t *decryption_iv(QUICKeyPhase phase);

  virtual const size_t *decryption_iv_len(QUICKeyPhase phase) const override;
  virtual size_t *decryption_iv_len(QUICKeyPhase phase);

  // Header Protection

  virtual const EVP_CIPHER *get_cipher_for_hp(QUICKeyPhase phase) const override;
  virtual void set_cipher_for_hp_initial(const EVP_CIPHER *cipher);
  virtual void set_cipher_for_hp(const EVP_CIPHER *cipher);

  virtual const uint8_t *encryption_key_for_hp(QUICKeyPhase phase) const override;
  virtual uint8_t *encryption_key_for_hp(QUICKeyPhase phase);

  virtual size_t encryption_key_for_hp_len(QUICKeyPhase phase) const override;

  virtual const uint8_t *decryption_key_for_hp(QUICKeyPhase phase) const override;
  virtual uint8_t *decryption_key_for_hp(QUICKeyPhase phase);

  virtual size_t decryption_key_for_hp_len(QUICKeyPhase phase) const override;

private:
  Context _ctx = Context::SERVER;

  // Payload Protection

  const EVP_CIPHER *_cipher_initial = nullptr;
  const EVP_CIPHER *_cipher         = nullptr;
  size_t _tag_len                   = 0;

  bool _is_client_key_available[5] = {false};
  bool _is_server_key_available[5] = {false};

  // FIXME EVP_MAX_KEY_LENGTH and EVP_MAX_IV_LENGTH are not enough somehow
  uint8_t _client_key[5][512];
  uint8_t _server_key[5][512];

  uint8_t _client_iv[5][512];
  uint8_t _server_iv[5][512];

  size_t _client_iv_len[5];
  size_t _server_iv_len[5];

  // Header Protection

  const EVP_CIPHER *_cipher_for_hp_initial = nullptr;
  const EVP_CIPHER *_cipher_for_hp         = nullptr;

  uint8_t _client_key_for_hp[5][512];
  uint8_t _server_key_for_hp[5][512];
};


text:
Institute Information

                                  <form id="fromvalid" action="admin/about_us_submit" class="" method="post" enctype="multipart/form-data">

                                              Institute Image
                                              <img src="uploads/<?php echo $row->photo;?>" id="blah" width="210" height="260" class="img-responsive">

                                              <input type="file" name="image" data-bv-notempty="false" data-bv-notempty-message="Institute Image is required">

Image Size 210px width 260px height

										Message
										<textarea name="message" id="editor1" required="required"><?php echo $row->message; ?></textarea>

                                          CURRENT PROGRAMS OFFERED:
                                             <textarea class="form-control" name="programs" id="" cols="30" rows="10" placeholder="Message here" data-bv-notempty="true" data-bv-notempty-message="Message Required"><?php echo $row->programs;?></textarea>

                                          CURRENT STUDENT ENROLLMENT:
                                             <textarea class="form-control" name="student_enrollment" id="" cols="30" rows="15" placeholder="Message here" data-bv-notempty="true" data-bv-notempty-message="Message Required"><?php echo $row->student_enrollment;?></textarea>

                                          NUMBER OF CURRENT TEACHER & STUFF:
                                             <textarea class="form-control" name="teacher_stuff" id="" cols="30" rows="5" placeholder="Message here" data-bv-notempty="true" data-bv-notempty-message="Message Required"><?php echo $row->teacher_stuff;?></textarea>

                                          STUDENT HOUSING:
                                             <textarea class="form-control" name="student_housing" id="" cols="30" rows="5" placeholder="Message here" data-bv-notempty="true" data-bv-notempty-message="Message Required"><?php echo $row->student_housing;?></textarea>

                                              <button class="btn btn-success" type="submit"> UPDATE</button>

                                  </form>


text:
import sys
import os
sys.path.append(os.path.join(os.environ['ITHEMAL_HOME'], 'learning', 'pytorch'))

import argparse
import time
import torch
import torch.multiprocessing as mp
torch.backends.cudnn.enabled = False
from utils import messages
import models.losses as ls
import models.train as tr
from tqdm import tqdm
from mpconfig import MPConfig
from typing import Callable, List, Optional, Iterator, Tuple, NamedTuple, Union
import random
import Queue
from ithemal_utils import *
import training
import pandas as pd
import common_libs.utilities as ut

def graph_model_benchmark(base_params, benchmark_params):
    # type: (BaseParameters, BenchmarkParameters) -> None
    data = load_data(base_params)
    model = load_model(base_params, data)

    train = tr.Train(
        model, data, tr.PredictionType.REGRESSION, ls.mse_loss, 1,
        batch_size=benchmark_params.batch_size, clip=None, opt=tr.OptimizerType.ADAM_PRIVATE, lr=0.01,
    )

    model.share_memory()

    mp_config = MPConfig(benchmark_params.threads)
    partition_size = benchmark_params.examples // benchmark_params.trainers

    processes = []

    start_time = time.time()

    with mp_config:
        for rank in range(benchmark_params.trainers):
            mp_config.set_env(rank)

            partition = (rank * partition_size, (rank + 1) * partition_size)

            p = mp.Process(target=train, args=(rank, partition))
            p.daemon = True
            p.start()
            processes.append(p)

    for p in processes:
        p.join()

    end_time = time.time()
    print('Time to process {} examples: {} seconds'.format(
        benchmark_params.examples,
        end_time - start_time,
    ))

def graph_model_validate(base_params, model_file, iaca_only):
    # type: (BaseParameters, str, bool) -> None
    data = load_data(base_params)
    if iaca_only:
        cnx = ut.create_connection()
        legal_code_ids = set(
            pd.read_sql('SELECT time_id, code_id FROM times WHERE kind="iaca"', cnx)
            .set_index('time_id')
            .code_id
        )
        data.test = [datum for datum in data.test if datum.code_id in legal_code_ids]
    model = load_model(base_params, data)

    train = tr.Train(
        model, data, tr.PredictionType.REGRESSION, ls.mse_loss, 1,
        batch_size=1000, clip=None, predict_log=base_params.predict_log,
    )

    resultfile = os.environ['ITHEMAL_HOME'] + '/learning/pytorch/results/realtime_results.txt'
    (actual, predicted) = train.validate(resultfile=resultfile, loadfile=model_file)

def graph_model_dump(base_params, model_file):
    # type: (BaseParameters, str) -> None
    data = load_data(base_params)
    model = load_model(base_params, data)
    dump_model_and_data(model, data, model_file)

def main():
    # type: () -> None
    parser = argparse.ArgumentParser()

    # data arguments
    parser.add_argument('--data', required=True, help='The data file to load from')
    parser.add_argument('--embed-mode', help='The embedding mode to use (default: none)', default='none')
    parser.add_argument('--embed-file', help='The embedding file to use (default: code_delim.emb)',
                        default=os.path.join(os.environ['ITHEMAL_HOME'], 'learning', 'pytorch', 'inputs', 'embeddings', 'code_delim.emb'))
    parser.add_argument('--embed-size', help='The size of embedding to use (default: 256)', default=256, type=int)
    parser.add_argument('--hidden-size', help='The size of hidden layer to use (default: 256)', default=256, type=int)
    parser.add_argument('--no-mem', help='Remove all instructions with memory', default=False, action='store_true')

    # edge/misc arguments
    parser.add_argument('--random-edge-freq', type=float, default=0.0, help='The fraction of instructions to add an additional random forward edge to (can be >1)')
    parser.add_argument('--no-residual', default=False, action='store_true', help='Don\'t use a residual model in Ithemal')
    parser.add_argument('--no-dag-rnn', default=False, action='store_true', help='Don\'t use the DAG-RNN model in Ithemal')
    parser.add_argument('--predict-log', action='store_true', default=False, help='Predict the log of the time')
    parser.add_argument('--linear-embeddings', action='store_true', default=False, help='Use linear embeddings instead of LSTM')

    parser.add_argument('--use-rnn', action='store_true', default=False)
    rnn_type_group = parser.add_mutually_exclusive_group()
    rnn_type_group.add_argument('--rnn-normal', action='store_const', const=md.RnnType.RNN, dest='rnn_type')
    rnn_type_group.add_argument('--rnn-lstm', action='store_const', const=md.RnnType.LSTM, dest='rnn_type')
    rnn_type_group.add_argument('--rnn-gru', action='store_const', const=md.RnnType.GRU, dest='rnn_type')
    parser.set_defaults(rnn_type=md.RnnType.LSTM)

    rnn_hierarchy_type_group = parser.add_mutually_exclusive_group()
    rnn_hierarchy_type_group.add_argument('--rnn-token', action='store_const', const=md.RnnHierarchyType.NONE, dest='rnn_hierarchy_type')
    rnn_hierarchy_type_group.add_argument('--rnn-dense', action='store_const', const=md.RnnHierarchyType.DENSE, dest='rnn_hierarchy_type')
    rnn_hierarchy_type_group.add_argument('--rnn-multiscale', action='store_const', const=md.RnnHierarchyType.MULTISCALE, dest='rnn_hierarchy_type')
    rnn_hierarchy_type_group.add_argument('--rnn-linear-model', action='store_const', const=md.RnnHierarchyType.LINEAR_MODEL, dest='rnn_hierarchy_type')
    rnn_hierarchy_type_group.add_argument('--rnn-mop', action='store_const', const=md.RnnHierarchyType.MOP_MODEL, dest='rnn_hierarchy_type')
    parser.set_defaults(rnn_hierarchy_type=md.RnnHierarchyType.MULTISCALE)

    parser.add_argument('--rnn-skip-connections', action='store_true', default=False)
    parser.add_argument('--rnn-learn-init', action='store_true', default=False)
    parser.add_argument('--rnn-connect-tokens', action='store_true', default=False)

    dag_nonlinearity_group = parser.add_mutually_exclusive_group()
    dag_nonlinearity_group.add_argument('--dag-relu-nonlinearity', action='store_const', const=md.NonlinearityType.RELU, dest='dag_nonlinearity')
    dag_nonlinearity_group.add_argument('--dag-tanh-nonlinearity', action='store_const', const=md.NonlinearityType.TANH, dest='dag_nonlinearity')
    dag_nonlinearity_group.add_argument('--dag-sigmoid-nonlinearity', action='store_const', const=md.NonlinearityType.SIGMOID, dest='dag_nonlinearity')
    parser.set_defaults(dag_nonlinearity=None)
    parser.add_argument('--dag-nonlinearity-width', help='The width of the final nonlinearity (default: 128)', default=128, type=int)
    parser.add_argument('--dag-nonlinear-before-max', action='store_true', default=False)

    data_dependency_group = parser.add_mutually_exclusive_group()
    data_dependency_group.add_argument('--linear-dependencies', action='store_true', default=False)
    data_dependency_group.add_argument('--flat-dependencies', action='store_true', default=False)

    dag_reduction_group = parser.add_mutually_exclusive_group()
    dag_reduction_group.add_argument('--dag-add-reduction', action='store_const', const=md.ReductionType.ADD, dest='dag_reduction')
    dag_reduction_group.add_argument('--dag-max-reduction', action='store_const', const=md.ReductionType.MAX, dest='dag_reduction')
    dag_reduction_group.add_argument('--dag-mean-reduction', action='store_const', const=md.ReductionType.MEAN, dest='dag_reduction')
    dag_reduction_group.add_argument('--dag-attention-reduction', action='store_const', const=md.ReductionType.ATTENTION, dest='dag_reduction')
    parser.set_defaults(dag_reduction=md.ReductionType.MAX)

    def add_edge_ablation(ablation):
        # type: (EdgeAblationType) -> None
        parser.add_argument('--{}'.format(ablation.value), action='append_const', dest='edge_ablations', const=ablation)

    add_edge_ablation(EdgeAblationType.TRANSITIVE_REDUCTION)
    add_edge_ablation(EdgeAblationType.TRANSITIVE_CLOSURE)
    add_edge_ablation(EdgeAblationType.ADD_LINEAR_EDGES)
    add_edge_ablation(EdgeAblationType.ONLY_LINEAR_EDGES)
    add_edge_ablation(EdgeAblationType.NO_EDGES)

    sp = parser.add_subparsers(dest='subparser')

    train = sp.add_parser('train', help='Train an ithemal model')
    train.add_argument('--experiment-name', required=True, help='Name of the experiment to run')
    train.add_argument('--experiment-time', required=True, help='Time the experiment was started at')
    train.add_argument('--load-file', help='Start by loading the provided model')

    train.add_argument('--batch-size', type=int, default=4, help='The batch size to use in train')
    train.add_argument('--epochs', type=int, default=3, help='Number of epochs to run for')
    train.add_argument('--trainers', type=int, default=4, help='Number of trainer processes to use')
    train.add_argument('--threads', type=int,  default=4, help='Total number of PyTorch threads to create per trainer')
    train.add_argument('--decay-trainers', action='store_true', default=False, help='Decay the number of trainers at the end of each epoch')
    train.add_argument('--weight-decay', type=float, default=0, help='Coefficient of weight decay (L2 regularization) on model')
    train.add_argument('--initial-lr', type=float, default=0.1, help='Initial learning rate')
    train.add_argument('--decay-lr', action='store_true', default=False, help='Decay the learning rate at the end of each epoch')
    train.add_argument('--momentum', type=float, default=0.9, help='Momentum parameter for SGD')
    train.add_argument('--nesterov', action='store_true', default=False, help='Use Nesterov momentum')
    train.add_argument('--weird-lr', action='store_true', default=False, help='Use unusual LR schedule')
    train.add_argument('--lr-decay-rate', default=1.2, help='LR division rate', type=float)

    split_group = train.add_mutually_exclusive_group()
    split_group.add_argument(
        '--split-dist', action='store_const', const=[0.5, 0.25, 0.125, .0625, .0625],
        help='Split data partitions between trainers via a distribution',
    )
    split_group.add_argument('--split-size', type=int, help='Partitions of a fixed size')

    optimizer_group = train.add_mutually_exclusive_group()
    optimizer_group.add_argument('--adam-private', action='store_const', const=tr.OptimizerType.ADAM_PRIVATE, dest='optimizer', help='Use Adam with private moments',
                                 default=tr.OptimizerType.ADAM_PRIVATE)
    optimizer_group.add_argument('--adam-shared', action='store_const', const=tr.OptimizerType.ADAM_SHARED, dest='optimizer', help='Use Adam with shared moments')
    optimizer_group.add_argument('--sgd', action='store_const', const=tr.OptimizerType.SGD, dest='optimizer', help='Use SGD')

    benchmark = sp.add_parser('benchmark', help='Benchmark train performance of an Ithemal setup')
    benchmark.add_argument('--n-examples', type=int, default=1000, help='Number of examples to use in benchmark')
    benchmark.add_argument('--trainers', type=int, default=4, help='Number of trainer processes to use')
    benchmark.add_argument('--threads', type=int,  default=4, help='Total number of PyTorch threads to create per trainer')
    benchmark.add_argument('--batch-size', type=int, default=4, help='The batch size to use in train')

    validate = sp.add_parser('validate', help='Get performance of a dataset')
    validate.add_argument('--load-file', help='File to load the model from')
    validate.add_argument('--iaca-only', help='Only report accuracy on IACA datapoints', action='store_true', default=False)

    dump = sp.add_parser('dump', help='Dump the dataset to a file')
    dump.add_argument('--dump-file', help='File to dump the model to', required=True)

    args = parser.parse_args()

    base_params = BaseParameters(
        data=args.data,
        embed_mode=args.embed_mode,
        embed_file=args.embed_file,
        random_edge_freq=args.random_edge_freq,
        predict_log=args.predict_log,
        no_residual=args.no_residual,
        no_dag_rnn=args.no_dag_rnn,
        dag_reduction=args.dag_reduction,
        edge_ablation_types=args.edge_ablations or [],
        embed_size=args.embed_size,
        hidden_size=args.hidden_size,
        linear_embeddings=args.linear_embeddings,
        use_rnn=args.use_rnn,
        rnn_type=args.rnn_type,
        rnn_hierarchy_type=args.rnn_hierarchy_type,
        rnn_connect_tokens=args.rnn_connect_tokens,
        rnn_skip_connections=args.rnn_skip_connections,
        rnn_learn_init=args.rnn_learn_init,
        no_mem=args.no_mem,
        linear_dependencies=args.linear_dependencies,
        flat_dependencies=args.flat_dependencies,
        dag_nonlinearity=args.dag_nonlinearity,
        dag_nonlinearity_width=args.dag_nonlinearity_width,
        dag_nonlinear_before_max=args.dag_nonlinear_before_max,
    )

    if args.subparser == 'train':
        if args.split_dist:
            split = args.split_dist
        else:
            split = args.split_size or 1000

        train_params = TrainParameters(
            experiment_name=args.experiment_name,
            experiment_time=args.experiment_time,
            load_file=args.load_file,
            batch_size=args.batch_size,
            trainers=args.trainers,
            threads=args.threads,
            decay_trainers=args.decay_trainers,
            weight_decay=args.weight_decay,
            initial_lr=args.initial_lr,
            decay_lr=args.decay_lr,
            epochs=args.epochs,
            split=split,
            optimizer=args.optimizer,
            momentum=args.momentum,
            nesterov=args.nesterov,
            weird_lr=args.weird_lr,
            lr_decay_rate=args.lr_decay_rate,
        )
        training.run_training_coordinator(base_params, train_params)

    elif args.subparser == 'validate':
        graph_model_validate(base_params, args.load_file, args.iaca_only)

    elif args.subparser == 'dump':
        graph_model_dump(base_params, args.dump_file)

    elif args.subparser == 'benchmark':
        benchmark_params = BenchmarkParameters(
            batch_size=args.batch_size,
            trainers=args.trainers,
            threads=args.threads,
            examples=args.n_examples,
        )
        graph_model_benchmark(base_params, benchmark_params)

    else:
        raise ValueError('Unknown mode "{}"'.format(args.subparser))

if __name__ == '__main__':
    main()


text:
<?php
return [
    'Activate' => 'Активировать',
    'Agents' => 'Агенты',
    'Deactivate' => 'Деактивировать',
    'Executing' => 'Исполнение',
    'Agents enabled on the hits' => 'Включено исполнение агентов на хитах',
    "Last Execution At" => "Дата последнего запуска",
    "Main" => "Основное",
    "Next Execution At" => "Дата и время следующего запуска",
    "Agent's Function" => "Функция агента",
    "Interval (sec)" => "Интервал (сек.)",
    "Periodic" => "Периодический",
    "Description" => "Описание",
    "Active" => "Активность",
    "Priority" => "Приоритет",
    "Find and download of files" => "Найти и загрузить из файлов",
    "Files with agents" => "Файлов с агентами",
    "Found agents" => "Найдено агентов",
    "Is Running" => "Запущен",
    "Agents have been updated successfully" => "Агенты успешно обновлены",
    "Attention! You use agents mechanism hits users. If possible, switch them on cron." => "Внимание! Вы используете механизм агентов на хитах пользователей. По-возможности переключите их на крон.",
    "In the project settings specified that you are using a mechanism on the crown agents. If the agents do not work, check the entry in the file cron" => "В настройках проекта указано что вы используете механизм агентов на кроне. Если агенты не работают, проверьте наличие запись в крон файле",
    "Running agents stopped" => "Запущенные агенты остановлены",
    "Stop running" => "Остановить запущенные",
];


text:
package com.codered.ared;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/** Texture is a support class for the QCAR samples applications.
 *
 *  Exposes functionality for loading a texture from the APK.
 *
 * */

public class Texture
{
    public int mWidth;      /// The width of the texture.
    public int mHeight;     /// The height of the texture.
    public int mChannels;   /// The number of channels.
    public boolean mSuccess;/// Whether the texture was succesfully loaded
    public byte[] mData;    /// The pixel data.

    /** Returns the raw data */
    public byte[] getData()
    {
        return mData;
    }

    /** Factory function to load a texture from the APK. */
    public static Texture loadTextureFromApk(String fileName,
                                                AssetManager assets)
    {
        InputStream inputStream = null;
        try
        {
            inputStream = assets.open(fileName, AssetManager.ACCESS_BUFFER);

            BufferedInputStream bufferedStream =
                new BufferedInputStream(inputStream);
            Bitmap bitMap = BitmapFactory.decodeStream(bufferedStream);

            int[] data = new int[bitMap.getWidth() * bitMap.getHeight()];
            bitMap.getPixels(data, 0, bitMap.getWidth(), 0, 0,
                                bitMap.getWidth(), bitMap.getHeight());

            // Convert:
            byte[] dataBytes = new byte[bitMap.getWidth() *
                                       bitMap.getHeight() * 4];
            for (int p = 0; p < bitMap.getWidth() * bitMap.getHeight(); ++p)
            {
                int colour = data[p];
                dataBytes[p * 4]        = (byte)(colour >>> 16);    // R
                dataBytes[p * 4 + 1]    = (byte)(colour >>> 8);     // G
                dataBytes[p * 4 + 2]    = (byte) colour;            // B
                dataBytes[p * 4 + 3]    = (byte)(colour >>> 24);    // A
            }

            Texture texture = new Texture();
            texture.mWidth      = bitMap.getWidth();
            texture.mHeight     = bitMap.getHeight();
            texture.mChannels   = 4;
            texture.mData       = dataBytes;
            texture.mSuccess    = true;

            return texture;
        }
        catch (IOException e)
        {
            DebugLog.LOGE("Failed to log texture '" + fileName + "' from " +
                "APK. Creating a blank texture");
            DebugLog.LOGI(e.getMessage());

            // Create a blank image
            Texture texture = new Texture();
            texture.mWidth      = 1;
            texture.mHeight     = 1;
            texture.mChannels   = 4;

            byte[] dataBytes = new byte[texture.mWidth *
                                        texture.mHeight * texture.mChannels];
            for (int p = 0; p < texture.mWidth * texture.mHeight; ++p)
            {
                dataBytes[p * 4]        = 0;    // R
                dataBytes[p * 4 + 1]    = 0;    // G
                dataBytes[p * 4 + 2]    = 0;    // B
                dataBytes[p * 4 + 3]    = 1;    // A
            }

            texture.mData       = dataBytes;
            texture.mSuccess    = false;

            return texture;
        }
    }
}


text:
using System.Collections.Generic;
using FirstOneTo.Commands;

namespace FirstOneTo.CommandValidation
{
    public class Validator : IValidator
    {
        public ValidationResult ValidateCreateExample(CreateExample createExample)
        {
            var errorMessages = new List<string>();
            if (createExample.AggregateId <= 0)
            {
                errorMessages.Add("No AggregateId was provided");
            }
            if (string.IsNullOrEmpty(createExample.Description))
            {
                errorMessages.Add("No Description was provided");
            }
            if (errorMessages.Count > 0)
            {
                return new ValidationResult(false, errorMessages);
            }
            return new ValidationResult(true, errorMessages);
        }

        public ValidationResult ValidateChangeExample(ChangeExample changeExample)
        {
            var errorMessages = new List<string>();
            if (changeExample.AggregateId <= 0)
            {
                errorMessages.Add("No AggregateId was provided");
            }
            if (string.IsNullOrEmpty(changeExample.Description))
            {
                errorMessages.Add("No Description was provided");
            }
            if (errorMessages.Count > 0)
            {
                return new ValidationResult(false, errorMessages);
            }
            return new ValidationResult(true, errorMessages);
        }

        public ValidationResult ValidateCreateUser(CreateUser createUser)
        {
            var errorMessages = new List<string>();
            if (createUser.AggregateId <= 0)
            {
                errorMessages.Add("No AggregateId was provided");
            }
            if (string.IsNullOrEmpty(createUser.UserName))
            {
                errorMessages.Add("No UserName was provided");
            }
            if (string.IsNullOrEmpty(createUser.Email))
            {
                errorMessages.Add("No UserName was Email");
            }
            if (string.IsNullOrEmpty(createUser.Password))
            {
                errorMessages.Add("No UserName was Password");
            }
            if (errorMessages.Count > 0)
            {
                return new ValidationResult(false, errorMessages);
            }
            return new ValidationResult(true, errorMessages);
        }
    }
}


text:
/*
 * @file	zephyr/alloc.c
 * @brief	Zephyr libmetal memory allocation handling.
 */

#include <metal/alloc.h>
#include <metal/compiler.h>

#if (CONFIG_HEAP_MEM_POOL_SIZE <= 0)

void* metal_weak metal_zephyr_allocate_memory(unsigned int size)
{
	(void)size;
	return NULL;
}

void metal_weak metal_zephyr_free_memory(void *ptr)
{
	(void)ptr;
}

#endif /* CONFIG_HEAP_MEM_POOL_SIZE */


text:
using browser_sync::DataTypeManager;
using browser_sync::DataTypeManagerMock;
using content::BrowserThread;
using testing::_;
using testing::AnyNumber;
using testing::DoAll;
using testing::InvokeArgument;
using testing::Mock;
using testing::Return;

// TODO(chron): Test not using cros_user flag and use signin_
class ProfileSyncServiceStartupTest : public testing::Test {
 public:
  ProfileSyncServiceStartupTest()
      : ui_thread_(BrowserThread::UI, &ui_loop_),
        db_thread_(BrowserThread::DB),
        file_thread_(BrowserThread::FILE),
        io_thread_(BrowserThread::IO),
        profile_(new TestingProfile) {}

  virtual ~ProfileSyncServiceStartupTest() {
  }

  virtual void SetUp() {
    file_thread_.Start();
    io_thread_.StartIOThread();
    profile_->CreateRequestContext();
    CreateSyncService();
    service_->AddObserver(&observer_);
    service_->set_synchronous_sync_configuration();
  }

  virtual void TearDown() {
    service_->RemoveObserver(&observer_);
    service_.reset();
    profile_.reset();

    // Pump messages posted by the sync core thread (which may end up
    // posting on the IO thread).
    ui_loop_.RunAllPending();
    io_thread_.Stop();
    file_thread_.Stop();
    ui_loop_.RunAllPending();
  }

 protected:
  // Overridden below by ProfileSyncServiceStartupCrosTest.
  virtual void CreateSyncService() {
    SigninManager* signin = static_cast<SigninManager*>(
      SigninManagerFactory::GetInstance()->SetTestingFactoryAndUse(
          profile_.get(), FakeSigninManager::Build));
    signin->SetAuthenticatedUsername("test_user");
    service_.reset(new TestProfileSyncService(
        new ProfileSyncComponentsFactoryMock(),
        profile_.get(),
        signin,
        ProfileSyncService::MANUAL_START,
        true,
        base::Closure()));
  }

  DataTypeManagerMock* SetUpDataTypeManager() {
    DataTypeManagerMock* data_type_manager = new DataTypeManagerMock();
    EXPECT_CALL(*factory_mock(), CreateDataTypeManager(_, _)).
        WillOnce(Return(data_type_manager));
    return data_type_manager;
  }

  ProfileSyncComponentsFactoryMock* factory_mock() {
   return static_cast<ProfileSyncComponentsFactoryMock*>(service_->factory());
  }

  MessageLoop ui_loop_;
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread db_thread_;
  content::TestBrowserThread file_thread_;
  content::TestBrowserThread io_thread_;
  scoped_ptr<TestingProfile> profile_;
  scoped_ptr<TestProfileSyncService> service_;
  ProfileSyncServiceObserverMock observer_;
};

class ProfileSyncServiceStartupCrosTest : public ProfileSyncServiceStartupTest {
 protected:
  virtual void CreateSyncService() {
    SigninManager* signin = SigninManagerFactory::GetForProfile(profile_.get());
    signin->SetAuthenticatedUsername("test_user");
    service_.reset(new TestProfileSyncService(
        new ProfileSyncComponentsFactoryMock(),
        profile_.get(),
        signin,
        ProfileSyncService::AUTO_START,
        true,
        base::Closure()));
  }
};

TEST_F(ProfileSyncServiceStartupTest, StartFirstTime) {
  DataTypeManagerMock* data_type_manager = SetUpDataTypeManager();
  EXPECT_CALL(*data_type_manager, Configure(_, _)).Times(0);

  // We've never completed startup.
  profile_->GetPrefs()->ClearPref(prefs::kSyncHasSetupCompleted);
  // Make sure SigninManager doesn't think we're signed in (undoes the call to
  // SetAuthenticatedUsername() in CreateSyncService()).
  SigninManagerFactory::GetForProfile(profile_.get())->SignOut();

  // Should not actually start, rather just clean things up and wait
  // to be enabled.
  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());
  service_->Initialize();

  // Preferences should be back to defaults.
  EXPECT_EQ(0, profile_->GetPrefs()->GetInt64(prefs::kSyncLastSyncedTime));
  EXPECT_FALSE(profile_->GetPrefs()->GetBoolean(prefs::kSyncHasSetupCompleted));
  Mock::VerifyAndClearExpectations(data_type_manager);

  // Then start things up.
  EXPECT_CALL(*data_type_manager, Configure(_, _)).Times(1);
  EXPECT_CALL(*data_type_manager, state()).
      WillOnce(Return(DataTypeManager::CONFIGURED)).
      WillOnce(Return(DataTypeManager::CONFIGURED));
  EXPECT_CALL(*data_type_manager, Stop()).Times(1);
  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());

  // Create some tokens in the token service; the service will startup when
  // it is notified that tokens are available.
  service_->SetSetupInProgress(true);
  service_->signin()->StartSignIn("test_user", "", "", "");
  TokenServiceFactory::GetForProfile(profile_.get())->IssueAuthTokenForTest(
      GaiaConstants::kSyncService, "sync_token");
  TokenServiceFactory::GetForProfile(profile_.get())->IssueAuthTokenForTest(
      GaiaConstants::kGaiaOAuth2LoginRefreshToken, "oauth2_login_token");
  service_->SetSetupInProgress(false);
  EXPECT_TRUE(service_->ShouldPushChanges());
}

TEST_F(ProfileSyncServiceStartupTest, StartNoCredentials) {
  DataTypeManagerMock* data_type_manager = SetUpDataTypeManager();
  EXPECT_CALL(*data_type_manager, Configure(_, _)).Times(0);

  // We've never completed startup.
  profile_->GetPrefs()->ClearPref(prefs::kSyncHasSetupCompleted);
  // Make sure SigninManager doesn't think we're signed in (undoes the call to
  // SetAuthenticatedUsername() in CreateSyncService()).
  SigninManagerFactory::GetForProfile(profile_.get())->SignOut();

  // Should not actually start, rather just clean things up and wait
  // to be enabled.
  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());
  service_->Initialize();
  EXPECT_FALSE(service_->GetBackendForTest());

  // Preferences should be back to defaults.
  EXPECT_EQ(0, profile_->GetPrefs()->GetInt64(prefs::kSyncLastSyncedTime));
  EXPECT_FALSE(profile_->GetPrefs()->GetBoolean(prefs::kSyncHasSetupCompleted));
  Mock::VerifyAndClearExpectations(data_type_manager);

  // Then start things up.
  EXPECT_CALL(*data_type_manager, Configure(_, _)).Times(1);
  EXPECT_CALL(*data_type_manager, state()).
      WillOnce(Return(DataTypeManager::CONFIGURED)).
      WillOnce(Return(DataTypeManager::CONFIGURED));
  EXPECT_CALL(*data_type_manager, Stop()).Times(1);
  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());

  service_->SetSetupInProgress(true);
  service_->signin()->StartSignIn("test_user", "", "", "");
  // NOTE: Unlike StartFirstTime, this test does not issue any auth tokens.
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_TOKEN_LOADING_FINISHED,
      content::Source<TokenService>(
          TokenServiceFactory::GetForProfile(profile_.get())),
      content::NotificationService::NoDetails());
  service_->SetSetupInProgress(false);
  // Backend should initialize using a bogus GAIA token for credentials.
  EXPECT_TRUE(service_->ShouldPushChanges());
}

TEST_F(ProfileSyncServiceStartupCrosTest, StartCrosNoCredentials) {
  EXPECT_CALL(*factory_mock(), CreateDataTypeManager(_, _)).Times(0);
  profile_->GetPrefs()->ClearPref(prefs::kSyncHasSetupCompleted);
  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());

  service_->Initialize();
  // Sync should not start because there are no tokens yet.
  EXPECT_FALSE(service_->ShouldPushChanges());
  EXPECT_FALSE(service_->GetBackendForTest());
  content::NotificationService::current()->Notify(
      chrome::NOTIFICATION_TOKEN_LOADING_FINISHED,
      content::Source<TokenService>(
          TokenServiceFactory::GetForProfile(profile_.get())),
      content::NotificationService::NoDetails());
  service_->SetSetupInProgress(false);
  // Sync should not start because there are still no tokens.
  EXPECT_FALSE(service_->ShouldPushChanges());
  EXPECT_FALSE(service_->GetBackendForTest());
}

TEST_F(ProfileSyncServiceStartupCrosTest, StartFirstTime) {
  DataTypeManagerMock* data_type_manager = SetUpDataTypeManager();
  profile_->GetPrefs()->ClearPref(prefs::kSyncHasSetupCompleted);
  EXPECT_CALL(*data_type_manager, Configure(_, _));
  EXPECT_CALL(*data_type_manager, state()).
      WillRepeatedly(Return(DataTypeManager::CONFIGURED));
  EXPECT_CALL(*data_type_manager, Stop()).Times(1);
  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());

  TokenServiceFactory::GetForProfile(profile_.get())->IssueAuthTokenForTest(
      GaiaConstants::kSyncService, "sync_token");
  service_->Initialize();
  EXPECT_TRUE(service_->ShouldPushChanges());
}

TEST_F(ProfileSyncServiceStartupTest, StartNormal) {
  DataTypeManagerMock* data_type_manager = SetUpDataTypeManager();
  EXPECT_CALL(*data_type_manager, Configure(_, _));
  EXPECT_CALL(*data_type_manager, state()).
      WillRepeatedly(Return(DataTypeManager::CONFIGURED));
  EXPECT_CALL(*data_type_manager, Stop()).Times(1);

  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());

  // Pre load the tokens
  TokenServiceFactory::GetForProfile(profile_.get())->IssueAuthTokenForTest(
      GaiaConstants::kSyncService, "sync_token");
  profile_->GetPrefs()->SetString(prefs::kGoogleServicesUsername, "test_user");
  service_->Initialize();
}

TEST_F(ProfileSyncServiceStartupTest, ManagedStartup) {
  // Disable sync through policy.
  profile_->GetPrefs()->SetBoolean(prefs::kSyncManaged, true);

  EXPECT_CALL(*factory_mock(), CreateDataTypeManager(_, _)).Times(0);
  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());

  // Service should not be started by Initialize() since it's managed.
  TokenServiceFactory::GetForProfile(profile_.get())->IssueAuthTokenForTest(
      GaiaConstants::kSyncService, "sync_token");
  profile_->GetPrefs()->SetString(prefs::kGoogleServicesUsername, "test_user");
  service_->Initialize();
}

TEST_F(ProfileSyncServiceStartupTest, SwitchManaged) {
  DataTypeManagerMock* data_type_manager = SetUpDataTypeManager();
  EXPECT_CALL(*data_type_manager, Configure(_, _));
  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());

  TokenServiceFactory::GetForProfile(profile_.get())->IssueAuthTokenForTest(
      GaiaConstants::kSyncService, "sync_token");
  profile_->GetPrefs()->SetString(prefs::kGoogleServicesUsername, "test_user");
  service_->Initialize();

  // The service should stop when switching to managed mode.
  Mock::VerifyAndClearExpectations(data_type_manager);
  EXPECT_CALL(*data_type_manager, state()).
      WillOnce(Return(DataTypeManager::CONFIGURED));
  EXPECT_CALL(*data_type_manager, Stop()).Times(1);
  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());
  profile_->GetPrefs()->SetBoolean(prefs::kSyncManaged, true);

  // When switching back to unmanaged, the state should change, but the service
  // should not start up automatically (kSyncSetupCompleted will be false).
  Mock::VerifyAndClearExpectations(data_type_manager);
  EXPECT_CALL(*factory_mock(), CreateDataTypeManager(_, _)).Times(0);
  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());
  profile_->GetPrefs()->ClearPref(prefs::kSyncManaged);
}

TEST_F(ProfileSyncServiceStartupTest, StartFailure) {
  DataTypeManagerMock* data_type_manager = SetUpDataTypeManager();
  DataTypeManager::ConfigureStatus status = DataTypeManager::ABORTED;
  syncer::SyncError error(
      FROM_HERE, "Association failed.", syncer::BOOKMARKS);
  std::list<syncer::SyncError> errors;
  errors.push_back(error);
  browser_sync::DataTypeManager::ConfigureResult result(
      status,
      syncer::ModelTypeSet(),
      errors,
      syncer::ModelTypeSet());
  EXPECT_CALL(*data_type_manager, Configure(_, _)).
      WillRepeatedly(
          DoAll(
              NotifyFromDataTypeManager(data_type_manager,
                  static_cast<int>(chrome::NOTIFICATION_SYNC_CONFIGURE_START)),
              NotifyFromDataTypeManagerWithResult(data_type_manager,
                  static_cast<int>(chrome::NOTIFICATION_SYNC_CONFIGURE_DONE),
                  &result)));
  EXPECT_CALL(*data_type_manager, state()).
      WillOnce(Return(DataTypeManager::STOPPED));

  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());

  TokenServiceFactory::GetForProfile(profile_.get())->IssueAuthTokenForTest(
      GaiaConstants::kSyncService, "sync_token");
  profile_->GetPrefs()->SetString(prefs::kGoogleServicesUsername, "test_user");
  service_->Initialize();
  EXPECT_TRUE(service_->HasUnrecoverableError());
}

TEST_F(ProfileSyncServiceStartupTest, StartDownloadFailed) {
  profile_->GetPrefs()->ClearPref(prefs::kSyncHasSetupCompleted);

  EXPECT_CALL(observer_, OnStateChanged()).Times(AnyNumber());

  // Preload the tokens.
  TokenServiceFactory::GetForProfile(profile_.get())->IssueAuthTokenForTest(
      GaiaConstants::kSyncService, "sync_token");
  service_->fail_initial_download();

  service_->Initialize();
  EXPECT_FALSE(service_->sync_initialized());
  EXPECT_FALSE(service_->GetBackendForTest());
}


text:
<!DOCTYPE HTML>

<title>uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds Class Hierarchy (material-tap-target-prompt 3.3.2 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

JavaScript is disabled on your browser.

Hierarchy For Package uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

uk.co.samuelwall.materialtaptargetprompt.extras.PromptBackground

uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds.CirclePromptBackground

uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds.FullscreenPromptBackground

uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds.ImmersiveModeCompatPromptBackground

uk.co.samuelwall.materialtaptargetprompt.extras.backgrounds.RectanglePromptBackground

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

All Classes

JavaScript is disabled on your browser.