text:
package com.evolveum.midpoint.model.common.mapping;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;

import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.schema.SchemaConstantsGenerated;
import com.evolveum.midpoint.schema.constants.ExpressionConstants;
import com.evolveum.midpoint.security.api.SecurityEnforcer;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.prism.xml.ns._public.types_3.ItemPathType;

import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Element;

import com.evolveum.midpoint.common.filter.Filter;
import com.evolveum.midpoint.common.filter.FilterManager;
import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition;
import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.repo.common.expression.Expression;
import com.evolveum.midpoint.repo.common.expression.ExpressionEvaluationContext;
import com.evolveum.midpoint.repo.common.expression.ExpressionFactory;
import com.evolveum.midpoint.repo.common.expression.ExpressionUtil;
import com.evolveum.midpoint.repo.common.expression.ExpressionVariables;
import com.evolveum.midpoint.repo.common.expression.ItemDeltaItem;
import com.evolveum.midpoint.repo.common.expression.ObjectDeltaObject;
import com.evolveum.midpoint.repo.common.expression.Source;
import com.evolveum.midpoint.repo.common.expression.StringPolicyResolver;
import com.evolveum.midpoint.repo.common.expression.ValueSetDefinition;
import com.evolveum.midpoint.schema.internals.InternalsConfig;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.util.SchemaDebugUtil;
import com.evolveum.midpoint.schema.util.ObjectResolver;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.MiscUtil;
import com.evolveum.midpoint.util.exception.ExpressionEvaluationException;
import com.evolveum.midpoint.util.exception.ObjectNotFoundException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.TunnelException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;

/**
 *
 * Mapping is non-recyclable single-use object. Once evaluated it should not be evaluated again. It will retain its original
 * inputs and outputs that can be read again and again. But these should not be changed after evaluation.
 *
 * Configuration properties are unmodifiable. They are to be set via Mapping.Builder.
 *
 * @author Radovan Semancik
 *
 */
public class Mapping<V extends PrismValue,D extends ItemDefinition> implements DebugDumpable, PrismValueDeltaSetTripleProducer<V, D> {

	// configuration properties (unmodifiable)
	private final MappingType mappingType;
	private final ExpressionFactory expressionFactory;
	private final ExpressionVariables variables;

	private final ObjectDeltaObject<?> sourceContext;
	private final Collection<Source<?,?>> sources;
	private final Source<?,?> defaultSource;

	private final PrismObjectDefinition<?> targetContext;
	private final ItemPath defaultTargetPath;
	private final D defaultTargetDefinition;
	private final Collection<V> originalTargetValues;

	private final ObjectResolver objectResolver;
    private final SecurityEnforcer securityEnforcer;          // in order to get c:actor variable
	private final OriginType originType;
	private final ObjectType originObject;
	private final FilterManager<Filter> filterManager;
	private final StringPolicyResolver stringPolicyResolver;
	private final boolean conditionMaskOld;
	private final boolean conditionMaskNew;
	private final XMLGregorianCalendar defaultReferenceTime;
	private final XMLGregorianCalendar now;
	private final boolean profiling;
	private final String contextDescription;

	private final QName mappingQName;						// This is sometimes used to identify the element that mapping produces
															// if it is different from itemName. E.g. this happens with associations.
	private final RefinedObjectClassDefinition refinedObjectClassDefinition;

	// working and output properties
	private D outputDefinition;
	private ItemPath outputPath;
	private MappingEvaluationState state = MappingEvaluationState.UNINITIALIZED;

	private PrismValueDeltaSetTriple<V> outputTriple;
	private PrismValueDeltaSetTriple<PrismPropertyValue<Boolean>> conditionOutputTriple;
	private Boolean timeConstraintValid = null;
	private XMLGregorianCalendar nextRecomputeTime = null;
	private Long evaluationStartTime = null;
	private Long evaluationEndTime = null;

	private String mappingContextDescription = null;

	// This is single-use only. Once evaluated it is not used any more
	// it is remembered only for tracing purposes.
	private Expression<V,D> expression;

	private static final Trace LOGGER = TraceManager.getTrace(Mapping.class);

	private Mapping(Builder<V,D> builder) {
		expressionFactory = builder.expressionFactory;
		variables = builder.variables;
		mappingType = builder.mappingType;
		objectResolver = builder.objectResolver;
		securityEnforcer = builder.securityEnforcer;
		defaultSource = builder.defaultSource;
		defaultTargetDefinition = builder.defaultTargetDefinition;
		defaultTargetPath = builder.defaultTargetPath;
		originalTargetValues = builder.originalTargetValues;
		sourceContext = builder.sourceContext;
		targetContext = builder.targetContext;
		sources = builder.sources;
		originType = builder.originType;
		originObject = builder.originObject;
		filterManager = builder.filterManager;
		stringPolicyResolver = builder.stringPolicyResolver;
		conditionMaskOld = builder.conditionMaskOld;
		conditionMaskNew = builder.conditionMaskNew;
		defaultReferenceTime = builder.defaultReferenceTime;
		profiling = builder.profiling;
		contextDescription = builder.contextDescription;
		mappingQName = builder.mappingQName;
		refinedObjectClassDefinition = builder.refinedObjectClassDefinition;
		now = builder.now;
	}

	public ObjectResolver getObjectResolver() {
		return objectResolver;
	}

	public QName getItemName() {
		if (outputDefinition != null) {
			return outputDefinition.getName();
		}
		return null;
	}

	public OriginType getOriginType() {
		return originType;
	}

	public ObjectType getOriginObject() {
		return originObject;
	}

	public Source<?,?> getDefaultSource() {
		return defaultSource;
	}

	public D getDefaultTargetDefinition() {
		return defaultTargetDefinition;
	}

	public ItemPath getDefaultTargetPath() {
		return defaultTargetPath;
	}

	public ObjectDeltaObject<?> getSourceContext() {
		return sourceContext;
	}

	public PrismObjectDefinition<?> getTargetContext() {
		return targetContext;
	}

	public String getContextDescription() {
		return contextDescription;
	}

	public String getMappingContextDescription() {
		if (mappingContextDescription == null) {
			StringBuilder sb = new StringBuilder("mapping ");
			if (mappingType.getName() != null) {
				sb.append("'").append(mappingType.getName()).append("' ");
			}
			sb.append("in ");
			sb.append(contextDescription);
			mappingContextDescription  = sb.toString();
		}
		return mappingContextDescription;
	}

	public MappingType getMappingType() {
		return mappingType;
	}

	@Override
	public boolean isSourceless() {
		return sources.isEmpty();
	}

	public MappingStrengthType getStrength() {
		return getStrength(mappingType);
	}

	public static MappingStrengthType getStrength(MappingType mappingType) {
		if (mappingType == null) {
			return MappingStrengthType.NORMAL;
		}
		MappingStrengthType value = mappingType.getStrength();
		if (value == null) {
			value = MappingStrengthType.NORMAL;
		}
		return value;
	}

	public boolean isAuthoritative() {
		if (mappingType == null) {
			return true;
		}
		Boolean value = mappingType.isAuthoritative();
		if (value == null) {
			value = true;
		}
		return value;
	}

	public boolean isExclusive() {
		if (mappingType == null) {
			return false;
		}
		Boolean value = mappingType.isExclusive();
		if (value == null) {
			value = false;
		}
		return value;
	}

	public Boolean isTolerant() {
		if (mappingType == null) {
			return null;
		}
		return mappingType.isTolerant();
	}

	public boolean isConditionMaskOld() {
		return conditionMaskOld;
	}

	public boolean isConditionMaskNew() {
		return conditionMaskNew;
	}

	private PrismContext getPrismContext() {
		return outputDefinition.getPrismContext();
	}

	public FilterManager<Filter> getFilterManager() {
		return filterManager;
	}

	public StringPolicyResolver getStringPolicyResolver() {
		return stringPolicyResolver;
	}

	public boolean isApplicableToChannel(String channelUri) {
		return isApplicableToChannel(mappingType, channelUri);
	}

	public static boolean isApplicableToChannel(MappingType mappingType, String channelUri) {
		List<String> exceptChannel = mappingType.getExceptChannel();
		if (exceptChannel != null &&  !exceptChannel.isEmpty()){
			return !exceptChannel.contains(channelUri);
		}
		List<String> applicableChannels = mappingType.getChannel();
		if (applicableChannels == null || applicableChannels.isEmpty()) {
			return true;
		}
		return applicableChannels.contains(channelUri);
	}

	public XMLGregorianCalendar getNow() {
		return now;
	}

	public XMLGregorianCalendar getDefaultReferenceTime() {
		return defaultReferenceTime;
	}

	public XMLGregorianCalendar getNextRecomputeTime() {
		return nextRecomputeTime;
	}

	public boolean isProfiling() {
		return profiling;
	}

	public Long getEvaluationStartTime() {
		return evaluationStartTime;
	}

	public Long getEvaluationEndTime() {
		return evaluationEndTime;
	}

	public Long getEtime() {
		if (evaluationStartTime == null || evaluationEndTime == null) {
			return null;
		}
		return evaluationEndTime - evaluationStartTime;
	}

	/* (non-Javadoc)
	 * @see com.evolveum.midpoint.model.common.mapping.PrismValueDeltaSetTripleProducer#getMappingQName()
	 */
	@Override
	public QName getMappingQName() {
		return mappingQName;
	}

	public RefinedObjectClassDefinition getRefinedObjectClassDefinition() {
		return refinedObjectClassDefinition;
	}

	// TODO: rename to evaluateAll
	public void evaluate(Task task, OperationResult parentResult) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
		prepare(task, parentResult);

//		if (!isActivated()) {
//			outputTriple = null;
//			LOGGER.debug("Skipping evaluation of mapping {} in {} because it is not activated",
//					mappingType.getName() == null?null:mappingType.getName(), contextDescription);
//			return;
//		}

		evaluateBody(task, parentResult);
	}

	/**
	 * Prepare mapping for evaluation.  Parse the values
	 * After this call it can checked if a mapping is activated
	 * (i.e. if the input changes will "trigger" the mapping).
	 */
	public void prepare(Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException {
			OperationResult result = parentResult.createMinorSubresult(Mapping.class.getName()+".prepare");
		assertState(MappingEvaluationState.UNINITIALIZED);
		try {

			parseSources(task, result);

			parseTarget();
			if (outputPath != null && outputDefinition == null) {
				throw new IllegalArgumentException("No output definition, cannot evaluate "+getMappingContextDescription());
			}

		} catch (ExpressionEvaluationException | ObjectNotFoundException | RuntimeException | SchemaException | Error e) {
			result.recordFatalError(e);
			throw e;
		}

		transitionState(MappingEvaluationState.PREPARED);
		result.recordSuccess();
	}

	public boolean isActivated() {
		// TODO
//		return isActivated;
		return sourcesChanged();
	}

	// TODO: rename to evaluate
	public void evaluateBody(Task task, OperationResult parentResult) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {

		assertState(MappingEvaluationState.PREPARED);

		OperationResult result = parentResult.createMinorSubresult(Mapping.class.getName()+".evaluate");

        traceEvaluationStart();

		try {

			// We may need to re-parse the sources here

			evaluateTimeConstraintValid(task, result);

			if (!timeConstraintValid) {
				outputTriple = null;
				result.recordNotApplicableIfUnknown();
				traceDeferred();
				return;
			}

			evaluateCondition(task, result);

			boolean conditionOutputOld = computeConditionResult(conditionOutputTriple.getNonPositiveValues());
			boolean conditionResultOld = conditionOutputOld && conditionMaskOld;

			boolean conditionOutputNew = computeConditionResult(conditionOutputTriple.getNonNegativeValues());
			boolean conditionResultNew = conditionOutputNew && conditionMaskNew;

			if (!conditionResultOld && !conditionResultNew) {
				outputTriple = null;
				transitionState(MappingEvaluationState.EVALUATED);
				result.recordNotApplicableIfUnknown();
				traceNotApplicable("condition is false");
				return;
			}

			// TODO: input filter
			evaluateExpression(task, result, conditionResultOld, conditionResultNew);
			fixDefinition();
			recomputeValues();
			setOrigin();
			// TODO: output filter

			checkRange(task, result);

			transitionState(MappingEvaluationState.EVALUATED);
			result.recordSuccess();
			traceSuccess(conditionResultOld, conditionResultNew);

		} catch (ExpressionEvaluationException | ObjectNotFoundException | RuntimeException | SchemaException | Error e) {
			result.recordFatalError(e);
			traceFailure(e);
			throw e;
		}
	}

	private void checkRange(Task task, OperationResult result)
			throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
		VariableBindingDefinitionType target = mappingType.getTarget();
		if (target != null && target.getSet() != null) {
			checkRangeTarget(task, result);
		}
		if (mappingType.getRange() != null) {
			checkRangeLegacy(task, result);
		}
	}

	private void checkRangeTarget(Task task, OperationResult result)
			throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
		if (originalTargetValues == null) {
			throw new IllegalStateException("Couldn't check range for mapping in " + contextDescription + ", as original target values are not known.");
		}
		ValueSetDefinitionType rangetSetDefType = mappingType.getTarget().getSet();
		QName name = outputPath.lastNamed().getName();
		ValueSetDefinition setDef = new ValueSetDefinition(rangetSetDefType, name, "range of "+name.getLocalPart()+" in "+getMappingContextDescription(), task, result);
		setDef.init(expressionFactory);
		for (V originalValue : originalTargetValues) {
			if (!setDef.contains(originalValue)) {
				continue;
			}
			addToMinusIfNecessary(originalValue);
		}
	}

	@SuppressWarnings("unchecked")
	private void addToMinusIfNecessary(V originalValue) {
		if (outputTriple != null && (outputTriple.presentInPlusSet(originalValue) || outputTriple.presentInZeroSet(originalValue))) {
			return;
		}
		// remove it!
		if (outputTriple == null) {
			outputTriple = new PrismValueDeltaSetTriple<>();
		}
		LOGGER.trace("Original value is in the mapping range (while not in mapping result), adding it to minus set: {}", originalValue);
		outputTriple.addToMinusSet((V)originalValue.clone());
	}

	private void checkRangeLegacy(Task task, OperationResult result)
			throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
		if (originalTargetValues == null) {
			throw new IllegalStateException("Couldn't check range for mapping in " + contextDescription + ", as original target values are not known.");
		}
		for (V originalValue : originalTargetValues) {
			if (!isInRange(originalValue, task, result)) {
				continue;
			}
			addToMinusIfNecessary(originalValue);
		}
	}

	private boolean isInRange(V value, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
		@NotNull ValueSetSpecificationType range = mappingType.getRange();
		if (range.getIsInSetExpression() == null) {
			return false;
		}
		ExpressionVariables variables = new ExpressionVariables();
		variables.addVariableDefinitions(this.variables);			// TODO is this ok?

		if (value instanceof PrismContainerValue) {
			// artifically create parent for PCV in order to pass it to expression
			PrismContainer.createParentIfNeeded((PrismContainerValue) value, outputDefinition);
		}
		variables.addVariableDefinition(ExpressionConstants.VAR_VALUE, value);

		PrismPropertyDefinition<Boolean> outputDef = new PrismPropertyDefinitionImpl<Boolean>(SchemaConstantsGenerated.C_VALUE, DOMUtil.XSD_BOOLEAN, getPrismContext(), null, false);
		PrismPropertyValue<Boolean> rv = ExpressionUtil.evaluateExpression(variables, outputDef, range.getIsInSetExpression(), expressionFactory, "isInSet expression in " + contextDescription, task, result);

		// but now remove the parent!
		if (value.getParent() != null) {
			value.setParent(null);
		}

		return rv != null && rv.getValue() != null ? rv.getValue() : Boolean.FALSE;
	}

	public boolean isSatisfyCondition() {
		boolean conditionOutputOld = computeConditionResult(conditionOutputTriple.getNonPositiveValues());
		boolean conditionResultOld = conditionOutputOld && conditionMaskOld;

		boolean conditionOutputNew = computeConditionResult(conditionOutputTriple.getNonNegativeValues());
		boolean conditionResultNew = conditionOutputNew && conditionMaskNew;
		return (conditionResultOld || conditionResultNew);
	}

	public PrismValueDeltaSetTriple<PrismPropertyValue<Boolean>> getConditionOutputTriple() {
		return conditionOutputTriple;
	}

	private void traceEvaluationStart() {
		if (profiling) {
			evaluationStartTime = System.currentTimeMillis();
		}
	}

	private void traceEvaluationEnd() {
		if (profiling) {
			evaluationEndTime = System.currentTimeMillis();
		}
	}

	private void traceSuccess(boolean conditionResultOld, boolean conditionResultNew) {
		traceEvaluationEnd();
		if (!isTrace()) {
			return;
		}
		StringBuilder sb = new StringBuilder();
		sb.append("Mapping trace:\n");
		appendTraceHeader(sb);
		sb.append("\nCondition: ").append(conditionResultOld).append(" -> ").append(conditionResultNew);
		if (nextRecomputeTime != null) {
			sb.append("\nNext recompute: ");
			sb.append(nextRecomputeTime);
		}
		sb.append("\nResult: ");
		if (outputTriple == null) {
			sb.append("null");
		} else {
			sb.append(outputTriple.toHumanReadableString());
		}
		if (profiling) {
			sb.append("\nEtime: ");
			sb.append(getEtime());
			sb.append(" ms");
		}
		appendTraceFooter(sb);
		trace(sb.toString());
	}

	private void traceDeferred() {
		traceEvaluationEnd();
		if (!isTrace()) {
			return;
		}
		StringBuilder sb = new StringBuilder();
		sb.append("Mapping trace:\n");
		appendTraceHeader(sb);
		sb.append("\nEvaluation DEFERRED to: ");
		if (nextRecomputeTime == null) {
			sb.append("null");
		} else {
			sb.append(nextRecomputeTime);
		}
		if (profiling) {
			sb.append("\nEtime: ");
			sb.append(getEtime());
			sb.append(" ms");
		}
		appendTraceFooter(sb);
		trace(sb.toString());
	}

	private void traceNotApplicable(String reason) {
		traceEvaluationEnd();
		if (!isTrace()) {
			return;
		}
		StringBuilder sb = new StringBuilder();
		sb.append("Mapping trace:\n");
		appendTraceHeader(sb);
		sb.append("\nEvaluation is NOT APPLICABLE because "+reason);
		if (profiling) {
			sb.append("\nEtime: ");
			sb.append(getEtime());
			sb.append(" ms");
		}
		appendTraceFooter(sb);
		trace(sb.toString());
	}

	private void traceFailure(Throwable e) {
		LOGGER.error("Error evaluating {}: {}", new Object[]{getMappingContextDescription(), e.getMessage(), e});
		traceEvaluationEnd();
		if (!isTrace()) {
			return;
		}
		StringBuilder sb = new StringBuilder();
		sb.append("Mapping FAILURE:\n");
		appendTraceHeader(sb);
		sb.append("\nERROR: ").append(e.getClass().getSimpleName()).append(": ").append(e.getMessage());
		if (profiling) {
			sb.append("\nEtime: ");
			sb.append(getEtime());
			sb.append(" ms");
		}
		appendTraceFooter(sb);
		trace(sb.toString());
	}

	private boolean isTrace() {
		return LOGGER.isTraceEnabled() || (mappingType != null && mappingType.isTrace() == Boolean.TRUE);
	}

	private void trace(String msg) {
		if (mappingType != null && mappingType.isTrace() == Boolean.TRUE) {
			LOGGER.info(msg);
		} else {
			LOGGER.trace(msg);
		}
	}

	private void appendTraceHeader(StringBuilder sb) {
		sb.append("---[ MAPPING ");
		if (mappingType.getName() != null) {
			sb.append("'").append(mappingType.getName()).append("' ");
		}
		sb.append(" in ");
		sb.append(contextDescription);
		sb.append("]---------------------------");
		MappingStrengthType strength = getStrength();
		if (strength != null) {
			sb.append("\nStregth: ").append(strength);
		}
		for (Source<?,?> source: sources) {
			sb.append("\nSource: ");
			sb.append(source.shortDebugDump());
		}
		sb.append("\nTarget: ").append(MiscUtil.toString(outputDefinition));
		sb.append("\nExpression: ");
		if (expression == null) {
			sb.append("null");
		} else {
			sb.append(expression.shortDebugDump());
		}
	}

	private void appendTraceFooter(StringBuilder sb) {
		sb.append("\n------------------------------------------------------");
	}

	private boolean computeConditionResult(Collection<PrismPropertyValue<Boolean>> booleanPropertyValues) {
		if (mappingType.getCondition() == null) {
			// If condition is not present at all consider it to be true
			return true;
		}
		return ExpressionUtil.computeConditionResult(booleanPropertyValues);
	}

	public Boolean evaluateTimeConstraintValid(Task task, OperationResult result) throws SchemaException, ObjectNotFoundException {
		if (timeConstraintValid == null) {
			parseTimeConstraints(task, result);
		}
		return timeConstraintValid;
	}

	private void parseTimeConstraints(Task task, OperationResult result) throws SchemaException, ObjectNotFoundException {
		MappingTimeDeclarationType timeFromType = mappingType.getTimeFrom();
		MappingTimeDeclarationType timeToType = mappingType.getTimeTo();
		if (timeFromType == null && timeToType == null) {
			timeConstraintValid = true;
			return;
		}

		XMLGregorianCalendar timeFrom = parseTime(timeFromType, task, result);
		if (timeFrom == null && timeFromType != null) {
			// Time is specified but there is no value for it.
			// This means that event that should start validity haven't happened yet
			// therefore the mapping is not yet valid.
			timeConstraintValid = false;
			return;
		}
		XMLGregorianCalendar timeTo = parseTime(timeToType, task, result);

		if (timeFrom != null && timeFrom.compare(now) == DatatypeConstants.GREATER) {
			// before timeFrom
			nextRecomputeTime = timeFrom;
			timeConstraintValid = false;
			return;
		}

		if (timeTo == null && timeToType != null) {
			// Time is specified but there is no value for it.
			// This means that event that should stop validity haven't happened yet
			// therefore the mapping is still valid.
			timeConstraintValid = true;
			return;
		}

		if (timeTo != null && timeTo.compare(now) == DatatypeConstants.GREATER) {
			// between timeFrom and timeTo (also no timeFrom and before timeTo)
			nextRecomputeTime = timeTo;
			timeConstraintValid = true;
			return;
		}

		if (timeTo == null) {
			// after timeFrom and no timeTo
			// no nextRecomputeTime set, there is nothing to recompute in the future
			timeConstraintValid = true;
			return;

		} else {
			// after timeTo
			// no nextRecomputeTime set, there is nothing to recompute in the future
			timeConstraintValid = false;
			return;
		}

	}

	private XMLGregorianCalendar parseTime(MappingTimeDeclarationType timeType, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException {
		if (timeType == null) {
			return null;
		}
		XMLGregorianCalendar time;
		VariableBindingDefinitionType referenceTimeType = timeType.getReferenceTime();
		if (referenceTimeType == null) {
			if (defaultReferenceTime == null) {
				throw new SchemaException("No reference time specified (and there is also no default) in time specification in "+getMappingContextDescription());
			} else {
				time = (XMLGregorianCalendar) defaultReferenceTime.clone();
			}
		} else {
			time = parseTimeSource(referenceTimeType, task, result);
			if (time == null) {
				// Reference time is specified but the value is not present.
				return null;
			}
			time = (XMLGregorianCalendar) time.clone();
		}
		Duration offset = timeType.getOffset();
		if (offset != null) {
			time.add(offset);
		}
		return time;
	}

	private XMLGregorianCalendar parseTimeSource(VariableBindingDefinitionType sourceType, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException {
		ItemPathType itemPathType = sourceType.getPath();
		if (itemPathType == null) {
			throw new SchemaException("No path in source definition in "+getMappingContextDescription());
		}
		ItemPath path = itemPathType.getItemPath();
		if (path.isEmpty()) {
			throw new SchemaException("Empty source path in "+getMappingContextDescription());
		}

		Object sourceObject = ExpressionUtil.resolvePath(path, variables, sourceContext, objectResolver, "reference time definition in "+getMappingContextDescription(), task, result);
		if (sourceObject == null) {
			return null;
		}
		PrismProperty<XMLGregorianCalendar> timeProperty;
		if (sourceObject instanceof ItemDeltaItem<?,?>) {
			timeProperty = (PrismProperty<XMLGregorianCalendar>) ((ItemDeltaItem<?,?>)sourceObject).getItemNew();
		} else if (sourceObject instanceof Item<?,?>) {
			timeProperty = (PrismProperty<XMLGregorianCalendar>) sourceObject;
		} else {
			throw new IllegalStateException("Unknown resolve result "+sourceObject);
		}
		if (timeProperty == null) {
			return null;
		}
		return timeProperty.getRealValue();
	}

	private Collection<Source<?,?>> parseSources(Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException {
		List<VariableBindingDefinitionType> sourceTypes = mappingType.getSource();
		if (defaultSource != null) {
			defaultSource.recompute();
			sources.add(defaultSource);
			defaultSource.recompute();
		}
		if (sourceTypes != null) {
			for (VariableBindingDefinitionType sourceType: sourceTypes) {
				Source<?,?> source = parseSource(sourceType, task, result);
				source.recompute();

				// Override existing sources (e.g. default source)
				Iterator<Source<?,?>> iterator = sources.iterator();
				while (iterator.hasNext()) {
					Source<?,?> next = iterator.next();
					if (next.getName().equals(source.getName())) {
						iterator.remove();
					}
				}

				sources.add(source);
			}
		}
		return sources;
	}

	private <IV extends PrismValue, ID extends ItemDefinition> Source<IV,ID> parseSource(VariableBindingDefinitionType sourceType, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException {
		ItemPathType itemPathType = sourceType.getPath();
		if (itemPathType == null) {
			throw new SchemaException("No path in source definition in "+getMappingContextDescription());
		}
		ItemPath path = itemPathType.getItemPath();
		if (path.isEmpty()) {
			throw new SchemaException("Empty source path in "+getMappingContextDescription());
		}
		QName name = sourceType.getName();
		if (name == null) {
			name = ItemPath.getName(path.last());
		}
		ItemPath resolvePath = path;
		Object sourceObject = ExpressionUtil.resolvePath(path, variables, sourceContext, objectResolver, "source definition in "+getMappingContextDescription(), task, result);
		Item<IV,ID> itemOld = null;
		ItemDelta<IV,ID> delta = null;
		Item<IV,ID> itemNew = null;
		ItemPath residualPath = null;
		Collection<? extends ItemDelta<?,?>> subItemDeltas = null;
		if (sourceObject != null) {
			if (sourceObject instanceof ItemDeltaItem<?,?>) {
				itemOld = ((ItemDeltaItem<IV,ID>)sourceObject).getItemOld();
				delta = ((ItemDeltaItem<IV,ID>)sourceObject).getDelta();
				itemNew = ((ItemDeltaItem<IV,ID>)sourceObject).getItemNew();
				residualPath = ((ItemDeltaItem<IV,ID>)sourceObject).getResidualPath();
				resolvePath = ((ItemDeltaItem<IV,ID>)sourceObject).getResolvePath();
				subItemDeltas = ((ItemDeltaItem<IV,ID>)sourceObject).getSubItemDeltas();
			} else if (sourceObject instanceof Item<?,?>) {
				itemOld = (Item<IV,ID>) sourceObject;
				itemNew = (Item<IV,ID>) sourceObject;
			} else {
				throw new IllegalStateException("Unknown resolve result "+sourceObject);
			}
		}

		// apply domain
		ValueSetDefinitionType domainSetType = sourceType.getSet();
		if (domainSetType != null) {
			ValueSetDefinition setDef = new ValueSetDefinition(domainSetType, name, "domain of "+name.getLocalPart()+" in "+getMappingContextDescription(), task, result);
			setDef.init(expressionFactory);
			try {

				if (itemOld != null) {
					itemOld = itemOld.clone();
					itemOld.filterValues(val -> setDef.containsTunnel(val));
				}

				if (itemNew != null) {
					itemNew = itemNew.clone();
					itemNew.filterValues(val -> setDef.containsTunnel(val));
				}

				if (delta != null) {
					delta = delta.clone();
					delta.filterValues(val -> setDef.containsTunnel(val));
				}

			} catch (TunnelException te) {
				Throwable cause = te.getCause();
				if (cause instanceof SchemaException) {
					throw (SchemaException)cause;
				} else if (cause instanceof ExpressionEvaluationException) {
					throw (ExpressionEvaluationException)cause;
				} else if (cause instanceof ObjectNotFoundException) {
					throw (ObjectNotFoundException)cause;
				}
			}
		}

		Source<IV,ID> source = new Source<>(itemOld, delta, itemNew, name);
		source.setResidualPath(residualPath);
		source.setResolvePath(resolvePath);
		source.setSubItemDeltas(subItemDeltas);
		return source;
	}

	private boolean sourcesChanged() {
		for (Source<?,?> source: sources) {
			if (source.getDelta() != null) {
				return true;
			}
		}
		return false;
	}

	private void parseTarget() throws SchemaException {
		VariableBindingDefinitionType targetType = mappingType.getTarget();
		if (targetType == null) {
			outputDefinition = defaultTargetDefinition;
			outputPath = defaultTargetPath;
		} else {
			ItemPathType itemPathType = targetType.getPath();
			if (itemPathType == null) {
				outputDefinition = defaultTargetDefinition;
				outputPath = defaultTargetPath;
			} else {
				ItemPath path = itemPathType.getItemPath();
				outputDefinition = ExpressionUtil.resolveDefinitionPath(path, variables, targetContext, "target definition in "+getMappingContextDescription());
				if (outputDefinition == null) {
					throw new SchemaException("No target item that would conform to the path "+path+" in "+getMappingContextDescription());
				}
				outputPath = path.stripVariableSegment();
			}
		}
		if (stringPolicyResolver != null) {
			stringPolicyResolver.setOutputDefinition(outputDefinition);
			stringPolicyResolver.setOutputPath(outputPath);
		}
	}

	public D getOutputDefinition() throws SchemaException {
		if (outputDefinition == null) {
			parseTarget();
		}
		return outputDefinition;
	}

	public ItemPath getOutputPath() throws SchemaException {
		if (outputDefinition == null) {
			parseTarget();
		}
		return outputPath;
	}

	/**
	 * Applies definition to the output if needed.
	 */
	private void fixDefinition() throws SchemaException {
		if (outputTriple == null) {
			return;
		}
		if (outputTriple.isRaw()) {
			outputTriple.applyDefinition(outputDefinition);
		}
	}

	private void recomputeValues() {
		if (outputTriple == null) {
			return;
		}
		Visitor visitor = new Visitor() {
			@Override
			public void visit(Visitable visitable) {
				if (visitable instanceof PrismValue) {
					((PrismValue)visitable).recompute(getPrismContext());
				}
			}
		};
		outputTriple.accept(visitor);
	}

	private void setOrigin() {
		if (outputTriple == null) {
			return;
		}
		if (originType != null) {
			outputTriple.setOriginType(originType);
		}
		if (originObject != null) {
			outputTriple.setOriginObject(originObject);
		}
	}

	private void evaluateCondition(Task task, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
		ExpressionType conditionExpressionType = mappingType.getCondition();
		if (conditionExpressionType == null) {
			// True -> True
			conditionOutputTriple = new PrismValueDeltaSetTriple<PrismPropertyValue<Boolean>>();
			conditionOutputTriple.addToZeroSet(new PrismPropertyValue<Boolean>(Boolean.TRUE));
			return;
		}
		Expression<PrismPropertyValue<Boolean>,PrismPropertyDefinition<Boolean>> expression =
				ExpressionUtil.createCondition(conditionExpressionType, expressionFactory,
				"condition in "+getMappingContextDescription(), task, result);
		ExpressionEvaluationContext context = new ExpressionEvaluationContext(sources, variables,
				"condition in "+getMappingContextDescription(), task, result);
		context.setStringPolicyResolver(stringPolicyResolver);
		context.setExpressionFactory(expressionFactory);
		context.setDefaultSource(defaultSource);
		context.setDefaultTargetContext(getTargetContext());
		context.setRefinedObjectClassDefinition(getRefinedObjectClassDefinition());
		context.setMappingQName(mappingQName);
		conditionOutputTriple = expression.evaluate(context);
	}

	private void evaluateExpression(Task task, OperationResult result, boolean conditionResultOld, boolean conditionResultNew) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
		ExpressionType expressionType = null;
		if (mappingType != null) {
			expressionType = mappingType.getExpression();
		}
		expression = expressionFactory.makeExpression(expressionType, outputDefinition,
				"expression in "+getMappingContextDescription(), task, result);
		ExpressionEvaluationContext context = new ExpressionEvaluationContext(sources, variables,
				"expression in "+getMappingContextDescription(), task, result);
		context.setDefaultSource(defaultSource);
		context.setSkipEvaluationMinus(!conditionResultOld);
		context.setSkipEvaluationPlus(!conditionResultNew);
		context.setStringPolicyResolver(stringPolicyResolver);
		context.setExpressionFactory(expressionFactory);
		context.setDefaultTargetContext(getTargetContext());
		context.setRefinedObjectClassDefinition(getRefinedObjectClassDefinition());
		context.setMappingQName(mappingQName);
		outputTriple = expression.evaluate(context);

		if (outputTriple == null) {

			if (conditionResultNew) {
				// We need to return empty triple instead of null.
				// The condition was true (or there was not condition at all)
				// so the mapping is applicable.
				// Returning null would mean that the mapping is not applicable
				// at all.
				outputTriple = new PrismValueDeltaSetTriple<>();
			}

		} else {

			// reflect condition change
			if (!conditionResultOld && conditionResultNew) {
				// Condition change false -> true
				outputTriple.addAllToPlusSet(outputTriple.getZeroSet());
				outputTriple.clearZeroSet();
				outputTriple.clearMinusSet();
			}
			if (conditionResultOld && !conditionResultNew) {
				// Condition change true -> false
				outputTriple.addAllToMinusSet(outputTriple.getZeroSet());
				outputTriple.clearZeroSet();
				outputTriple.clearPlusSet();
			}
		}
	}

	/* (non-Javadoc)
	 * @see com.evolveum.midpoint.model.common.mapping.PrismValueDeltaSetTripleProducer#getOutputTriple()
	 */
	@Override
	public PrismValueDeltaSetTriple<V> getOutputTriple() {
		if (outputTriple != null && InternalsConfig.consistencyChecks) {
			try {
				outputTriple.checkNoParent();
			} catch (IllegalStateException e) {
				throw new IllegalStateException(e.getMessage() + " in output triple in " + getContextDescription(), e);
			}
		}
		return outputTriple;
	}

	public Item<V,D> getOutput() throws SchemaException {
		if (outputTriple == null) {
			return null;
		}
		Item<V,D> output = outputDefinition.instantiate();
		output.addAll(PrismValue.cloneCollection(outputTriple.getNonNegativeValues()));
		return output;
	}

	public ItemDelta<V,D> createEmptyDelta(ItemPath path) {
		return outputDefinition.createEmptyDelta(path);
	}

	private <T> PrismPropertyValue<T> filterValue(PrismPropertyValue<T> propertyValue, List<ValueFilterType> filters) {
        PrismPropertyValue<T> filteredValue = propertyValue.clone();
        filteredValue.setOriginType(OriginType.INBOUND);

        if (filters == null || filters.isEmpty()) {
            return filteredValue;
        }

        for (ValueFilterType filter : filters) {
            Filter filterInstance = filterManager.getFilterInstance(filter.getType(), filter.getAny());
            filterInstance.apply(filteredValue);
        }

        return filteredValue;
    }

	private void transitionState(MappingEvaluationState newState) {
		state = newState;
	}

	private void assertState(MappingEvaluationState expecetdState) {
		if (state != expecetdState) {
			throw new IllegalArgumentException("Expected mapping state "+expecetdState+", but was "+state);
		}
	}

	/**
	 * Shallow clone. Only the output is cloned deeply.
	 */
	public PrismValueDeltaSetTripleProducer<V, D> clone() {
		Mapping<V, D> clone = new Builder<V, D>()
				.mappingType(mappingType)
				.contextDescription(contextDescription)
				.expressionFactory(expressionFactory)
				.securityEnforcer(securityEnforcer)
				.variables(variables)
				.conditionMaskNew(conditionMaskNew)
				.conditionMaskOld(conditionMaskOld)
				.defaultSource(defaultSource)
				.defaultTargetDefinition(defaultTargetDefinition)
				.objectResolver(objectResolver)
				.originObject(originObject)
				.originType(originType)
				.sourceContext(sourceContext)
				.sources(sources)
				.targetContext(targetContext)
				.build();

		clone.outputDefinition = outputDefinition;
		clone.outputPath = outputPath;

		if (this.outputTriple != null) {
			clone.outputTriple = this.outputTriple.clone();
		}
		if (this.conditionOutputTriple != null) {
			clone.conditionOutputTriple = this.conditionOutputTriple.clone();
		}
		return clone;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (conditionMaskNew ? 1231 : 1237);
		result = prime * result + (conditionMaskOld ? 1231 : 1237);
		result = prime * result + ((conditionOutputTriple == null) ? 0 : conditionOutputTriple.hashCode());
		result = prime * result + ((defaultSource == null) ? 0 : defaultSource.hashCode());
		result = prime * result
				+ ((defaultTargetDefinition == null) ? 0 : defaultTargetDefinition.hashCode());
		result = prime * result + ((expressionFactory == null) ? 0 : expressionFactory.hashCode());
		result = prime * result + ((mappingType == null) ? 0 : mappingType.hashCode());
		result = prime * result + ((objectResolver == null) ? 0 : objectResolver.hashCode());
		result = prime * result + ((originObject == null) ? 0 : originObject.hashCode());
		result = prime * result + ((originType == null) ? 0 : originType.hashCode());
		result = prime * result + ((outputDefinition == null) ? 0 : outputDefinition.hashCode());
		result = prime * result + ((outputTriple == null) ? 0 : outputTriple.hashCode());
		result = prime * result + ((contextDescription == null) ? 0 : contextDescription.hashCode());
		result = prime * result + ((sourceContext == null) ? 0 : sourceContext.hashCode());
		result = prime * result + ((sources == null) ? 0 : sources.hashCode());
		result = prime * result + ((targetContext == null) ? 0 : targetContext.hashCode());
		result = prime * result + ((variables == null) ? 0 : variables.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Mapping other = (Mapping) obj;
		if (conditionMaskNew != other.conditionMaskNew)
			return false;
		if (conditionMaskOld != other.conditionMaskOld)
			return false;
		if (conditionOutputTriple == null) {
			if (other.conditionOutputTriple != null)
				return false;
		} else if (!conditionOutputTriple.equals(other.conditionOutputTriple))
			return false;
		if (defaultSource == null) {
			if (other.defaultSource != null)
				return false;
		} else if (!defaultSource.equals(other.defaultSource))
			return false;
		if (defaultTargetDefinition == null) {
			if (other.defaultTargetDefinition != null)
				return false;
		} else if (!defaultTargetDefinition.equals(other.defaultTargetDefinition))
			return false;
		if (expressionFactory == null) {
			if (other.expressionFactory != null)
				return false;
		} else if (!expressionFactory.equals(other.expressionFactory))
			return false;
		if (mappingType == null) {
			if (other.mappingType != null)
				return false;
		} else if (!mappingType.equals(other.mappingType))
			return false;
		if (objectResolver == null) {
			if (other.objectResolver != null)
				return false;
		} else if (!objectResolver.equals(other.objectResolver))
			return false;
		if (originObject == null) {
			if (other.originObject != null)
				return false;
		} else if (!originObject.equals(other.originObject))
			return false;
		if (originType != other.originType)
			return false;
		if (outputDefinition == null) {
			if (other.outputDefinition != null)
				return false;
		} else if (!outputDefinition.equals(other.outputDefinition))
			return false;
		if (outputTriple == null) {
			if (other.outputTriple != null)
				return false;
		} else if (!outputTriple.equals(other.outputTriple))
			return false;
		if (contextDescription == null) {
			if (other.contextDescription != null)
				return false;
		} else if (!contextDescription.equals(other.contextDescription))
			return false;
		if (sourceContext == null) {
			if (other.sourceContext != null)
				return false;
		} else if (!sourceContext.equals(other.sourceContext))
			return false;
		if (sources == null) {
			if (other.sources != null)
				return false;
		} else if (!sources.equals(other.sources))
			return false;
		if (targetContext == null) {
			if (other.targetContext != null)
				return false;
		} else if (!targetContext.equals(other.targetContext))
			return false;
		if (variables == null) {
			if (other.variables != null)
				return false;
		} else if (!variables.equals(other.variables))
			return false;
		return true;
	}

	@Override
	public String debugDump() {
		return debugDump(0);
	}

	@Override
	public String debugDump(int indent) {
		StringBuilder sb = new StringBuilder();
		for (int i=0;i<indent;i++) {
			sb.append(INDENT_STRING);
		}
		sb.append(toString());
		return sb.toString();
	}

	@Override
	public String toString() {
		if (mappingType != null && mappingType.getName() != null) {
			return "M(" + mappingType.getName()+ ": "+ getMappingDisplayName() + " = " + outputTriple + toStringStrength() + ")";
		} else {
			return "M(" + getMappingDisplayName() + " = " + outputTriple + toStringStrength() + ")";
		}
	}

	private String getMappingDisplayName() {
		if (mappingQName != null) {
			return SchemaDebugUtil.prettyPrint(mappingQName);
		}
		if (outputDefinition == null) {
			return null;
		}
		return SchemaDebugUtil.prettyPrint(outputDefinition.getName());
	}

	private String toStringStrength() {
		switch (getStrength()) {
			case NORMAL: return "";
			case WEAK: return ", weak";
			case STRONG: return ", strong";
		}
		return null;
	}

	/**
	 * Builder is used to construct a configuration of Mapping object, which - after building - becomes
	 * immutable.
	 *
	 * In order to provide backward-compatibility with existing use of Mapping object, the builder has
	 * also traditional setter methods. Both setters and "builder-style" methods MODIFY existing Builder
	 * object (i.e. they do not create a new one).
	 *
	 * TODO decide on which style of setters to keep (setters vs builder-style).
	 */
	public static final class Builder<V extends PrismValue, D extends ItemDefinition> {
		private ExpressionFactory expressionFactory;
		private ExpressionVariables variables = new ExpressionVariables();
		private MappingType mappingType;
		private ObjectResolver objectResolver;
		private SecurityEnforcer securityEnforcer;
		private Source<?, ?> defaultSource;
		private D defaultTargetDefinition;
		private ItemPath defaultTargetPath;
		private Collection<V> originalTargetValues;
		private ObjectDeltaObject<?> sourceContext;
		private PrismObjectDefinition<?> targetContext;
		private Collection<Source<?, ?>> sources = new ArrayList<>();
		private OriginType originType;
		private ObjectType originObject;
		private FilterManager<Filter> filterManager;
		private StringPolicyResolver stringPolicyResolver;
		private boolean conditionMaskOld = true;
		private boolean conditionMaskNew = true;
		private XMLGregorianCalendar now;
		private XMLGregorianCalendar defaultReferenceTime;
		private boolean profiling;
		private String contextDescription;
		private QName mappingQName;
		private RefinedObjectClassDefinition refinedObjectClassDefinition;
		private PrismContext prismContext;

		public Builder<V,D> expressionFactory(ExpressionFactory val) {
			expressionFactory = val;
			return this;
		}

		public Builder<V,D> variables(ExpressionVariables val) {
			variables = val;
			return this;
		}

		public Builder<V,D> mappingType(MappingType val) {
			mappingType = val;
			return this;
		}

		public Builder<V,D> objectResolver(ObjectResolver val) {
			objectResolver = val;
			return this;
		}

		public Builder<V,D> securityEnforcer(SecurityEnforcer val) {
			securityEnforcer = val;
			return this;
		}

		public Builder<V,D> defaultSource(Source<?, ?> val) {
			defaultSource = val;
			return this;
		}

		public Builder<V,D> defaultTargetDefinition(D val) {
			defaultTargetDefinition = val;
			return this;
		}

		public Builder<V,D> defaultTargetPath(ItemPath val) {
			defaultTargetPath = val;
			return this;
		}

		public Builder<V,D> originalTargetValues(Collection<V> values) {
			originalTargetValues = values;
			return this;
		}

		public Builder<V,D> sourceContext(ObjectDeltaObject<?> val) {
			sourceContext = val;
			return this;
		}

		public Builder<V,D> targetContext(PrismObjectDefinition<?> val) {
			targetContext = val;
			return this;
		}

		public Builder<V,D> sources(Collection<Source<?, ?>> val) {
			sources = val;
			return this;
		}

		public Builder<V,D> originType(OriginType val) {
			originType = val;
			return this;
		}

		public Builder<V,D> originObject(ObjectType val) {
			originObject = val;
			return this;
		}

		public Builder<V,D> filterManager(FilterManager<Filter> val) {
			filterManager = val;
			return this;
		}

		public Builder<V,D> stringPolicyResolver(StringPolicyResolver val) {
			stringPolicyResolver = val;
			return this;
		}

		public Builder<V,D> conditionMaskOld(boolean val) {
			conditionMaskOld = val;
			return this;
		}

		public Builder<V,D> conditionMaskNew(boolean val) {
			conditionMaskNew = val;
			return this;
		}

		public Builder<V,D> now(XMLGregorianCalendar val) {
			now = val;
			return this;
		}

		public Builder<V,D> defaultReferenceTime(XMLGregorianCalendar val) {
			defaultReferenceTime = val;
			return this;
		}

		public Builder<V,D> profiling(boolean val) {
			profiling = val;
			return this;
		}

		public Builder<V,D> contextDescription(String val) {
			contextDescription = val;
			return this;
		}

		public Builder<V,D> mappingQName(QName val) {
			mappingQName = val;
			return this;
		}

		public Builder<V,D> refinedObjectClassDefinition(RefinedObjectClassDefinition val) {
			refinedObjectClassDefinition = val;
			return this;
		}

		public Builder<V,D> prismContext(PrismContext val) {
			prismContext = val;
			return this;
		}

		public Mapping<V,D> build() {
			return new Mapping<>(this);
		}

		public ExpressionFactory getExpressionFactory() {
			return expressionFactory;
		}

		public ExpressionVariables getVariables() {
			return variables;
		}

		public MappingType getMappingType() {
			return mappingType;
		}

		public ObjectResolver getObjectResolver() {
			return objectResolver;
		}

		public SecurityEnforcer getSecurityEnforcer() {
			return securityEnforcer;
		}

		public Source<?, ?> getDefaultSource() {
			return defaultSource;
		}

		public D getDefaultTargetDefinition() {
			return defaultTargetDefinition;
		}

		public ItemPath getDefaultTargetPath() {
			return defaultTargetPath;
		}

		public Collection<V> getOriginalTargetValues() {
			return originalTargetValues;
		}

		public ObjectDeltaObject<?> getSourceContext() {
			return sourceContext;
		}

		public PrismObjectDefinition<?> getTargetContext() {
			return targetContext;
		}

		public Collection<Source<?, ?>> getSources() {
			return sources;
		}

		public OriginType getOriginType() {
			return originType;
		}

		public ObjectType getOriginObject() {
			return originObject;
		}

		public FilterManager<Filter> getFilterManager() {
			return filterManager;
		}

		public StringPolicyResolver getStringPolicyResolver() {
			return stringPolicyResolver;
		}

		public boolean isConditionMaskOld() {
			return conditionMaskOld;
		}

		public boolean isConditionMaskNew() {
			return conditionMaskNew;
		}

		public XMLGregorianCalendar getNow() {
			return now;
		}

		public XMLGregorianCalendar getDefaultReferenceTime() {
			return defaultReferenceTime;
		}

		public boolean isProfiling() {
			return profiling;
		}

		public String getContextDescription() {
			return contextDescription;
		}

		public QName getMappingQName() {
			return mappingQName;
		}

		public RefinedObjectClassDefinition getRefinedObjectClassDefinition() {
			return refinedObjectClassDefinition;
		}

		public Builder<V, D> rootNode(ObjectReferenceType objectRef) {
			return addVariableDefinition(null,(Object)objectRef);
		}

		public Builder<V, D> rootNode(ObjectDeltaObject<?> odo) {
			return addVariableDefinition(null,(Object)odo);
		}

		public Builder<V, D> rootNode(ObjectType objectType) {
			return addVariableDefinition(null,(Object)objectType);
		}

		public Builder<V, D> rootNode(PrismObject<? extends ObjectType> mpObject) {
			return addVariableDefinition(null,(Object)mpObject);
		}

		@Deprecated
		public void setRootNode(ObjectReferenceType objectRef) {
			rootNode(objectRef);
		}

		@Deprecated
		public void setRootNode(ObjectDeltaObject<?> odo) {
			rootNode(odo);
		}

		@Deprecated
		public void setRootNode(ObjectType objectType) {
			rootNode(objectType);
		}

		@Deprecated
		public void setRootNode(PrismObject<? extends ObjectType> mpObject) {
			rootNode(mpObject);
		}

		public PrismContext getPrismContext() {
			return prismContext;
		}

		public Builder<V, D> addVariableDefinition(ExpressionVariableDefinitionType varDef) throws SchemaException {
			if (varDef.getObjectRef() != null) {
				ObjectReferenceType ref = varDef.getObjectRef();
				ref.setType(getPrismContext().getSchemaRegistry().qualifyTypeName(ref.getType()));
				return addVariableDefinition(varDef.getName(), ref);
			} else if (varDef.getValue() != null) {
				return addVariableDefinition(varDef.getName(),varDef.getValue());
			} else {
				LOGGER.warn("Empty definition of variable {} in {}, ignoring it", varDef.getName(), getContextDescription());
				return this;
			}
		}

		public Builder<V, D> addVariableDefinition(QName name, ObjectReferenceType objectRef) {
			return addVariableDefinition(name, (Object)objectRef);
		}

		public Builder<V, D> addVariableDefinition(QName name, ObjectType objectType) {
			return addVariableDefinition(name,(Object)objectType);
		}

		public Builder<V, D> addVariableDefinition(QName name, PrismObject<? extends ObjectType> midpointObject) {
			return addVariableDefinition(name,(Object)midpointObject);
		}

		public Builder<V, D> addVariableDefinition(QName name, String value) {
			return addVariableDefinition(name,(Object)value);
		}

		public Builder<V, D> addVariableDefinition(QName name, int value) {
			return addVariableDefinition(name,(Object)value);
		}

		public Builder<V, D> addVariableDefinition(QName name, Element value) {
			return addVariableDefinition(name,(Object)value);
		}

		public Builder<V, D> addVariableDefinition(QName name, PrismValue value) {
			return addVariableDefinition(name,(Object)value);
		}

		public Builder<V, D> addVariableDefinition(QName name, ObjectDeltaObject<?> value) {
			return addVariableDefinition(name,(Object)value);
		}

		public Builder<V, D> addVariableDefinitions(Map<QName, Object> extraVariables) {
			variables.addVariableDefinitions(extraVariables);
			return this;
		}

		public Builder<V, D> addVariableDefinition(QName name, Object value) {
			variables.addVariableDefinition(name, value);
			return this;
		}

		public boolean hasVariableDefinition(QName varName) {
			return variables.containsKey(varName);
		}

		public boolean isApplicableToChannel(String channel) {
			return Mapping.isApplicableToChannel(mappingType, channel);
		}

		public Builder<V, D> addSource(Source<?,?> source) {
			sources.add(source);
			return this;
		}

		// traditional setters are also here, to avoid massive changes to existing code

		@Deprecated
		public void setExpressionFactory(ExpressionFactory expressionFactory) {
			this.expressionFactory = expressionFactory;
		}

		@Deprecated
		public void setVariables(ExpressionVariables variables) {
			this.variables = variables;
		}

		@Deprecated
		public void setMappingType(MappingType mappingType) {
			this.mappingType = mappingType;
		}

		@Deprecated
		public void setObjectResolver(ObjectResolver objectResolver) {
			this.objectResolver = objectResolver;
		}

		@Deprecated
		public void setSecurityEnforcer(SecurityEnforcer securityEnforcer) {
			this.securityEnforcer = securityEnforcer;
		}

		@Deprecated
		public void setDefaultSource(Source<?, ?> defaultSource) {
			this.defaultSource = defaultSource;
		}

		@Deprecated
		public void setDefaultTargetDefinition(D defaultTargetDefinition) {
			this.defaultTargetDefinition = defaultTargetDefinition;
		}

		@Deprecated
		public void setDefaultTargetPath(ItemPath defaultTargetPath) {
			this.defaultTargetPath = defaultTargetPath;
		}

		@Deprecated
		public void setSourceContext(ObjectDeltaObject<?> sourceContext) {
			this.sourceContext = sourceContext;
		}

		@Deprecated
		public void setTargetContext(PrismObjectDefinition<?> targetContext) {
			this.targetContext = targetContext;
		}

		@Deprecated
		public void setSources(Collection<Source<?, ?>> sources) {
			this.sources = sources;
		}

		@Deprecated
		public void setOriginType(OriginType originType) {
			this.originType = originType;
		}

		@Deprecated
		public void setOriginObject(ObjectType originObject) {
			this.originObject = originObject;
		}

		@Deprecated
		public void setFilterManager(
				FilterManager<Filter> filterManager) {
			this.filterManager = filterManager;
		}

		@Deprecated
		public void setStringPolicyResolver(
				StringPolicyResolver stringPolicyResolver) {
			this.stringPolicyResolver = stringPolicyResolver;
		}

		@Deprecated
		public void setConditionMaskOld(boolean conditionMaskOld) {
			this.conditionMaskOld = conditionMaskOld;
		}

		@Deprecated
		public void setConditionMaskNew(boolean conditionMaskNew) {
			this.conditionMaskNew = conditionMaskNew;
		}

		@Deprecated
		public void setNow(XMLGregorianCalendar now) {
			this.now = now;
		}

		@Deprecated
		public void setDefaultReferenceTime(XMLGregorianCalendar defaultReferenceTime) {
			this.defaultReferenceTime = defaultReferenceTime;
		}

		@Deprecated
		public void setProfiling(boolean profiling) {
			this.profiling = profiling;
		}

		@Deprecated
		public void setContextDescription(String contextDescription) {
			this.contextDescription = contextDescription;
		}

		@Deprecated
		public void setMappingQName(QName mappingQName) {
			this.mappingQName = mappingQName;
		}

		@Deprecated
		public void setRefinedObjectClassDefinition(
				RefinedObjectClassDefinition refinedObjectClassDefinition) {
			this.refinedObjectClassDefinition = refinedObjectClassDefinition;
		}

		@Deprecated
		public void setPrismContext(PrismContext prismContext) {
			this.prismContext = prismContext;
		}

		public MappingStrengthType getStrength() {
			return Mapping.getStrength(mappingType);
		}
	}
}


text:
<?php

namespace MoySklad\Entities\Documents\Orders;

class CustomerOrder extends AbstractOrder  {
    public static $entityName = 'customerorder';
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace AutoFixture.Kernel
{
    /// <summary>
    /// Creates specimens by returning the first specimen created by its children.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "The main responsibility of this class isn't to be a 'collection' (which, by the way, it isn't - it's just an Iterator).")]
    public class CompositeSpecimenBuilder : ISpecimenBuilderNode
    {
        private readonly ISpecimenBuilder[] composedBuilders;

        /// <summary>
        /// Initializes a new instance of the <see cref="CompositeSpecimenBuilder"/> class with the
        /// supplied builders.
        /// </summary>
        /// <param name="builders">The child builders.</param>
        public CompositeSpecimenBuilder(IEnumerable<ISpecimenBuilder> builders)
            : this(builders.ToArray())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CompositeSpecimenBuilder"/> class with the
        /// supplied builders.
        /// </summary>
        /// <param name="builders">The child builders.</param>
        public CompositeSpecimenBuilder(params ISpecimenBuilder[] builders)
        {
            this.composedBuilders = builders ?? throw new ArgumentNullException(nameof(builders));
        }

        /// <summary>
        /// Gets the child builders.
        /// </summary>
        public IEnumerable<ISpecimenBuilder> Builders => this.composedBuilders;

        /// <summary>
        /// Creates a new specimen by delegating to <see cref="Builders"/>.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A container that can be used to create other specimens.</param>
        /// <returns>The first result created by <see cref="Builders"/>.</returns>
        public object Create(object request, ISpecimenContext context)
        {
            // This is performance-sensitive code when used repeatedly over many requests.
            // See discussion at https://github.com/AutoFixture/AutoFixture/pull/218
            for (int i = 0; i < this.composedBuilders.Length; i++)
            {
                var result = this.composedBuilders[i].Create(request, context);
                if (!(result is NoSpecimen)) return result;
            }

            return new NoSpecimen();
        }

        /// <summary>Composes the supplied builders.</summary>
        /// <param name="builders">The builders to compose.</param>
        /// <returns>
        /// A new <see cref="ISpecimenBuilderNode" /> instance containing
        /// <paramref name="builders" /> as child nodes.
        /// </returns>
        public virtual ISpecimenBuilderNode Compose(IEnumerable<ISpecimenBuilder> builders)
        {
            return new CompositeSpecimenBuilder(builders);
        }

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="IEnumerator{ISpecimenBuilder}" /> that can be used to
        /// iterate through the collection.
        /// </returns>
        public IEnumerator<ISpecimenBuilder> GetEnumerator()
        {
            return this.composedBuilders.AsEnumerable().GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="System.Collections.IEnumerator" /> object that can
        /// be used to iterate through the collection.
        /// </returns>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        internal static ISpecimenBuilder ComposeIfMultiple(IEnumerable<ISpecimenBuilder> builders)
        {
            // This code is called very frequently during graph mutation (e.g. customization).
            // It's optimized to not perform unnecessary allocations and do not enumerate builders more than once.
            // Code is written expecting that single builder is the most common case.
            // See more detail here: https://github.com/AutoFixture/AutoFixture/pull/793
            ISpecimenBuilder singleItem = null;
            List<ISpecimenBuilder> multipleItems = null;
            bool hasItems = false;

            using (var enumerator = builders.GetEnumerator())
            {
                if (enumerator.MoveNext())
                {
                    singleItem = enumerator.Current;
                    hasItems = true;

                    while (enumerator.MoveNext())
                    {
                        // We are here only if more than one item is present.
                        // When we create collection for multiple items, we add the already enumerated one as well.
                        if (multipleItems == null)
                        {
                            multipleItems = new List<ISpecimenBuilder> { singleItem };
                        }

                        multipleItems.Add(enumerator.Current);
                    }
                }
            }

            if (!hasItems)
            {
                // It's very rare case and it does't make sense to optimize it.
                return new CompositeSpecimenBuilder();
            }

            // Single item is present only, so we return it.
            if (multipleItems == null)
            {
                return singleItem;
            }

            return new CompositeSpecimenBuilder(multipleItems);
        }

        internal static ISpecimenBuilderNode UnwrapIfSingle(ISpecimenBuilderNode node)
        {
            var c = node as CompositeSpecimenBuilder;
            if (c == null)
                return node;
            var isSingle = c.composedBuilders.Length == 1;
            if (isSingle)
            {
                if (c.composedBuilders[0] is ISpecimenBuilderNode n)
                    return n;
            }
            return node;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?><data jsxid="jsxroot">
  <record group="object" include="master.xml"/>
  <record group="position" include="master.xml"/>

  <record group="1" jsxid="columnchart" jsxtext="ColumnChart">
    <record docdefault="clustered (jsx3.chart.BCChart.TYPE_CLUSTERED)" docgetter="getType" docsetter="setType" eval="0" jsxexecute="objJSX.setType(vntValue);objJSX.repaint();" jsxid="type" jsxmask="jsxselect" jsxtext="Type" jsxtip="Sets the type of column chart." nullable="0">
      <enum jsxid="jsx3.chart.BCChart.TYPE_CLUSTERED" jsxtext="clustered"/>
      <enum jsxid="jsx3.chart.BCChart.TYPE_STACKED" jsxtext="stacked"/>
      <enum jsxid="jsx3.chart.BCChart.TYPE_STACKED100" jsxtext="stacked 100%"/>
    </record>
    <record disallow="[^\.0-9\-]" docdefault="0" docgetter="getSeriesOverlap" docsetter="setSeriesOverlap" eval="1" jsxid="seriesOverlap" jsxmask="jsxtext" jsxtext="Column Overlap" jsxtip="Sets the amount of overlap between columns in the same category as a multiple of the column width."/>
    <record disallow="[^\.0-9]" docdefault="1" docgetter="setCategoryCoverage" docsetter="setCategoryCoverage" eval="1" jsxid="categoryCoverage" jsxmask="jsxtext" jsxtext="Column Coverage" jsxtip="Sets the fraction of the width of a category occupied by columns (0.0 - 1.0)."/>
  </record>

  <record group="blockx" include="master.xml"/>
  <record group="background" include="master.xml"/>
  <record group="chart" include="master.xml"/>
  <record group="interaction_menuonly" include="master.xml"/>
</data>


text:
namespace chromeos {

// Extension IME related utilities.
namespace extension_ime_util {

#if defined(GOOGLE_CHROME_BUILD)
const char kXkbExtensionId[] = "jkghodnilhceideoidjikpgommlajknk";
const char kM17nExtensionId[] = "gjaehgfemfahhmlgpdfknkhdnemmolop";
const char kHangulExtensionId[] = "bdgdidmhaijohebebipajioienkglgfo";
const char kMozcExtensionId[] = "gjaehgfemfahhmlgpdfknkhdnemmolop";
const char kT13nExtensionId[] = "gjaehgfemfahhmlgpdfknkhdnemmolop";
const char kChinesePinyinExtensionId[] = "gjaehgfemfahhmlgpdfknkhdnemmolop";
const char kChineseZhuyinExtensionId[] = "gjaehgfemfahhmlgpdfknkhdnemmolop";
const char kChineseCangjieExtensionId[] = "gjaehgfemfahhmlgpdfknkhdnemmolop";
#else
const char kXkbExtensionId[] = "fgoepimhcoialccpbmpnnblemnepkkao";
const char kM17nExtensionId[] = "jhffeifommiaekmbkkjlpmilogcfdohp";
const char kHangulExtensionId[] = "bdgdidmhaijohebebipajioienkglgfo";
const char kMozcExtensionId[] = "bbaiamgfapehflhememkfglaehiobjnk";
const char kT13nExtensionId[] = "gjaehgfemfahhmlgpdfknkhdnemmolop";
const char kChinesePinyinExtensionId[] = "cpgalbafkoofkjmaeonnfijgpfennjjn";
const char kChineseZhuyinExtensionId[] = "ekbifjdfhkmdeeajnolmgdlmkllopefi";
const char kChineseCangjieExtensionId[] = "aeebooiibjahgpgmhkeocbeekccfknbj";
#endif

// Returns InputMethodID for |engine_id| in |extension_id| of extension IME.
// This function does not check |extension_id| is installed extension IME nor
// |engine_id| is really a member of |extension_id|.
std::string UI_BASE_IME_EXPORT
GetInputMethodID(const std::string& extension_id, const std::string& engine_id);

// Returns InputMethodID for |engine_id| in |extension_id| of component
// extension IME, This function does not check |extension_id| is component one
// nor |engine_id| is really a member of |extension_id|.
std::string UI_BASE_IME_EXPORT
GetComponentInputMethodID(const std::string& extension_id,
                          const std::string& engine_id);

// Returns extension ID if |input_method_id| is extension IME ID or component
// extension IME ID. Otherwise returns an empty string ("").
std::string UI_BASE_IME_EXPORT
GetExtensionIDFromInputMethodID(const std::string& input_method_id);

// Returns InputMethodID from engine id (e.g. xkb:fr:fra), or returns itself if
// the |engine_id| is not a known engine id.
// The caller must make sure the |engine_id| is from system input methods
// instead of 3rd party input methods.
std::string UI_BASE_IME_EXPORT
GetInputMethodIDByEngineID(const std::string& engine_id);

// Returns true if |input_method_id| is extension IME ID. This function does not
// check |input_method_id| is installed extension IME.
bool UI_BASE_IME_EXPORT IsExtensionIME(const std::string& input_method_id);

// Returns true if |input_method_id| is component extension IME ID. This
// function does not check |input_method_id| is really whitelisted one or not.
// If you want to check |input_method_id| is whitelisted component extension
// IME, please use ComponentExtensionIMEManager::IsWhitelisted instead.
bool UI_BASE_IME_EXPORT
IsComponentExtensionIME(const std::string& input_method_id);

// Returns true if the |input_method| is a member of |extension_id| of extension
// IME, otherwise returns false.
bool UI_BASE_IME_EXPORT IsMemberOfExtension(const std::string& input_method_id,
                                            const std::string& extension_id);

// Returns true if the |input_method_id| is the extension based xkb keyboard,
// otherwise returns false.
bool UI_BASE_IME_EXPORT
IsKeyboardLayoutExtension(const std::string& input_method_id);

// Returns input method component id from the extension-based InputMethodID
// for component IME extensions. This function does not check that
// |input_method_id| is installed.
std::string UI_BASE_IME_EXPORT
GetComponentIDByInputMethodID(const std::string& input_method_id);

// Gets legacy xkb id (e.g. xkb:us::eng) from the new extension based xkb id
// (e.g. _comp_ime_...xkb:us::eng). If the given id is not prefixed with
// 'xkb:', just return the same as the given id.
std::string UI_BASE_IME_EXPORT
MaybeGetLegacyXkbId(const std::string& input_method_id);

}  // namespace extension_ime_util

}  // namespace chromeos

#endif  // UI_BASE_IME_CHROMEOS_EXTENSION_IME_UTIL_H_


text:
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/ActionBar.Mokojin.Regular</item>
        <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/ActionBar.Mokojin.Regular</item>
    </style>

    <style name="MainPageTheme" parent="AppTheme">
        <item name="android:actionBarStyle">@style/ActionBar.Mokojin.NoTitle</item>
        <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/ActionBar.Mokojin.NoTitle</item>
    </style>

    <style name="CharacterPageTheme" parent="AppTheme">
    </style>

    <!-- ActionBar styles -->
    <style name="ActionBar.Mokojin.Regular"
        parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">

        <item name="android:background">@color/primary</item>
        <item name="background">@color/primary</item>
    </style>

    <style name="ActionBar.Mokojin.NoTitle" parent="ActionBar.Mokojin.Regular">
        <item name="displayOptions">useLogo|showHome</item>
        <item name="logo">@mipmap/ic_launcher</item>
    </style>

    <style name="floatingActionButton">
        <item name="fab_plusIconColor">@color/white</item>
        <item name="fab_colorNormal">@color/primary</item>
        <item name="fab_colorPressed">@color/primary_pressed</item>
        <item name="fab_colorDisabled">@color/primary_disabled</item>
        <item name="android:layout_alignParentBottom">true</item>
        <item name="android:layout_alignParentRight">true</item>
        <item name="android:layout_marginRight">16dp</item>
        <item name="android:layout_marginBottom">16dp</item>
    </style>

    <style name="EditText.Mokojin" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorControlNormal">#D79C9C</item>
        <item name="colorControlActivated">#ffdfa4a4</item>
        <item name="colorControlHighlight">#fff4b2b2</item>
    </style>

    <style name="ProgressBar.Mokojin" parent="android:Widget.ProgressBar.Horizontal">
        <item name="android:indeterminateOnly">false</item>
        <item name="android:progressDrawable">@drawable/progress_chance_bar</item>
        <item name="android:minHeight">10dip</item>
        <item name="android:maxHeight">20dip</item>
    </style>

    <style name="clockText">
        <item name="android:textSize">@dimen/abc_text_size_caption_material</item>
        <item name="android:textColor">@android:color/secondary_text_light</item>
    </style>

</resources>


text:
package com.ggstudios.views;

import android.content.Context;
import android.graphics.Canvas;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;

public class VerticalTextView extends TextView{
	final boolean topDown;

	public VerticalTextView(Context context, AttributeSet attrs){
		super(context, attrs);
		final int gravity = getGravity();
		if(Gravity.isVertical(gravity) && (gravity&Gravity.VERTICAL_GRAVITY_MASK) == Gravity.BOTTOM) {
			setGravity((gravity&Gravity.HORIZONTAL_GRAVITY_MASK) | Gravity.TOP);
			topDown = false;
		}else
			topDown = true;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
		super.onMeasure(heightMeasureSpec, widthMeasureSpec);
		setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
	}

	@Override
	protected void onDraw(Canvas canvas){
		TextPaint textPaint = getPaint();
		textPaint.setColor(getCurrentTextColor());
		textPaint.drawableState = getDrawableState();

		canvas.save();

		if(topDown){
			canvas.translate(getWidth(), 0);
			canvas.rotate(90);
		}else {
			canvas.translate(0, getHeight());
			canvas.rotate(-90);
		}

		canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop());

		getLayout().draw(canvas);
		canvas.restore();
	}
}


text:
/*
 * This file was copied from Preact's source code,
 * so we're going to disable TS/lint/codecov:
 */
/* istanbul ignore file */
/* eslint-disable */
// @ts-nocheck
import {createElement} from '#preact';

// Copied from preact/compat/src/utils.js:
/**
 * Check if two objects have a different shape
 * @param {any} a
 * @param {any} b
 * @return {boolean}
 */
export function shallowDiffers(a, b) {
  for (const i in a) {
    if (i !== '__source' && !(i in b)) {
      return true;
    }
  }
  for (const i in b) {
    if (i !== '__source' && a[i] !== b[i]) {
      return true;
    }
  }
  return false;
}

// Copied from preact/compat/src/memo.js:
/**
 * Memoize a component, so that it only updates when the props actually have
 * changed. This was previously known as `React.pure`.
 * @param {import('../types').FC} c functional component
 * @param {(prev: object, next: object) => boolean} [comparer] Custom equality function
 * @return {import('../types').FC}
 */
export function memo(c, comparer) {
  function shouldUpdate(nextProps) {
    const {ref} = this.props;
    const updateRef = ref == nextProps.ref;
    if (!updateRef && ref) {
      ref.call ? ref(null) : (ref.current = null);
    }

    if (!comparer) {
      return shallowDiffers(this.props, nextProps);
    }

    return !comparer(this.props, nextProps) || !updateRef;
  }

  function Memoed(props) {
    this.shouldComponentUpdate = shouldUpdate;
    return createElement(c, props);
  }
  Memoed.displayName = 'Memo(' + (c.displayName || c.name) + ')';
  Memoed.prototype.isReactComponent = true;
  Memoed._forwarded = true;
  // @ts-ignore
  return Memoed;
}


text:
/*
2. Write a program that creates threads and increments a global variable n=0 with the values from a struct given as argument to each thread until it is greater than 20. The struct contains for each thread 2 random numbers generated in the main program.
*/

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <pthread.h>

#define T 10
#define maxrand 100
#define maxn 1000

int n;
pthread_mutex_t mtx;

struct pair {
    int first, second;
};

void* run(void *arg) {
    struct pair * act = (struct pair *) arg;
    printf("Thread has %d and %d. n = %d\n", act->first, act->second, n);
    while(n < maxn) {
        pthread_mutex_lock(&mtx);
        printf("Thread n = %d + %d\n", n, act->first);
        n += act->first;
        pthread_mutex_unlock(&mtx);
        if(n < maxn) {      /// so that once it is greater, then it is no need to increment again with the second generated random number
            pthread_mutex_lock(&mtx);
            printf("Thread n = %d + %d\n", n, act->second);
            n += act->second;
            pthread_mutex_unlock(&mtx);
        }
    }
    free(act);
    return NULL;
}

int main() {
    srand(time(NULL));

    int i;
    pthread_t t[T];
    pthread_mutex_init(&mtx, NULL);
    for(i = 0 ; i < T ; ++ i) {
        struct pair * act = (struct pair *)malloc(sizeof(struct pair));
        act->first = rand() % maxrand;
        act->second = rand() % maxrand;
        pthread_create(&t[i], NULL, run, (void *)act);
    }

    for(i = 0 ; i < T ; ++ i) {
        pthread_join(t[i], NULL);
    }
    printf("%d\n", n);
    pthread_mutex_destroy(&mtx);
    return 0;
}


text:
@interface MOBProjectionEPSG6120 : MOBProjection

@end


text:
@interface UITextLayer(Private)

- (id)containerView;

@end


text:
require_relative '../spec_helper'

module Aws
  module S3
    describe Client do

      let (:options) {{ stub_responses: true, region: 'us-west-2' }}

      let (:client) { Client.new(options) }

      let (:dualstack_client) { Client.new(options.merge(use_dualstack_endpoint: true)) }

      describe ':use_dualstack_endpoint' do

        it 'defaults to false' do
          client = Client.new(options)
          expect(client.config.use_dualstack_endpoint).to be(false)
          resp = client.put_object(bucket:'bucket-name', key:'key')
          expect(resp.context.http_request.endpoint.to_s).to eq(
            'https://bucket-name.s3.us-west-2.amazonaws.com/key')
        end

        it 'can be set in the constructor' do
          client = Client.new(options.merge(use_dualstack_endpoint: true))
          expect(client.config.use_dualstack_endpoint).to be(true)
          resp = client.put_object(bucket:'bucket-name', key:'key')
          expect(resp.context.http_request.endpoint.to_s).to eq(
            'https://bucket-name.s3.dualstack.us-west-2.amazonaws.com/key')
        end

        it 'can be set on the operation' do
          expect(client.config.use_dualstack_endpoint).to be(false)
          resp = client.put_object(bucket:'bucket-name', key:'key', use_dualstack_endpoint: true)
          expect(resp.context.http_request.endpoint.to_s).to eq(
            'https://bucket-name.s3.dualstack.us-west-2.amazonaws.com/key')
        end

        it 'can be disabled by the operation' do
          resp = dualstack_client.put_object(bucket:'bucket-name', key:'key', use_dualstack_endpoint: false)
          expect(resp.context.http_request.endpoint.to_s).to eq(
            'https://bucket-name.s3.us-west-2.amazonaws.com/key')
        end

        it 'works for global operations' do
          resp = dualstack_client.list_buckets
          expect(resp.context.http_request.endpoint.to_s).to eq(
            'https://s3.dualstack.us-west-2.amazonaws.com/'
          )
        end

        it 'works with HTTP endpoints' do
          client = Client.new(options.merge(use_dualstack_endpoint: true, endpoint: "http://s3.us-west-2.amazonaws.com"))
          resp = client.put_object(bucket: 'bucket-name', key: 'key')
          expect(resp.context.http_request.endpoint.to_s).to eq(
            'http://bucket-name.s3.dualstack.us-west-2.amazonaws.com/key'
          )
        end

        it 'works with DNS incompatible buckets' do
          resp = dualstack_client.put_object(bucket: 'bucket.name', key: 'key')
          expect(resp.context.http_request.endpoint.to_s).to eq(
            'https://s3.dualstack.us-west-2.amazonaws.com/bucket.name/key'
          )
        end

        it 'works with DNS incompatible buckets in HTTP scheme' do
          client = Client.new(options.merge(use_dualstack_endpoint: true, endpoint: "http://s3.us-west-2.amazonaws.com"))
          resp = client.put_object(bucket: 'bucket.name', key: 'key')
          expect(resp.context.http_request.endpoint.to_s).to eq(
            'http://bucket.name.s3.dualstack.us-west-2.amazonaws.com/key'
          )
        end

        it 'works with :force_path_style' do
          client = Client.new(options.merge(use_dualstack_endpoint: true, force_path_style: true))
          resp = client.put_object(bucket: 'bucket-name', key: 'key')
          expect(resp.context.http_request.endpoint.to_s).to eq(
            'https://s3.dualstack.us-west-2.amazonaws.com/bucket-name/key'
          )
        end

        it 'uses the correct endpoint pattern for us-east-1' do
          client = Client.new(stub_responses: true, region: "us-east-1", use_dualstack_endpoint: true)
          resp = client.put_object(bucket: 'bucket-name', key: 'key')
          expect(resp.context.http_request.endpoint.to_s).to eq(
            'https://bucket-name.s3.dualstack.us-east-1.amazonaws.com/key'
          )
        end

        it 'works for different dns suffixes' do
          client = Client.new(stub_responses: true, region: "cn-north-1", use_dualstack_endpoint: true)
          resp = client.put_object(bucket: 'bucket-name', key: 'key')
          expect(resp.context.http_request.endpoint.to_s).to eq(
            'https://bucket-name.s3.dualstack.cn-north-1.amazonaws.com.cn/key'
          )
        end
      end

    end
  end
end


text:
<?php
/**
 * Blocks API: WP_Block_Styles_Registry class
 *
 * @package WordPress
 * @subpackage Blocks
 * @since 5.3.0
 */

/**
 * Class used for interacting with block styles.
 *
 * @since 5.3.0
 */
final class WP_Block_Styles_Registry {
	/**
	 * Registered block styles, as `$block_name => $block_style_name => $block_style_properties` multidimensional arrays.
	 *
	 * @since 5.3.0
	 * @var array
	 */
	private $registered_block_styles = array();

	/**
	 * Container for the main instance of the class.
	 *
	 * @since 5.3.0
	 * @var WP_Block_Styles_Registry|null
	 */
	private static $instance = null;

	/**
	 * Registers a block style.
	 *
	 * @since 5.3.0
	 *
	 * @param string $block_name       Block type name including namespace.
	 * @param array  $style_properties Array containing the properties of the style name, label,
	 *                                 style (name of the stylesheet to be enqueued),
	 *                                 inline_style (string containing the CSS to be added).
	 * @return bool True if the block style was registered with success and false otherwise.
	 */
	public function register( $block_name, $style_properties ) {

		if ( ! isset( $block_name ) || ! is_string( $block_name ) ) {
			$message = __( 'Block name must be a string.' );
			_doing_it_wrong( __METHOD__, $message, '5.3.0' );
			return false;
		}

		if ( ! isset( $style_properties['name'] ) || ! is_string( $style_properties['name'] ) ) {
			$message = __( 'Block style name must be a string.' );
			_doing_it_wrong( __METHOD__, $message, '5.3.0' );
			return false;
		}

		$block_style_name = $style_properties['name'];

		if ( ! isset( $this->registered_block_styles[ $block_name ] ) ) {
			$this->registered_block_styles[ $block_name ] = array();
		}
		$this->registered_block_styles[ $block_name ][ $block_style_name ] = $style_properties;

		return true;
	}

	/**
	 * Unregisters a block style.
	 *
	 * @param string $block_name       Block type name including namespace.
	 * @param string $block_style_name Block style name.
	 * @return bool True if the block style was unregistered with success and false otherwise.
	 */
	public function unregister( $block_name, $block_style_name ) {
		if ( ! $this->is_registered( $block_name, $block_style_name ) ) {
			/* translators: 1: Block name, 2: Block style name. */
			$message = sprintf( __( 'Block "%1$s" does not contain a style named "%2$s".' ), $block_name, $block_style_name );
			_doing_it_wrong( __METHOD__, $message, '5.3.0' );
			return false;
		}

		unset( $this->registered_block_styles[ $block_name ][ $block_style_name ] );

		return true;
	}

	/**
	 * Retrieves an array containing the properties of a registered block style.
	 *
	 * @since 5.3.0
	 *
	 * @param string $block_name       Block type name including namespace.
	 * @param string $block_style_name Block style name.
	 * @return array Registered block style properties.
	 */
	public function get_registered( $block_name, $block_style_name ) {
		if ( ! $this->is_registered( $block_name, $block_style_name ) ) {
			return null;
		}

		return $this->registered_block_styles[ $block_name ][ $block_style_name ];
	}

	/**
	 * Retrieves all registered block styles.
	 *
	 * @since 5.3.0
	 *
	 * @return array Array of arrays containing the registered block styles properties grouped per block,
	 *               and per style.
	 */
	public function get_all_registered() {
		return $this->registered_block_styles;
	}

	/**
	 * Retrieves registered block styles for a specific block.
	 *
	 * @since 5.3.0
	 *
	 * @param string $block_name Block type name including namespace.
	 * @return array Array whose keys are block style names and whose value are block style properties.
	 */
	public function get_registered_styles_for_block( $block_name ) {
		if ( isset( $this->registered_block_styles[ $block_name ] ) ) {
			return $this->registered_block_styles[ $block_name ];
		}
		return array();
	}

	/**
	 * Checks if a block style is registered.
	 *
	 * @since 5.3.0
	 *
	 * @param string $block_name       Block type name including namespace.
	 * @param string $block_style_name Block style name.
	 * @return bool True if the block style is registered, false otherwise.
	 */
	public function is_registered( $block_name, $block_style_name ) {
		return isset( $this->registered_block_styles[ $block_name ][ $block_style_name ] );
	}

	/**
	 * Utility method to retrieve the main instance of the class.
	 *
	 * The instance will be created if it does not exist yet.
	 *
	 * @since 5.3.0
	 *
	 * @return WP_Block_Styles_Registry The main instance.
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}
}


text:
package org.radargun.stages;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.radargun.DistStageAck;
import org.radargun.config.Property;
import org.radargun.config.Stage;
import org.radargun.utils.Utils;

/**
 * @author Radim Vansa <rvansa@redhat.com>
 */
@Stage(internal = true, doc = "DO NOT USE DIRECTLY. This stage is automatically inserted before the beginning of scenario.")
public final class ScenarioInitStage extends AbstractDistStage {
   static final String INITIAL_FREE_MEMORY = "INITIAL_FREE_MEMORY";
   static final String INITIAL_THREADS = "INITIAL_THREADS";

   @Property(doc = "Directory where the heap dump will be produced. Contrary to scenario-cleanup, " +
         "if this directory is set, the heap dump is written always. By default the dump will not be produced.")
   private String heapDumpDir;

   @Override
   public DistStageAck executeOnSlave() {
      Thread.currentThread().setContextClassLoader(slaveState.getClassLoader());

      System.gc();
      Runtime runtime = Runtime.getRuntime();
      slaveState.putPersistent(INITIAL_FREE_MEMORY, runtime.freeMemory() + runtime.maxMemory() - runtime.totalMemory());

      Thread[] activeThreads = new Thread[Thread.activeCount() * 2];
      int activeThreadCount = Thread.enumerate(activeThreads);
      Set<Thread> threads = new HashSet<>(activeThreadCount);
      for (int i = 0; i < activeThreadCount; ++i) threads.add(activeThreads[i]);
      slaveState.putPersistent(INITIAL_THREADS, threads);

      if (heapDumpDir != null) {
         try {
            File heapDumpFile = new File(heapDumpDir, slaveState.getConfigName() + "." + slaveState.getSlaveIndex()
                  + "." + new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()) + ".bin");
            log.info("Dumping heap into " + heapDumpFile.getAbsolutePath());
            Utils.dumpHeap(heapDumpFile.getAbsolutePath());
            log.info("Successfully written heap dump.");
         } catch (Exception e) {
            log.error("Cannot write heap dump!", e);
         }
      }

      return successfulResponse();
   }
}


text:
// Copyright 2009 Jeffrey Cameron
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Concordion.Api;
using Concordion.Internal.Util;

namespace Concordion.Internal.Commands
{
    public class SetCommand : ICommand
    {
        #region ICommand Members

        public void Setup(CommandCall commandCall, IEvaluator evaluator, IResultRecorder resultRecorder)
        {
            Check.IsFalse(commandCall.HasChildCommands, "Nesting commands inside a 'set' is not supported");
            evaluator.SetVariable(commandCall.Expression, commandCall.Element.Text);
        }

        public void Execute(CommandCall commandCall, IEvaluator evaluator, IResultRecorder resultRecorder)
        {
        }

        public void Verify(CommandCall commandCall, IEvaluator evaluator, IResultRecorder resultRecorder)
        {
        }

        #endregion
    }
}


text:
package org.jkiss.dbeaver.model.data.aggregate;

/**
 * FunctionCount
 */
public class FunctionCount implements IAggregateFunction {

    private int count = 0;

    @Override
    public boolean accumulate(Object value, boolean aggregateAsStrings) {
        count++;
        return true;
    }

    @Override
    public Object getResult(int valueCount) {
        return count;
    }
}


text:
var angular = require("./index") || window.angular;
require("./lib/angular-cookies.min");
module.exports = angular.module('ngCookies');


text:
import gm = require('gm');
import stream = require('stream');

declare const src: string;
declare const matrix: string;
declare const enable: boolean;
declare const ltr: boolean;
declare const password: string;
declare const bits: number;
declare const intensity: number;
declare const r: number;
declare const g: number;
declare const b: number;
declare const opacity: number;
declare const x: number;
declare const y: number;
declare const radius: number;
declare const sigma: number;
declare const width: number;
declare const height: number;
declare const color: string;
declare const channel: gm.ChannelType;
declare const type: string;
declare const factor: number;
declare const numColors: number;
declare const operator: string;
declare const multiplier: number;
declare const kernel: string;
declare const usePercent: boolean;
declare const time: number;
declare const server: string;
declare const method: string;
declare const percent: number;
declare const encoding: string;
declare const options: gm.ResizeOption;
declare const file: string;
declare const distance: number;
declare const geometry: string;
declare const direction: string;
declare const name: string;
declare const offset: number;
declare const blackPoint: number;
declare const gamma: number;
declare const whitePoint: number;
declare const limit: string;
declare const format: string;
declare const iterations: number;
declare const count: number;
declare const s: number;
declare const h: number;
declare const dest: string;
declare const images: string[];
declare const angle: number;
declare const NxN: string;
declare const size: number;
declare const command: string;
declare const index: number;
declare const threshold: number;
declare const attribute: string;
declare const attrValue: string;
declare const font: string;
declare const quality: number;
declare const align: string;
declare const depth: number;
declare const defineValue: string;
declare const customCommand: string;
declare const customInArguments: string[];
declare const customOutArguments: string[];
let readStream: stream.PassThrough;

gm(src)
	.adjoin()
	.affine(matrix)
	.antialias(enable)
	.append(src)
	.append(src, ltr)
	.authenticate(password)
	.autoOrient()
	.backdrop()
	.background(color)
	.bitdepth(bits)
	.blackThreshold(intensity)
	.blackThreshold(r, g, b)
	.blackThreshold(r, g, b, opacity)
	.bluePrimary(x, y)
	.blur(radius)
	.blur(radius, sigma)
	.border(width, height)
	.borderColor(color)
	.box(color)
	.channel(channel)
	.charcoal(factor)
	.chop(width, height)
	.chop(width, height, x, y)
	.clip()
	.coalesce()
	.colorize(r, g, b)
	.colorMap(type)
	.colors(numColors)
	.colorspace(type)
	.command(customCommand)
	.compose(operator)
	.compress(type)
	.contrast(multiplier)
	.convolve(kernel)
	.createDirectories()
	.crop(width, height)
	.crop(width, height, x, y)
	.crop(width, height, x, y, usePercent)
	.cycle(factor)
	.deconstruct()
	.define(defineValue)
	.delay(time)
	.density(width, height)
	.despeckle()
	.displace(x, y)
	.display(server)
	.dispose(method)
	.dissolve(percent)
	.dither()
	.dither(enable)
	.edge()
	.edge(radius)
	.emboss()
	.emboss(radius)
	.encoding(encoding)
	.endian(type)
	.enhance()
	.equalize()
	.extent(width, height)
	.extent(width, height, options)
	.file(file)
	.filter(type)
	.flatten()
	.flip()
	.flop()
	.foreground(color)
	.frame(width, height, width, height)
	.fuzz(distance)
	.fuzz(distance, usePercent)
	.gamma(r, b, g)
	.gaussian(radius)
	.gaussian(radius, sigma)
	.geometry(width, height)
	.geometry(width, height, options)
	.geometry(geometry)
	.greenPrimary(x, y)
	.gravity(direction)
	.highlightColor(color)
	.highlightStyle(type)
	.iconGeometry(geometry)
	.implode()
	.implode(factor)
	.in(...customInArguments)
	.intent(type)
	.interlace(type)
	.label(name)
	.lat(width, height, offset)
	.lat(width, height, offset, usePercent)
	.level(blackPoint, gamma, whitePoint)
	.level(blackPoint, gamma, whitePoint, usePercent)
	.limit(type, limit)
	.list(type)
	.log(format)
	.loop(iterations)
	.lower(width, height)
	.magnify(factor)
	.map(file)
	.mask(file)
	.matte()
	.matteColor(color)
	.maximumError(count)
	.median()
	.median(radius)
	.minify(factor)
	.mode(type)
	.modulate(b, s, h)
	.monitor()
	.monochrome()
	.morph(src, dest)
	.morph(src, dest, (err, stdout, stderr, cmd) => {
	})
	.morph(images, dest)
	.morph(images, dest, (err, stdout, stderr, cmd) => {
	})
	.mosaic()
	.motionBlur(radius)
	.motionBlur(radius, sigma)
	.motionBlur(radius, sigma, angle)
	.name()
	.negative()
	.noise(type)
	.noise(radius)
	.noop()
	.normalize()
	.opaque(color)
	.operator(channel, operator, factor)
	.operator(channel, operator, factor, usePercent)
	.orderedDither(channel, NxN)
	.out(...customOutArguments)
	.outputDirectory(dest)
	.page(width, height)
	.page(width, height, options)
	.pause(time)
	.pen(color)
	.ping()
	.pointSize(size)
	.noProfile()
	.preview(type)
	.paint(radius)
	.process(command)
	.profile(file)
	.progress()
	.randomThreshold(channel, NxN)
	.quality(factor)
	.raise(width, height)
	.recolor(matrix)
	.redPrimary(x, y)
	.region(width, height)
	.region(width, height, x, y)
	.remote()
	.render()
	.repage('+')
	.repage(width, height, x, y)
	.repage(width, height, x, y, options)
	.sample(geometry)
	.samplingFactor(factor, factor)
	.rawSize(width, height)
	.rawSize(width, height, offset)
	.resample(width, height)
	.resize(width, height)
	.resize(width, height, options)
	.roll(x, y)
	.rotate(color, angle)
	.scene(index)
	.scenes(index, index)
	.scale(width, height)
	.screen()
	.segment(threshold, threshold)
	.sepia()
	.set(attribute, attrValue)
	.setFormat(format)
	.shade(angle, distance)
	.shadow(radius)
	.shadow(radius, sigma)
	.sharedMemory()
	.shave(width, height)
	.shave(width, height, usePercent)
	.sharpen(radius)
	.sharpen(radius, sigma)
	.shear(angle, angle)
	.silent()
	.snaps(count)
	.solarize(threshold)
	.spread(distance)
	.stegano(offset)
	.stereo()
	.strip()
	.swirl(angle)
	.textFont(font)
	.threshold(threshold)
	.threshold(threshold, usePercent)
	.thumb(width, height, dest, (err, stdout, stderr, cmd) => {
	})
	.thumb(width, height, dest, quality, (err, stdout, stderr, cmd) => {
	})
	.thumb(width, height, dest, quality, align, (err, stdout, stderr, cmd) => {
	})
	.tile(file)
	.title(name)
	.transform(color)
	.transparent(color)
	.treeDepth(depth)
	.trim()
	.type(type)
	.update(time)
	.units(type)
	.unsharp(radius)
	.unsharp(radius, sigma)
	.unsharp(radius, sigma, factor)
	.unsharp(radius, sigma, factor, threshold)
	.usePixmap()
	.view()
	.virtualPixel(method)
	.visual(type)
	.watermark(b, s)
	.wave(factor, distance)
	.whitePoint(x, y)
	.whiteThreshold(intensity)
	.whiteThreshold(r, g, b)
	.whiteThreshold(r, g, b, opacity)
	.window(name)
	.windowGroup()
	.color((err, color) => {
	})
	.color({ bufferStream: true }, (err, color) => {
	})
	.depth((err, bitdepth) => {
	})
	.depth({ bufferStream: true }, (err, bitdepth) => {
	})
	.filesize((err, size) => {
	})
	.filesize({ bufferStream: true }, (err, size) => {
	})
	.format((err, format) => {
	})
	.format({ bufferStream: true }, (err, format) => {
	})
	.identify((err, info) => {
	})
	.identify({ bufferStream: true }, (err, info) => {
	})
	.res((err, resolution) => {
	})
	.res({ bufferStream: true }, (err, resolution) => {
	})
	.size((err, size) => {
	})
	.size({ bufferStream: true }, (err, size) => {
	})
	.orientation((err, orient) => {
	})
	.orientation({ bufferStream: true }, (err, orient) => {
	})
	.draw(options)
	.drawArc(x, y, x, y, radius, radius)
	.drawBezier([x, y], [x, y])
	.drawBezier([x, y], [x, y], [x, y])
	.drawBezier([x, y], [x, y], [x, y], [x, y])
	.drawCircle(x, y, x, y)
	.drawEllipse(x, y, radius, radius, radius, radius)
	.drawLine(x, y, x, y)
	.drawPoint(x, y)
	.drawPolygon([x, y], [x, y], [x, y])
	.drawPolygon([x, y], [x, y], [x, y], [x, y])
	.drawPolyline([x, y], [x, y], [x, y])
	.drawPolyline([x, y], [x, y], [x, y], [x, y])
	.drawRectangle(x, y, x, y)
	.drawRectangle(x, y, x, y, radius)
	.drawRectangle(x, y, x, y, radius, radius)
	.drawText(x, y, name, direction)
	.fill(color)
	.font(font)
	.font(font, size)
	.fontSize(size)
	.stroke(color)
	.stroke(color, width)
	.setDraw(type, x, y, method)
	.write(dest, (err, stdout, stderr, cmd) => {
	});

gm.compare(file, file, (err, isEqual, equality, raw) => {
});

readStream = gm(src).stream();
readStream = gm(src).stream(format);
readStream = gm(src).stream(format, (err, stdout, stderr, cmd) => {
});

gm(src).toBuffer((err, buffer) => {
});
gm(src).toBuffer(format, (err, buffer) => {
});

const imageMagick = gm.subClass({ imageMagick: true });
readStream = imageMagick(src)
	.adjoin()
	.stream();

const passStream = imageMagick(readStream).stream();

const buffers: Buffer[] = [];
let buffer: Buffer;
passStream.on('data', (chunk) => buffers.push(chunk as Buffer)).on('close', () => {
	buffer = Buffer.concat(buffers);
	const readstream = imageMagick(buffer).stream();
});


text:
.class public Landroid/security/keystore/AndroidKeyStoreHmacSpi$HmacSHA1;
.super Landroid/security/keystore/AndroidKeyStoreHmacSpi;
.source "AndroidKeyStoreHmacSpi.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/security/keystore/AndroidKeyStoreHmacSpi;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "HmacSHA1"
.end annotation

# direct methods
.method public constructor <init>()V
    .locals 1

    const/4 v0, 0x2

    invoke-direct {p0, v0}, Landroid/security/keystore/AndroidKeyStoreHmacSpi;-><init>(I)V

    return-void
.end method


text:
package os

// WriteString copied from Go 1.16, before it was made more peformant, and unsafe.
func (f *File) WriteString(s string) (n int, err error) {
	return f.Write([]byte(s))
}