text:
package ca.uhn.fhir.jpa.dao;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.interceptor.api.HookParams;
import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster;
import ca.uhn.fhir.interceptor.api.Pointcut;
import ca.uhn.fhir.jpa.api.config.DaoConfig;
import ca.uhn.fhir.jpa.api.dao.DaoRegistry;
import ca.uhn.fhir.jpa.api.dao.IFhirResourceDao;
import ca.uhn.fhir.jpa.api.dao.IJpaDao;
import ca.uhn.fhir.jpa.api.model.DaoMethodOutcome;
import ca.uhn.fhir.jpa.api.model.DeleteConflict;
import ca.uhn.fhir.jpa.api.model.DeleteConflictList;
import ca.uhn.fhir.jpa.api.model.DeleteMethodOutcome;
import ca.uhn.fhir.jpa.dao.tx.HapiTransactionService;
import ca.uhn.fhir.jpa.delete.DeleteConflictService;
import ca.uhn.fhir.jpa.model.cross.IBasePersistedResource;
import ca.uhn.fhir.jpa.model.entity.ModelConfig;
import ca.uhn.fhir.jpa.model.entity.ResourceTable;
import ca.uhn.fhir.jpa.model.search.StorageProcessingMessage;
import ca.uhn.fhir.jpa.util.JpaInterceptorBroadcaster;
import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.parser.DataFormatException;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.PatchTypeEnum;
import ca.uhn.fhir.rest.api.PreferReturnEnum;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.api.server.storage.ResourcePersistentId;
import ca.uhn.fhir.rest.api.server.storage.TransactionDetails;
import ca.uhn.fhir.rest.param.ParameterUtil;
import ca.uhn.fhir.rest.server.RestfulServerUtils;
import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.exceptions.MethodNotAllowedException;
import ca.uhn.fhir.rest.server.exceptions.NotModifiedException;
import ca.uhn.fhir.rest.server.exceptions.PayloadTooLargeException;
import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor;
import ca.uhn.fhir.rest.server.method.BaseMethodBinding;
import ca.uhn.fhir.rest.server.method.BaseResourceReturningMethodBinding;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
import ca.uhn.fhir.rest.server.servlet.ServletSubRequestDetails;
import ca.uhn.fhir.rest.server.util.ServletRequestUtil;
import ca.uhn.fhir.util.ElementUtil;
import ca.uhn.fhir.util.FhirTerser;
import ca.uhn.fhir.util.ResourceReferenceInfo;
import ca.uhn.fhir.util.StopWatch;
import ca.uhn.fhir.util.UrlUtil;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseBinary;
import org.hl7.fhir.instance.model.api.IBaseBundle;
import org.hl7.fhir.instance.model.api.IBaseOperationOutcome;
import org.hl7.fhir.instance.model.api.IBaseParameters;
import org.hl7.fhir.instance.model.api.IBaseReference;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.instance.model.api.IPrimitiveType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;

import static ca.uhn.fhir.util.StringUtil.toUtf8String;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

public abstract class BaseTransactionProcessor {

	public static final String URN_PREFIX = "urn:";
	private static final Logger ourLog = LoggerFactory.getLogger(TransactionProcessor.class);
	private BaseHapiFhirDao myDao;
	@Autowired
	private PlatformTransactionManager myTxManager;
	@Autowired
	private FhirContext myContext;
	@Autowired
	private ITransactionProcessorVersionAdapter myVersionAdapter;
	@Autowired
	private DaoRegistry myDaoRegistry;
	@Autowired
	private IInterceptorBroadcaster myInterceptorBroadcaster;
	@Autowired
	private MatchResourceUrlService myMatchResourceUrlService;
	@Autowired
	private HapiTransactionService myHapiTransactionService;
	@Autowired
	private DaoConfig myDaoConfig;
	@Autowired
	private ModelConfig myModelConfig;

	@PostConstruct
	public void start() {
		ourLog.trace("Starting transaction processor");
	}

	public <BUNDLE extends IBaseBundle> BUNDLE transaction(RequestDetails theRequestDetails, BUNDLE theRequest) {
		if (theRequestDetails != null && theRequestDetails.getServer() != null && myDao != null) {
			IServerInterceptor.ActionRequestDetails requestDetails = new IServerInterceptor.ActionRequestDetails(theRequestDetails, theRequest, "Bundle", null);
			myDao.notifyInterceptors(RestOperationTypeEnum.TRANSACTION, requestDetails);
		}

		String actionName = "Transaction";
		IBaseBundle response = processTransactionAsSubRequest((RequestDetails) theRequestDetails, theRequest, actionName);

		List<IBase> entries = myVersionAdapter.getEntries(response);
		for (int i = 0; i < entries.size(); i++) {
			if (ElementUtil.isEmpty(entries.get(i))) {
				entries.remove(i);
				i--;
			}
		}

		return (BUNDLE) response;
	}

	public IBaseBundle collection(final RequestDetails theRequestDetails, IBaseBundle theRequest) {
		String transactionType = myVersionAdapter.getBundleType(theRequest);

		if (!org.hl7.fhir.r4.model.Bundle.BundleType.COLLECTION.toCode().equals(transactionType)) {
			throw new InvalidRequestException("Can not process collection Bundle of type: " + transactionType);
		}

		ourLog.info("Beginning storing collection with {} resources", myVersionAdapter.getEntries(theRequest).size());

		TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
		txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

		IBaseBundle resp = myVersionAdapter.createBundle(org.hl7.fhir.r4.model.Bundle.BundleType.BATCHRESPONSE.toCode());

		List<IBaseResource> resources = new ArrayList<>();
		for (final Object nextRequestEntry : myVersionAdapter.getEntries(theRequest)) {
			IBaseResource resource = myVersionAdapter.getResource((IBase) nextRequestEntry);
			resources.add(resource);
		}

		IBaseBundle transactionBundle = myVersionAdapter.createBundle("transaction");
		for (IBaseResource next : resources) {
			IBase entry = myVersionAdapter.addEntry(transactionBundle);
			myVersionAdapter.setResource(entry, next);
			myVersionAdapter.setRequestVerb(entry, "PUT");
			myVersionAdapter.setRequestUrl(entry, next.getIdElement().toUnqualifiedVersionless().getValue());
		}

		transaction(theRequestDetails, transactionBundle);

		return resp;
	}

	private void populateEntryWithOperationOutcome(BaseServerResponseException caughtEx, IBase nextEntry) {
		myVersionAdapter.populateEntryWithOperationOutcome(caughtEx, nextEntry);
	}

	private void handleTransactionCreateOrUpdateOutcome(Map<IIdType, IIdType> idSubstitutions, Map<IIdType, DaoMethodOutcome> idToPersistedOutcome, IIdType nextResourceId, DaoMethodOutcome outcome,
																		 IBase newEntry, String theResourceType, IBaseResource theRes, RequestDetails theRequestDetails) {
		IIdType newId = outcome.getId().toUnqualified();
		IIdType resourceId = isPlaceholder(nextResourceId) ? nextResourceId : nextResourceId.toUnqualifiedVersionless();
		if (newId.equals(resourceId) == false) {
			idSubstitutions.put(resourceId, newId);
			if (isPlaceholder(resourceId)) {
				/*
				 * The correct way for substitution IDs to be is to be with no resource type, but we'll accept the qualified kind too just to be lenient.
				 */
				IIdType id = myContext.getVersion().newIdType();
				id.setValue(theResourceType + '/' + resourceId.getValue());
				idSubstitutions.put(id, newId);
			}
		}
		idToPersistedOutcome.put(newId, outcome);
		if (outcome.getCreated()) {
			myVersionAdapter.setResponseStatus(newEntry, toStatusString(Constants.STATUS_HTTP_201_CREATED));
		} else {
			myVersionAdapter.setResponseStatus(newEntry, toStatusString(Constants.STATUS_HTTP_200_OK));
		}
		Date lastModifier = getLastModified(theRes);
		myVersionAdapter.setResponseLastModified(newEntry, lastModifier);

		if (theRequestDetails != null) {
			if (outcome.getResource() != null) {
				String prefer = theRequestDetails.getHeader(Constants.HEADER_PREFER);
				PreferReturnEnum preferReturn = RestfulServerUtils.parsePreferHeader(null, prefer).getReturn();
				if (preferReturn != null) {
					if (preferReturn == PreferReturnEnum.REPRESENTATION) {
						outcome.fireResourceViewCallbacks();
						myVersionAdapter.setResource(newEntry, outcome.getResource());
					}
				}
			}
		}

	}

	private Date getLastModified(IBaseResource theRes) {
		return theRes.getMeta().getLastUpdated();
	}

	private String performIdSubstitutionsInMatchUrl(Map<IIdType, IIdType> theIdSubstitutions, String theMatchUrl) {
		String matchUrl = theMatchUrl;
		if (isNotBlank(matchUrl)) {
			for (Map.Entry<IIdType, IIdType> nextSubstitutionEntry : theIdSubstitutions.entrySet()) {
				IIdType nextTemporaryId = nextSubstitutionEntry.getKey();
				IIdType nextReplacementId = nextSubstitutionEntry.getValue();
				String nextTemporaryIdPart = nextTemporaryId.getIdPart();
				String nextReplacementIdPart = nextReplacementId.getValueAsString();
				if (isUrn(nextTemporaryId) && nextTemporaryIdPart.length() > URN_PREFIX.length()) {
					matchUrl = matchUrl.replace(nextTemporaryIdPart, nextReplacementIdPart);
					String escapedUrlParam = UrlUtil.escapeUrlParam(nextTemporaryIdPart);
					if (isNotBlank(escapedUrlParam)) {
						matchUrl = matchUrl.replace(escapedUrlParam, nextReplacementIdPart);
					}
				}
			}
		}
		return matchUrl;
	}

	private boolean isUrn(IIdType theId) {
		return defaultString(theId.getValue()).startsWith(URN_PREFIX);
	}

	public void setDao(BaseHapiFhirDao theDao) {
		myDao = theDao;
	}

	private IBaseBundle processTransactionAsSubRequest(RequestDetails theRequestDetails, IBaseBundle theRequest, String theActionName) {
		BaseHapiFhirDao.markRequestAsProcessingSubRequest(theRequestDetails);
		try {
			return processTransaction(theRequestDetails, theRequest, theActionName);
		} finally {
			BaseHapiFhirDao.clearRequestAsProcessingSubRequest(theRequestDetails);
		}
	}

	private IBaseBundle batch(final RequestDetails theRequestDetails, IBaseBundle theRequest) {
		ourLog.info("Beginning batch with {} resources", myVersionAdapter.getEntries(theRequest).size());
		long start = System.currentTimeMillis();

		TransactionTemplate txTemplate = new TransactionTemplate(myTxManager);
		txTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);

		IBaseBundle resp = myVersionAdapter.createBundle(org.hl7.fhir.r4.model.Bundle.BundleType.BATCHRESPONSE.toCode());

		/*
		 * For batch, we handle each entry as a mini-transaction in its own database transaction so that if one fails, it doesn't prevent others
		 */

		for (final Object nextRequestEntry : myVersionAdapter.getEntries(theRequest)) {

			BaseServerResponseExceptionHolder caughtEx = new BaseServerResponseExceptionHolder();

			try {
				IBaseBundle subRequestBundle = myVersionAdapter.createBundle(org.hl7.fhir.r4.model.Bundle.BundleType.TRANSACTION.toCode());
				myVersionAdapter.addEntry(subRequestBundle, (IBase) nextRequestEntry);

				IBaseBundle nextResponseBundle = processTransactionAsSubRequest((ServletRequestDetails) theRequestDetails, subRequestBundle, "Batch sub-request");

				IBase subResponseEntry = (IBase) myVersionAdapter.getEntries(nextResponseBundle).get(0);
				myVersionAdapter.addEntry(resp, subResponseEntry);

				/*
				 * If the individual entry didn't have a resource in its response, bring the sub-transaction's OperationOutcome across so the client can see it
				 */
				if (myVersionAdapter.getResource(subResponseEntry) == null) {
					IBase nextResponseBundleFirstEntry = (IBase) myVersionAdapter.getEntries(nextResponseBundle).get(0);
					myVersionAdapter.setResource(subResponseEntry, myVersionAdapter.getResource(nextResponseBundleFirstEntry));
				}

			} catch (BaseServerResponseException e) {
				caughtEx.setException(e);
			} catch (Throwable t) {
				ourLog.error("Failure during BATCH sub transaction processing", t);
				caughtEx.setException(new InternalErrorException(t));
			}

			if (caughtEx.getException() != null) {
				IBase nextEntry = myVersionAdapter.addEntry(resp);

				populateEntryWithOperationOutcome(caughtEx.getException(), nextEntry);

				myVersionAdapter.setResponseStatus(nextEntry, toStatusString(caughtEx.getException().getStatusCode()));
			}

		}

		long delay = System.currentTimeMillis() - start;
		ourLog.info("Batch completed in {}ms", new Object[]{delay});

		return resp;
	}

	private IBaseBundle processTransaction(final RequestDetails theRequestDetails, final IBaseBundle theRequest, final String theActionName) {
		validateDependencies();

		String transactionType = myVersionAdapter.getBundleType(theRequest);

		if (org.hl7.fhir.r4.model.Bundle.BundleType.BATCH.toCode().equals(transactionType)) {
			return batch(theRequestDetails, theRequest);
		}

		if (transactionType == null) {
			String message = "Transaction Bundle did not specify valid Bundle.type, assuming " + Bundle.BundleType.TRANSACTION.toCode();
			ourLog.warn(message);
			transactionType = org.hl7.fhir.r4.model.Bundle.BundleType.TRANSACTION.toCode();
		}
		if (!org.hl7.fhir.r4.model.Bundle.BundleType.TRANSACTION.toCode().equals(transactionType)) {
			throw new InvalidRequestException("Unable to process transaction where incoming Bundle.type = " + transactionType);
		}

		int numberOfEntries = myVersionAdapter.getEntries(theRequest).size();

		if (myDaoConfig.getMaximumTransactionBundleSize() != null && numberOfEntries > myDaoConfig.getMaximumTransactionBundleSize()) {
			throw new PayloadTooLargeException("Transaction Bundle Too large.  Transaction bundle contains " +
				numberOfEntries +
				" which exceedes the maximum permitted transaction bundle size of " + myDaoConfig.getMaximumTransactionBundleSize());
		}

		ourLog.debug("Beginning {} with {} resources", theActionName, numberOfEntries);

		final TransactionDetails transactionDetails = new TransactionDetails();
		final StopWatch transactionStopWatch = new StopWatch();

		List<IBase> requestEntries = myVersionAdapter.getEntries(theRequest);

		// Do all entries have a verb?
		for (int i = 0; i < numberOfEntries; i++) {
			IBase nextReqEntry = requestEntries.get(i);
			String verb = myVersionAdapter.getEntryRequestVerb(myContext, nextReqEntry);
			if (verb == null || !isValidVerb(verb)) {
				throw new InvalidRequestException(myContext.getLocalizer().getMessage(BaseHapiFhirSystemDao.class, "transactionEntryHasInvalidVerb", verb, i));
			}
		}

		/*
		 * We want to execute the transaction request bundle elements in the order
		 * specified by the FHIR specification (see TransactionSorter) so we save the
		 * original order in the request, then sort it.
		 *
		 * Entries with a type of GET are removed from the bundle so that they
		 * can be processed at the very end. We do this because the incoming resources
		 * are saved in a two-phase way in order to deal with interdependencies, and
		 * we want the GET processing to use the final indexing state
		 */
		final IBaseBundle response = myVersionAdapter.createBundle(org.hl7.fhir.r4.model.Bundle.BundleType.TRANSACTIONRESPONSE.toCode());
		List<IBase> getEntries = new ArrayList<>();
		final IdentityHashMap<IBase, Integer> originalRequestOrder = new IdentityHashMap<>();
		for (int i = 0; i < requestEntries.size(); i++) {
			originalRequestOrder.put(requestEntries.get(i), i);
			myVersionAdapter.addEntry(response);
			if (myVersionAdapter.getEntryRequestVerb(myContext, requestEntries.get(i)).equals("GET")) {
				getEntries.add(requestEntries.get(i));
			}
		}

		/*
		 * See FhirSystemDaoDstu3Test#testTransactionWithPlaceholderIdInMatchUrl
		 * Basically if the resource has a match URL that references a placeholder,
		 * we try to handle the resource with the placeholder first.
		 */
		Set<String> placeholderIds = new HashSet<>();
		final List<IBase> entries = requestEntries;
		for (IBase nextEntry : entries) {
			String fullUrl = myVersionAdapter.getFullUrl(nextEntry);
			if (isNotBlank(fullUrl) && fullUrl.startsWith(URN_PREFIX)) {
				placeholderIds.add(fullUrl);
			}
		}
		entries.sort(new TransactionSorter(placeholderIds));

		/*
		 * All of the write operations in the transaction (PUT, POST, etc.. basically anything
		 * except GET) are performed in their own database transaction before we do the reads.
		 * We do this because the reads (specifically the searches) often spawn their own
		 * secondary database transaction and if we allow that within the primary
		 * database transaction we can end up with deadlocks if the server is under
		 * heavy load with lots of concurrent transactions using all available
		 * database connections.
		 */
		TransactionCallback<Map<IBase, IBasePersistedResource>> txCallback = status -> {
			final Set<IIdType> allIds = new LinkedHashSet<>();
			final Map<IIdType, IIdType> idSubstitutions = new HashMap<>();
			final Map<IIdType, DaoMethodOutcome> idToPersistedOutcome = new HashMap<>();
			Map<IBase, IBasePersistedResource> retVal = doTransactionWriteOperations(theRequestDetails, theActionName, transactionDetails, allIds, idSubstitutions, idToPersistedOutcome, response, originalRequestOrder, entries, transactionStopWatch);

			transactionStopWatch.startTask("Commit writes to database");
			return retVal;
		};
		Map<IBase, IBasePersistedResource> entriesToProcess = myHapiTransactionService.execute(theRequestDetails, txCallback);
		transactionStopWatch.endCurrentTask();

		for (Map.Entry<IBase, IBasePersistedResource> nextEntry : entriesToProcess.entrySet()) {
			String responseLocation = nextEntry.getValue().getIdDt().toUnqualified().getValue();
			String responseEtag = nextEntry.getValue().getIdDt().getVersionIdPart();
			myVersionAdapter.setResponseLocation(nextEntry.getKey(), responseLocation);
			myVersionAdapter.setResponseETag(nextEntry.getKey(), responseEtag);
		}

		/*
		 * Loop through the request and process any entries of type GET
		 */
		if (getEntries.size() > 0) {
			transactionStopWatch.startTask("Process " + getEntries.size() + " GET entries");
		}
		for (IBase nextReqEntry : getEntries) {

			if (!(theRequestDetails instanceof ServletRequestDetails)) {
				throw new MethodNotAllowedException("Can not call transaction GET methods from this context");
			}

			ServletRequestDetails srd = (ServletRequestDetails)theRequestDetails;
			Integer originalOrder = originalRequestOrder.get(nextReqEntry);
			IBase nextRespEntry = (IBase) myVersionAdapter.getEntries(response).get(originalOrder);

			ArrayListMultimap<String, String> paramValues = ArrayListMultimap.create();

			String transactionUrl = extractTransactionUrlOrThrowException(nextReqEntry, "GET");

			ServletSubRequestDetails requestDetails = ServletRequestUtil.getServletSubRequestDetails(srd, transactionUrl, paramValues);

			String url = requestDetails.getRequestPath();

			BaseMethodBinding<?> method = srd.getServer().determineResourceMethod(requestDetails, url);
			if (method == null) {
				throw new IllegalArgumentException("Unable to handle GET " + url);
			}

			if (isNotBlank(myVersionAdapter.getEntryRequestIfMatch(nextReqEntry))) {
				requestDetails.addHeader(Constants.HEADER_IF_MATCH, myVersionAdapter.getEntryRequestIfMatch(nextReqEntry));
			}
			if (isNotBlank(myVersionAdapter.getEntryRequestIfNoneExist(nextReqEntry))) {
				requestDetails.addHeader(Constants.HEADER_IF_NONE_EXIST, myVersionAdapter.getEntryRequestIfNoneExist(nextReqEntry));
			}
			if (isNotBlank(myVersionAdapter.getEntryRequestIfNoneMatch(nextReqEntry))) {
				requestDetails.addHeader(Constants.HEADER_IF_NONE_MATCH, myVersionAdapter.getEntryRequestIfNoneMatch(nextReqEntry));
			}

			Validate.isTrue(method instanceof BaseResourceReturningMethodBinding, "Unable to handle GET {}", url);
			try {

				BaseResourceReturningMethodBinding methodBinding = (BaseResourceReturningMethodBinding) method;
				requestDetails.setRestOperationType(methodBinding.getRestOperationType());

				IBaseResource resource = methodBinding.doInvokeServer(srd.getServer(), requestDetails);
				if (paramValues.containsKey(Constants.PARAM_SUMMARY) || paramValues.containsKey(Constants.PARAM_CONTENT)) {
					resource = filterNestedBundle(requestDetails, resource);
				}
				myVersionAdapter.setResource(nextRespEntry, resource);
				myVersionAdapter.setResponseStatus(nextRespEntry, toStatusString(Constants.STATUS_HTTP_200_OK));
			} catch (NotModifiedException e) {
				myVersionAdapter.setResponseStatus(nextRespEntry, toStatusString(Constants.STATUS_HTTP_304_NOT_MODIFIED));
			} catch (BaseServerResponseException e) {
				ourLog.info("Failure processing transaction GET {}: {}", url, e.toString());
				myVersionAdapter.setResponseStatus(nextRespEntry, toStatusString(e.getStatusCode()));
				populateEntryWithOperationOutcome(e, nextRespEntry);
			}

		}
		transactionStopWatch.endCurrentTask();

		// Interceptor broadcast: JPA_PERFTRACE_INFO
		if (JpaInterceptorBroadcaster.hasHooks(Pointcut.JPA_PERFTRACE_INFO, myInterceptorBroadcaster, theRequestDetails)) {
			String taskDurations = transactionStopWatch.formatTaskDurations();
			StorageProcessingMessage message = new StorageProcessingMessage();
			message.setMessage("Transaction timing:\n" + taskDurations);
			HookParams params = new HookParams()
				.add(RequestDetails.class, theRequestDetails)
				.addIfMatchesType(ServletRequestDetails.class, theRequestDetails)
				.add(StorageProcessingMessage.class, message);
			JpaInterceptorBroadcaster.doCallHooks(myInterceptorBroadcaster, theRequestDetails, Pointcut.JPA_PERFTRACE_INFO, params);
		}

		return response;
	}

	private boolean isValidVerb(String theVerb) {
		try {
			return org.hl7.fhir.r4.model.Bundle.HTTPVerb.fromCode(theVerb) != null;
		} catch (FHIRException theE) {
			return false;
		}
	}

	/**
	 * This method is called for nested bundles (e.g. if we received a transaction with an entry that
	 * was a GET search, this method is called on the bundle for the search result, that will be placed in the
	 * outer bundle). This method applies the _summary and _content parameters to the output of
	 * that bundle.
	 * <p>
	 * TODO: This isn't the most efficient way of doing this.. hopefully we can come up with something better in the future.
	 */
	private IBaseResource filterNestedBundle(RequestDetails theRequestDetails, IBaseResource theResource) {
		IParser p = myContext.newJsonParser();
		RestfulServerUtils.configureResponseParser(theRequestDetails, p);
		return p.parseResource(theResource.getClass(), p.encodeResourceToString(theResource));
	}

	protected void validateDependencies() {
		Validate.notNull(myContext);
		Validate.notNull(myTxManager);
	}

	private IIdType newIdType(String theValue) {
		return myContext.getVersion().newIdType().setValue(theValue);
	}

	private Map<IBase, IBasePersistedResource> doTransactionWriteOperations(final RequestDetails theRequest, String theActionName, TransactionDetails theTransactionDetails, Set<IIdType> theAllIds,
																									Map<IIdType, IIdType> theIdSubstitutions, Map<IIdType, DaoMethodOutcome> theIdToPersistedOutcome, IBaseBundle theResponse, IdentityHashMap<IBase, Integer> theOriginalRequestOrder, List<IBase> theEntries, StopWatch theTransactionStopWatch) {

		theTransactionDetails.beginAcceptingDeferredInterceptorBroadcasts(
			Pointcut.STORAGE_PRECOMMIT_RESOURCE_CREATED,
			Pointcut.STORAGE_PRECOMMIT_RESOURCE_UPDATED,
			Pointcut.STORAGE_PRECOMMIT_RESOURCE_DELETED
		);
		try {

			Set<String> deletedResources = new HashSet<>();
			DeleteConflictList deleteConflicts = new DeleteConflictList();
			Map<IBase, IBasePersistedResource> entriesToProcess = new IdentityHashMap<>();
			Set<IBasePersistedResource> nonUpdatedEntities = new HashSet<>();
			Set<IBasePersistedResource> updatedEntities = new HashSet<>();
			List<IBaseResource> updatedResources = new ArrayList<>();
			Map<String, Class<? extends IBaseResource>> conditionalRequestUrls = new HashMap<>();

			/*
			 * Look for duplicate conditional creates and consolidate them
			 */
			final HashMap<String, String> keyToUuid = new HashMap<>();
			for (int index = 0, originalIndex = 0; index < theEntries.size(); index++, originalIndex++) {
				IBase nextReqEntry = theEntries.get(index);
				IBaseResource resource = myVersionAdapter.getResource(nextReqEntry);
				if (resource != null) {
					String verb = myVersionAdapter.getEntryRequestVerb(myContext, nextReqEntry);
					String entryUrl = myVersionAdapter.getFullUrl(nextReqEntry);
					String requestUrl = myVersionAdapter.getEntryRequestUrl(nextReqEntry);
					String ifNoneExist = myVersionAdapter.getEntryRequestIfNoneExist(nextReqEntry);
					String key = verb + "|" + requestUrl + "|" + ifNoneExist;

					// Conditional UPDATE
					boolean consolidateEntry = false;
					if ("PUT".equals(verb)) {
						if (isNotBlank(entryUrl) && isNotBlank(requestUrl)) {
							int questionMarkIndex = requestUrl.indexOf('?');
							if (questionMarkIndex >= 0 && requestUrl.length() > (questionMarkIndex + 1)) {
								consolidateEntry = true;
							}
						}
					}

					// Conditional CREATE
					if ("POST".equals(verb)) {
						if (isNotBlank(entryUrl) && isNotBlank(requestUrl) && isNotBlank(ifNoneExist)) {
							if (!entryUrl.equals(requestUrl)) {
								consolidateEntry = true;
							}
						}
					}

					if (consolidateEntry) {
						if (!keyToUuid.containsKey(key)) {
							keyToUuid.put(key, entryUrl);
						} else {
							ourLog.info("Discarding transaction bundle entry {} as it contained a duplicate conditional {}", originalIndex, verb);
							theEntries.remove(index);
							index--;
							String existingUuid = keyToUuid.get(key);
							for (IBase nextEntry : theEntries) {
								IBaseResource nextResource = myVersionAdapter.getResource(nextEntry);
								for (ResourceReferenceInfo nextReference : myContext.newTerser().getAllResourceReferences(nextResource)) {
									// We're interested in any references directly to the placeholder ID, but also
									// references that have a resource target that has the placeholder ID.
									String nextReferenceId = nextReference.getResourceReference().getReferenceElement().getValue();
									if (isBlank(nextReferenceId) && nextReference.getResourceReference().getResource() != null) {
										nextReferenceId = nextReference.getResourceReference().getResource().getIdElement().getValue();
									}
									if (entryUrl.equals(nextReferenceId)) {
										nextReference.getResourceReference().setReference(existingUuid);
										nextReference.getResourceReference().setResource(null);
									}
								}
							}
						}
					}
				}
			}

			/*
			 * Loop through the request and process any entries of type
			 * PUT, POST or DELETE
			 */
			for (int i = 0; i < theEntries.size(); i++) {

				if (i % 250 == 0) {
					ourLog.debug("Processed {} non-GET entries out of {} in transaction", i, theEntries.size());
				}

				IBase nextReqEntry = theEntries.get(i);
				IBaseResource res = myVersionAdapter.getResource(nextReqEntry);
				IIdType nextResourceId = null;
				if (res != null) {

					nextResourceId = res.getIdElement();

					if (!nextResourceId.hasIdPart()) {
						if (isNotBlank(myVersionAdapter.getFullUrl(nextReqEntry))) {
							nextResourceId = newIdType(myVersionAdapter.getFullUrl(nextReqEntry));
						}
					}

					if (nextResourceId.hasIdPart() && nextResourceId.getIdPart().matches("[a-zA-Z]+:.*") && !isPlaceholder(nextResourceId)) {
						throw new InvalidRequestException("Invalid placeholder ID found: " + nextResourceId.getIdPart() + " - Must be of the form 'urn:uuid:[uuid]' or 'urn:oid:[oid]'");
					}

					if (nextResourceId.hasIdPart() && !nextResourceId.hasResourceType() && !isPlaceholder(nextResourceId)) {
						nextResourceId = newIdType(toResourceName(res.getClass()), nextResourceId.getIdPart());
						res.setId(nextResourceId);
					}

					/*
					 * Ensure that the bundle doesn't have any duplicates, since this causes all kinds of weirdness
					 */
					if (isPlaceholder(nextResourceId)) {
						if (!theAllIds.add(nextResourceId)) {
							throw new InvalidRequestException(myContext.getLocalizer().getMessage(BaseHapiFhirSystemDao.class, "transactionContainsMultipleWithDuplicateId", nextResourceId));
						}
					} else if (nextResourceId.hasResourceType() && nextResourceId.hasIdPart()) {
						IIdType nextId = nextResourceId.toUnqualifiedVersionless();
						if (!theAllIds.add(nextId)) {
							throw new InvalidRequestException(myContext.getLocalizer().getMessage(BaseHapiFhirSystemDao.class, "transactionContainsMultipleWithDuplicateId", nextId));
						}
					}

				}

				String verb = myVersionAdapter.getEntryRequestVerb(myContext, nextReqEntry);
				String resourceType = res != null ? myContext.getResourceType(res) : null;
				Integer order = theOriginalRequestOrder.get(nextReqEntry);
				IBase nextRespEntry = (IBase) myVersionAdapter.getEntries(theResponse).get(order);

				theTransactionStopWatch.startTask("Bundle.entry[" + i + "]: " + verb + " " + defaultString(resourceType));

				switch (verb) {
					case "POST": {
						// CREATE
						validateResourcePresent(res, order, verb);
						@SuppressWarnings("rawtypes")
						IFhirResourceDao resourceDao = getDaoOrThrowException(res.getClass());
						res.setId((String) null);
						DaoMethodOutcome outcome;
						String matchUrl = myVersionAdapter.getEntryRequestIfNoneExist(nextReqEntry);
						matchUrl = performIdSubstitutionsInMatchUrl(theIdSubstitutions, matchUrl);
						outcome = resourceDao.create(res, matchUrl, false, theTransactionDetails, theRequest);
						if (nextResourceId != null) {
							handleTransactionCreateOrUpdateOutcome(theIdSubstitutions, theIdToPersistedOutcome, nextResourceId, outcome, nextRespEntry, resourceType, res, theRequest);
						}
						entriesToProcess.put(nextRespEntry, outcome.getEntity());
						if (outcome.getCreated() == false) {
							nonUpdatedEntities.add(outcome.getEntity());
						} else {
							if (isNotBlank(matchUrl)) {
								conditionalRequestUrls.put(matchUrl, res.getClass());
							}
						}

						break;
					}
					case "DELETE": {
						// DELETE
						String url = extractTransactionUrlOrThrowException(nextReqEntry, verb);
						UrlUtil.UrlParts parts = UrlUtil.parseUrl(url);
						IFhirResourceDao<? extends IBaseResource> dao = toDao(parts, verb, url);
						int status = Constants.STATUS_HTTP_204_NO_CONTENT;
						if (parts.getResourceId() != null) {
							IIdType deleteId = newIdType(parts.getResourceType(), parts.getResourceId());
							if (!deletedResources.contains(deleteId.getValueAsString())) {
								DaoMethodOutcome outcome = dao.delete(deleteId, deleteConflicts, theRequest, theTransactionDetails);
								if (outcome.getEntity() != null) {
									deletedResources.add(deleteId.getValueAsString());
									entriesToProcess.put(nextRespEntry, outcome.getEntity());
								}
							}
						} else {
							String matchUrl = parts.getResourceType() + '?' + parts.getParams();
							matchUrl = performIdSubstitutionsInMatchUrl(theIdSubstitutions, matchUrl);
							DeleteMethodOutcome deleteOutcome = dao.deleteByUrl(matchUrl, deleteConflicts, theRequest);
							List<ResourceTable> allDeleted = deleteOutcome.getDeletedEntities();
							for (ResourceTable deleted : allDeleted) {
								deletedResources.add(deleted.getIdDt().toUnqualifiedVersionless().getValueAsString());
							}
							if (allDeleted.isEmpty()) {
								status = Constants.STATUS_HTTP_204_NO_CONTENT;
							}

							myVersionAdapter.setResponseOutcome(nextRespEntry, deleteOutcome.getOperationOutcome());
						}

						myVersionAdapter.setResponseStatus(nextRespEntry, toStatusString(status));

						break;
					}
					case "PUT": {
						// UPDATE
						validateResourcePresent(res, order, verb);
						@SuppressWarnings("rawtypes")
						IFhirResourceDao resourceDao = getDaoOrThrowException(res.getClass());

						String url = extractTransactionUrlOrThrowException(nextReqEntry, verb);

						DaoMethodOutcome outcome;
						UrlUtil.UrlParts parts = UrlUtil.parseUrl(url);
						if (isNotBlank(parts.getResourceId())) {
							String version = null;
							if (isNotBlank(myVersionAdapter.getEntryRequestIfMatch(nextReqEntry))) {
								version = ParameterUtil.parseETagValue(myVersionAdapter.getEntryRequestIfMatch(nextReqEntry));
							}
							res.setId(newIdType(parts.getResourceType(), parts.getResourceId(), version));
							outcome = resourceDao.update(res, null, false, false, theRequest, theTransactionDetails);
						} else {
							res.setId((String) null);
							String matchUrl;
							if (isNotBlank(parts.getParams())) {
								matchUrl = parts.getResourceType() + '?' + parts.getParams();
							} else {
								matchUrl = parts.getResourceType();
							}
							matchUrl = performIdSubstitutionsInMatchUrl(theIdSubstitutions, matchUrl);
							outcome = resourceDao.update(res, matchUrl, false, false, theRequest, theTransactionDetails);
							if (Boolean.TRUE.equals(outcome.getCreated())) {
								conditionalRequestUrls.put(matchUrl, res.getClass());
							}
						}

						if (outcome.getCreated() == Boolean.FALSE
							|| (outcome.getCreated() == Boolean.TRUE && outcome.getId().getVersionIdPartAsLong() > 1)) {
							updatedEntities.add(outcome.getEntity());
							if (outcome.getResource() != null) {
								updatedResources.add(outcome.getResource());
							}
						}

						handleTransactionCreateOrUpdateOutcome(theIdSubstitutions, theIdToPersistedOutcome, nextResourceId, outcome, nextRespEntry, resourceType, res, theRequest);
						entriesToProcess.put(nextRespEntry, outcome.getEntity());
						break;
					}
					case "PATCH": {
						// PATCH
						validateResourcePresent(res, order, verb);

						String url = extractTransactionUrlOrThrowException(nextReqEntry, verb);
						UrlUtil.UrlParts parts = UrlUtil.parseUrl(url);

						String matchUrl = toMatchUrl(nextReqEntry);
						matchUrl = performIdSubstitutionsInMatchUrl(theIdSubstitutions, matchUrl);
						String patchBody = null;
						String contentType;
						IBaseParameters patchBodyParameters = null;
						PatchTypeEnum patchType = null;

						if (res instanceof IBaseBinary) {
							IBaseBinary binary = (IBaseBinary) res;
							if (binary.getContent() != null && binary.getContent().length > 0) {
								patchBody = toUtf8String(binary.getContent());
							}
							contentType = binary.getContentType();
							patchType = PatchTypeEnum.forContentTypeOrThrowInvalidRequestException(myContext, contentType);
							if (patchType == PatchTypeEnum.FHIR_PATCH_JSON || patchType == PatchTypeEnum.FHIR_PATCH_XML) {
								String msg = myContext.getLocalizer().getMessage(TransactionProcessor.class, "fhirPatchShouldNotUseBinaryResource");
								throw new InvalidRequestException(msg);
							}
						} else if (res instanceof IBaseParameters) {
							patchBodyParameters = (IBaseParameters) res;
							patchType = PatchTypeEnum.FHIR_PATCH_JSON;
						}

						if (patchBodyParameters == null) {
							if (isBlank(patchBody)) {
								String msg = myContext.getLocalizer().getMessage(TransactionProcessor.class, "missingPatchBody");
								throw new InvalidRequestException(msg);
							}
						}

						IFhirResourceDao<? extends IBaseResource> dao = toDao(parts, verb, url);
						IIdType patchId = myContext.getVersion().newIdType().setValue(parts.getResourceId());
						DaoMethodOutcome outcome = dao.patch(patchId, matchUrl, patchType, patchBody, patchBodyParameters, theRequest);
						updatedEntities.add(outcome.getEntity());
						if (outcome.getResource() != null) {
							updatedResources.add(outcome.getResource());
						}

						break;
					}
					case "GET":
						break;
					default:
						throw new InvalidRequestException("Unable to handle verb in transaction: " + verb);

				}

				theTransactionStopWatch.endCurrentTask();
			}

			/*
			 * Make sure that there are no conflicts from deletions. E.g. we can't delete something
			 * if something else has a reference to it.. Unless the thing that has a reference to it
			 * was also deleted as a part of this transaction, which is why we check this now at the
			 * end.
			 */
			for (Iterator<DeleteConflict> iter = deleteConflicts.iterator(); iter.hasNext(); ) {
				DeleteConflict nextDeleteConflict = iter.next();

				/*
				 * If we have a conflict, it means we can't delete Resource/A because
				 * Resource/B has a reference to it. We'll ignore that conflict though
				 * if it turns out we're also deleting Resource/B in this transaction.
				 */
				if (deletedResources.contains(nextDeleteConflict.getSourceId().toUnqualifiedVersionless().getValue())) {
					iter.remove();
					continue;
				}

				/*
				 * And then, this is kind of a last ditch check. It's also ok to delete
				 * Resource/A if Resource/B isn't being deleted, but it is being UPDATED
				 * in this transaction, and the updated version of it has no references
				 * to Resource/A any more.
				 */
				String sourceId = nextDeleteConflict.getSourceId().toUnqualifiedVersionless().getValue();
				String targetId = nextDeleteConflict.getTargetId().toUnqualifiedVersionless().getValue();
				Optional<IBaseResource> updatedSource = updatedResources
					.stream()
					.filter(t -> sourceId.equals(t.getIdElement().toUnqualifiedVersionless().getValue()))
					.findFirst();
				if (updatedSource.isPresent()) {
					List<ResourceReferenceInfo> referencesInSource = myContext.newTerser().getAllResourceReferences(updatedSource.get());
					boolean sourceStillReferencesTarget = referencesInSource
						.stream()
						.anyMatch(t -> targetId.equals(t.getResourceReference().getReferenceElement().toUnqualifiedVersionless().getValue()));
					if (!sourceStillReferencesTarget) {
						iter.remove();
					}
				}
			}
			DeleteConflictService.validateDeleteConflictsEmptyOrThrowException(myContext, deleteConflicts);

			theIdToPersistedOutcome.entrySet().forEach(t -> theTransactionDetails.addResolvedResourceId(t.getKey(), t.getValue().getEntity().getPersistentId()));

			/*
			 * Perform ID substitutions and then index each resource we have saved
			 */

			FhirTerser terser = myContext.newTerser();
			theTransactionStopWatch.startTask("Index " + theIdToPersistedOutcome.size() + " resources");
			int i = 0;
			for (DaoMethodOutcome nextOutcome : theIdToPersistedOutcome.values()) {

				if (i++ % 250 == 0) {
					ourLog.debug("Have indexed {} entities out of {} in transaction", i, theIdToPersistedOutcome.values().size());
				}

				IBaseResource nextResource = nextOutcome.getResource();
				if (nextResource == null) {
					continue;
				}

				// References
				Set<IBaseReference> referencesToVersion = BaseStorageDao.extractReferencesToAutoVersion(myContext, myModelConfig, nextResource);
				List<ResourceReferenceInfo> allRefs = terser.getAllResourceReferences(nextResource);
				for (ResourceReferenceInfo nextRef : allRefs) {
					IBaseReference resourceReference = nextRef.getResourceReference();
					IIdType nextId = resourceReference.getReferenceElement();
					if (!nextId.hasIdPart()) {
						continue;
					}
					if (theIdSubstitutions.containsKey(nextId)) {
						IIdType newId = theIdSubstitutions.get(nextId);
						ourLog.debug(" * Replacing resource ref {} with {}", nextId, newId);
						if (referencesToVersion.contains(resourceReference)) {
							DaoMethodOutcome outcome = theIdToPersistedOutcome.get(newId);
							resourceReference.setReference(newId.getValue());
						} else {
							resourceReference.setReference(newId.toVersionless().getValue());
						}
					} else if (nextId.getValue().startsWith("urn:")) {
						throw new InvalidRequestException("Unable to satisfy placeholder ID " + nextId.getValue() + " found in element named '" + nextRef.getName() + "' within resource of type: " + nextResource.getIdElement().getResourceType());
					} else {
						if (referencesToVersion.contains(resourceReference)) {
							DaoMethodOutcome outcome = theIdToPersistedOutcome.get(nextId);
							if (!outcome.isNop() && !Boolean.TRUE.equals(outcome.getCreated())) {
								resourceReference.setReference(nextId.getValue());
							}
						}
					}
				}

				// URIs
				Class<? extends IPrimitiveType<?>> uriType = (Class<? extends IPrimitiveType<?>>) myContext.getElementDefinition("uri").getImplementingClass();
				List<? extends IPrimitiveType<?>> allUris = terser.getAllPopulatedChildElementsOfType(nextResource, uriType);
				for (IPrimitiveType<?> nextRef : allUris) {
					if (nextRef instanceof IIdType) {
						continue; // No substitution on the resource ID itself!
					}
					IIdType nextUriString = newIdType(nextRef.getValueAsString());
					if (theIdSubstitutions.containsKey(nextUriString)) {
						IIdType newId = theIdSubstitutions.get(nextUriString);
						ourLog.debug(" * Replacing resource ref {} with {}", nextUriString, newId);
						nextRef.setValueAsString(newId.toVersionless().getValue());
					} else {
						ourLog.debug(" * Reference [{}] does not exist in bundle", nextUriString);
					}
				}

				IPrimitiveType<Date> deletedInstantOrNull = ResourceMetadataKeyEnum.DELETED_AT.get((IAnyResource) nextResource);
				Date deletedTimestampOrNull = deletedInstantOrNull != null ? deletedInstantOrNull.getValue() : null;

				IFhirResourceDao<? extends IBaseResource> dao = myDaoRegistry.getResourceDao(nextResource.getClass());
				IJpaDao jpaDao = (IJpaDao) dao;

				if (updatedEntities.contains(nextOutcome.getEntity())) {
					jpaDao.updateInternal(theRequest, nextResource, true, false, nextOutcome.getEntity(), nextResource.getIdElement(), nextOutcome.getPreviousResource(), theTransactionDetails);
				} else if (!nonUpdatedEntities.contains(nextOutcome.getEntity())) {
					jpaDao.updateEntity(theRequest, nextResource, nextOutcome.getEntity(), deletedTimestampOrNull, true, false, theTransactionDetails, false, true);
				}
			}

			theTransactionStopWatch.endCurrentTask();
			theTransactionStopWatch.startTask("Flush writes to database");

			flushSession(theIdToPersistedOutcome);

			theTransactionStopWatch.endCurrentTask();
			if (conditionalRequestUrls.size() > 0) {
				theTransactionStopWatch.startTask("Check for conflicts in conditional resources");
			}

			/*
			 * Double check we didn't allow any duplicates we shouldn't have
			 */
			for (Map.Entry<String, Class<? extends IBaseResource>> nextEntry : conditionalRequestUrls.entrySet()) {
				String matchUrl = nextEntry.getKey();
				Class<? extends IBaseResource> resType = nextEntry.getValue();
				if (isNotBlank(matchUrl)) {
					Set<ResourcePersistentId> val = myMatchResourceUrlService.processMatchUrl(matchUrl, resType, theRequest);
					if (val.size() > 1) {
						throw new InvalidRequestException(
							"Unable to process " + theActionName + " - Request would cause multiple resources to match URL: \"" + matchUrl + "\". Does transaction request contain duplicates?");
					}
				}
			}

			theTransactionStopWatch.endCurrentTask();

			for (IIdType next : theAllIds) {
				IIdType replacement = theIdSubstitutions.get(next);
				if (replacement == null) {
					continue;
				}
				if (replacement.equals(next)) {
					continue;
				}
				ourLog.debug("Placeholder resource ID \"{}\" was replaced with permanent ID \"{}\"", next, replacement);
			}

			ListMultimap<Pointcut, HookParams> deferredBroadcastEvents = theTransactionDetails.endAcceptingDeferredInterceptorBroadcasts();
			for (Map.Entry<Pointcut, HookParams> nextEntry : deferredBroadcastEvents.entries()) {
				Pointcut nextPointcut = nextEntry.getKey();
				HookParams nextParams = nextEntry.getValue();
				JpaInterceptorBroadcaster.doCallHooks(myInterceptorBroadcaster, theRequest, nextPointcut, nextParams);
			}

			return entriesToProcess;

		} finally {
			if (theTransactionDetails.isAcceptingDeferredInterceptorBroadcasts()) {
				theTransactionDetails.endAcceptingDeferredInterceptorBroadcasts();
			}
		}
	}

	protected abstract void flushSession(Map<IIdType, DaoMethodOutcome> theIdToPersistedOutcome);

	private void validateResourcePresent(IBaseResource theResource, Integer theOrder, String theVerb) {
		if (theResource == null) {
			String msg = myContext.getLocalizer().getMessage(TransactionProcessor.class, "missingMandatoryResource", theVerb, theOrder);
			throw new InvalidRequestException(msg);
		}
	}

	private IIdType newIdType(String theResourceType, String theResourceId, String theVersion) {
		org.hl7.fhir.r4.model.IdType id = new org.hl7.fhir.r4.model.IdType(theResourceType, theResourceId, theVersion);
		return myContext.getVersion().newIdType().setValue(id.getValue());
	}

	private IIdType newIdType(String theToResourceName, String theIdPart) {
		return newIdType(theToResourceName, theIdPart, null);
	}

	private IFhirResourceDao getDaoOrThrowException(Class<? extends IBaseResource> theClass) {
		IFhirResourceDao<? extends IBaseResource> dao = myDaoRegistry.getResourceDaoOrNull(theClass);
		if (dao == null) {
			Set<String> types = new TreeSet<>(myDaoRegistry.getRegisteredDaoTypes());
			String type = myContext.getResourceType(theClass);
			String msg = myContext.getLocalizer().getMessage(BaseTransactionProcessor.class, "unsupportedResourceType", type, types.toString());
			throw new InvalidRequestException(msg);
		}
		return dao;
	}

	private String toResourceName(Class<? extends IBaseResource> theResourceType) {
		return myContext.getResourceType(theResourceType);
	}

	public void setContext(FhirContext theContext) {
		myContext = theContext;
	}

	private String extractTransactionUrlOrThrowException(IBase nextEntry, String verb) {
		String url = myVersionAdapter.getEntryRequestUrl(nextEntry);
		if (isBlank(url)) {
			throw new InvalidRequestException(myContext.getLocalizer().getMessage(BaseHapiFhirSystemDao.class, "transactionMissingUrl", verb));
		}
		return url;
	}

	private IFhirResourceDao<? extends IBaseResource> toDao(UrlUtil.UrlParts theParts, String theVerb, String theUrl) {
		RuntimeResourceDefinition resType;
		try {
			resType = myContext.getResourceDefinition(theParts.getResourceType());
		} catch (DataFormatException e) {
			String msg = myContext.getLocalizer().getMessage(BaseHapiFhirSystemDao.class, "transactionInvalidUrl", theVerb, theUrl);
			throw new InvalidRequestException(msg);
		}
		IFhirResourceDao<? extends IBaseResource> dao = null;
		if (resType != null) {
			dao = myDaoRegistry.getResourceDao(resType.getImplementingClass());
		}
		if (dao == null) {
			String msg = myContext.getLocalizer().getMessage(BaseHapiFhirSystemDao.class, "transactionInvalidUrl", theVerb, theUrl);
			throw new InvalidRequestException(msg);
		}

		// if (theParts.getResourceId() == null && theParts.getParams() == null) {
		// String msg = getContext().getLocalizer().getMessage(BaseHapiFhirSystemDao.class, "transactionInvalidUrl", theVerb, theUrl);
		// throw new InvalidRequestException(msg);
		// }

		return dao;
	}

	private String toMatchUrl(IBase theEntry) {
		String verb = myVersionAdapter.getEntryRequestVerb(myContext, theEntry);
		if (verb.equals("POST")) {
			return myVersionAdapter.getEntryIfNoneExist(theEntry);
		}
		if (verb.equals("PATCH")) {
			return myVersionAdapter.getEntryRequestIfMatch(theEntry);
		}
		if (verb.equals("PUT") || verb.equals("DELETE")) {
			String url = extractTransactionUrlOrThrowException(theEntry, verb);
			UrlUtil.UrlParts parts = UrlUtil.parseUrl(url);
			if (isBlank(parts.getResourceId())) {
				return parts.getResourceType() + '?' + parts.getParams();
			}
		}
		return null;
	}

	public interface ITransactionProcessorVersionAdapter<BUNDLE extends IBaseBundle, BUNDLEENTRY extends IBase> {

		void setResponseStatus(BUNDLEENTRY theBundleEntry, String theStatus);

		void setResponseLastModified(BUNDLEENTRY theBundleEntry, Date theLastModified);

		void setResource(BUNDLEENTRY theBundleEntry, IBaseResource theResource);

		IBaseResource getResource(BUNDLEENTRY theBundleEntry);

		String getBundleType(BUNDLE theRequest);

		void populateEntryWithOperationOutcome(BaseServerResponseException theCaughtEx, BUNDLEENTRY theEntry);

		BUNDLE createBundle(String theBundleType);

		List<BUNDLEENTRY> getEntries(BUNDLE theRequest);

		void addEntry(BUNDLE theBundle, BUNDLEENTRY theEntry);

		BUNDLEENTRY addEntry(BUNDLE theBundle);

		String getEntryRequestVerb(FhirContext theContext, BUNDLEENTRY theEntry);

		String getFullUrl(BUNDLEENTRY theEntry);

		String getEntryIfNoneExist(BUNDLEENTRY theEntry);

		String getEntryRequestUrl(BUNDLEENTRY theEntry);

		void setResponseLocation(BUNDLEENTRY theEntry, String theResponseLocation);

		void setResponseETag(BUNDLEENTRY theEntry, String theEtag);

		String getEntryRequestIfMatch(BUNDLEENTRY theEntry);

		String getEntryRequestIfNoneExist(BUNDLEENTRY theEntry);

		String getEntryRequestIfNoneMatch(BUNDLEENTRY theEntry);

		void setResponseOutcome(BUNDLEENTRY theEntry, IBaseOperationOutcome theOperationOutcome);

		void setRequestVerb(BUNDLEENTRY theEntry, String theVerb);

		void setRequestUrl(BUNDLEENTRY theEntry, String theUrl);
	}

	/**
	 * Transaction Order, per the spec:
	 * <p>
	 * Process any DELETE interactions
	 * Process any POST interactions
	 * Process any PUT interactions
	 * Process any PATCH interactions
	 * Process any GET interactions
	 */
	//@formatter:off
	public class TransactionSorter implements Comparator<IBase> {

		private final Set<String> myPlaceholderIds;

		public TransactionSorter(Set<String> thePlaceholderIds) {
			myPlaceholderIds = thePlaceholderIds;
		}

		@Override
		public int compare(IBase theO1, IBase theO2) {
			int o1 = toOrder(theO1);
			int o2 = toOrder(theO2);

			if (o1 == o2) {
				String matchUrl1 = toMatchUrl(theO1);
				String matchUrl2 = toMatchUrl(theO2);
				if (isBlank(matchUrl1) && isBlank(matchUrl2)) {
					return 0;
				}
				if (isBlank(matchUrl1)) {
					return -1;
				}
				if (isBlank(matchUrl2)) {
					return 1;
				}

				boolean match1containsSubstitutions = false;
				boolean match2containsSubstitutions = false;
				for (String nextPlaceholder : myPlaceholderIds) {
					if (matchUrl1.contains(nextPlaceholder)) {
						match1containsSubstitutions = true;
					}
					if (matchUrl2.contains(nextPlaceholder)) {
						match2containsSubstitutions = true;
					}
				}

				if (match1containsSubstitutions && match2containsSubstitutions) {
					return 0;
				}
				if (!match1containsSubstitutions && !match2containsSubstitutions) {
					return 0;
				}
				if (match1containsSubstitutions) {
					return 1;
				} else {
					return -1;
				}
			}

			return o1 - o2;
		}

		private int toOrder(IBase theO1) {
			int o1 = 0;
			if (myVersionAdapter.getEntryRequestVerb(myContext, theO1) != null) {
				switch (myVersionAdapter.getEntryRequestVerb(myContext, theO1)) {
					case "DELETE":
						o1 = 1;
						break;
					case "POST":
						o1 = 2;
						break;
					case "PUT":
						o1 = 3;
						break;
					case "PATCH":
						o1 = 4;
						break;
					case "GET":
						o1 = 5;
						break;
					default:
						o1 = 0;
						break;
				}
			}
			return o1;
		}

	}

	private static class BaseServerResponseExceptionHolder {
		private BaseServerResponseException myException;

		public BaseServerResponseException getException() {
			return myException;
		}

		public void setException(BaseServerResponseException myException) {
			this.myException = myException;
		}
	}

	public static boolean isPlaceholder(IIdType theId) {
		if (theId != null && theId.getValue() != null) {
			return theId.getValue().startsWith("urn:oid:") || theId.getValue().startsWith("urn:uuid:");
		}
		return false;
	}

	private static String toStatusString(int theStatusCode) {
		return theStatusCode + " " + defaultString(Constants.HTTP_STATUS_NAMES.get(theStatusCode));
	}

}


text:
<?php
	include_once 'inc/connect_db.php';

    $id=$_REQUEST["id"];

    // Verifica se já existe uma imagem, se sim deleta.
    $sql_deleta_imagem="SELECT ftp_imagem FROM fotos_servicos WHERE ftp_ser_id=".$id;
    $result_deleta_imagem = mysqli_query($mysqli, $sql_deleta_imagem);
    while ($row_deleta_imagem= mysqli_fetch_array($result_deleta_imagem)){

    	if($row_deleta_imagem["ftp_imagem"]!=''){
        	$filename="../img/servicos/".$row_deleta_imagem["ftp_imagem"];
        	unlink($filename);
    	}
    }
    $sqltxt_o = "DELETE FROM fotos_servicos WHERE ftp_ser_id=".$id;
    $sql_o = mysqli_query($mysqli, $sqltxt_o);

    $sqltxt = "DELETE FROM servicos WHERE ser_id=".$id;
    $sql = mysqli_query($mysqli, $sqltxt);

    echo "<script type=text/javascript>alert('Cadastro excluído com sucesso!')</script>";
    echo "<script type=text/javascript>window.location.href = 'menu.php?sub=servicos';</script>";

?>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Respect\Http;

interface Reasonable
{

}


text:
#Region "Microsoft.VisualBasic::7a249eb4788ef16b6403ce970e7ee91a, src\assembly\assembly\MarkupData\mzML\RawScanParser.vb"

    ' Author:
    '
    '       xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
    '
    ' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
    '
    '
    ' MIT License
    '
    '
    ' Permission is hereby granted, free of charge, to any person obtaining a copy
    ' of this software and associated documentation files (the "Software"), to deal
    ' in the Software without restriction, including without limitation the rights
    ' to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    ' copies of the Software, and to permit persons to whom the Software is
    ' furnished to do so, subject to the following conditions:
    '
    ' The above copyright notice and this permission notice shall be included in all
    ' copies or substantial portions of the Software.
    '
    ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    ' IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    ' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    ' AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    ' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    ' OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    ' SOFTWARE.

    ' /********************************************************************************/

    ' Summaries:

    '     Class RawScanParser
    '
    '         Function: hasFileContent, IsMRMData, IsSIMData
    '
    '
    ' /********************************************************************************/

#End Region

Imports System.Runtime.CompilerServices
Imports Microsoft.VisualBasic.Text.Xml.Linq

Namespace MarkupData.mzML

    Public Class RawScanParser

        Public Const SRMSignature As String = "selected reaction monitoring chromatogram"
        Public Const SIMSignature As String = "selected ion monitoring chromatogram"

        ''' <summary>
        ''' GCMS SIM
        ''' </summary>
        ''' <param name="mzml"></param>
        ''' <returns></returns>
        <MethodImpl(MethodImplOptions.AggressiveInlining)>
        Public Shared Function IsSIMData(mzml As String) As Boolean
            Return hasFileContent(mzml, SIMSignature)
        End Function

        Public Shared Function hasFileContent(mzml As String, contentSig As String) As Boolean
            For Each content As fileDescription In mzml.LoadXmlDataSet(Of fileDescription)(, xmlns:=indexedmzML.xmlns)
                If content.fileContent IsNot Nothing AndAlso Not content.fileContent.cvParams.IsNullOrEmpty Then
                    If content.fileContent.cvParams.Any(Function(a) a.name = contentSig) Then
                        Return True
                    Else
                        Return False
                    End If
                End If
            Next

            Return False
        End Function

        ''' <summary>
        ''' LCMSMS MRM
        ''' </summary>
        ''' <param name="mzml"></param>
        ''' <returns></returns>
        <MethodImpl(MethodImplOptions.AggressiveInlining)>
        Public Shared Function IsMRMData(mzml As String) As Boolean
            Return hasFileContent(mzml, SRMSignature)
        End Function
    End Class
End Namespace


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
    Linux on Hyper-V and Azure Test Code, ver. 1.0.0
    Copyright (c) Microsoft Corporation
    All rights reserved.
    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
    THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
    OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
    ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
    PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
    See the Apache Version 2.0 License for specific language governing
    permissions and limitations under the License.
-->

<config>
    <global>
        <logfileRootDir>TestResults</logfileRootDir>
        <defaultSnapshot>ICABase</defaultSnapshot>
        <LisaInitScript>
            <file>.\setupScripts\CreateVMs.ps1</file>
        </LisaInitScript>
        <imageStoreDir>\\unc\path</imageStoreDir>
        <email>
            <recipients>
                <to>myboss@mycompany.com</to>
                <to>myself@mycompany.com</to>
            </recipients>
            <sender>myself@mycompany.com</sender>
            <subject>KVP and SQM Test Run</subject>
            <smtpServer>mysmtphost.mycompany.com</smtpServer>
        </email>
        <!-- Optional testParams go here -->
    </global>

    <testSuites>
        <suite>
            <suiteName>KVP</suiteName>
            <suiteTests>
                <suiteTest>SQM_Basic</suiteTest>
                <suiteTest>KVP_Basic</suiteTest>
                <suiteTest>ReadKVPData_BasicTest</suiteTest>
                <suiteTest>KVP_Add_Key_Values</suiteTest>
                <suiteTest>KVP_Modify_Key_Values</suiteTest>
                <suiteTest>KVP_Remove_Key_Values</suiteTest>
                <suiteTest>KVP_Push_Key_Values</suiteTest>
                <suiteTest>KVP_DeleteNonExistKVPOnGuest</suiteTest>
                <suiteTest>KVP_ModifyNonExistKVPOnGuest</suiteTest>
                <suiteTest>KVP_VerifyHostInjectedItems</suiteTest>
                <suiteTest>KVP_TestRescind</suiteTest>
                <suiteTest>KVP_Max_Read</suiteTest>
            </suiteTests>
        </suite>
    </testSuites>

    <testCases>
        <test>
            <testName>SQM_Basic</testName>
            <testScript>SetupScripts\SQM_Basic.ps1</testScript>
            <timeout>600</timeout>
            <onError>Continue</onError>
            <noReboot>False</noReboot>
            <testparams>
                <param>TC_COVERED=SQM-01</param>
            </testparams>
        </test>

        <test>
            <testName>KVP_Basic</testName>
            <testScript>SetupScripts\KVP_Basic.ps1</testScript>
            <timeout>600</timeout>
            <onError>Continue</onError>
            <noReboot>True</noReboot>
            <testparams>
                <param>TC_COVERED=KVP-01</param>
            </testparams>
        </test>

        <test>
            <testName>ReadKVPData_BasicTest</testName>
            <testScript>KVP_BasicTest.sh</testScript>
            <files>remote-scripts\ica\KVP_BasicTest.sh,remote-scripts/ica/utils.sh,
                tools/KVP/kvp_client64,tools/KVP/kvp_client32</files>
            <timeout>600</timeout>
            <onError>Continue</onError>
            <noReboot>False</noReboot>
            <testparams>
                <param>TC_COVERED=BVT-21</param>
            </testparams>
        </test>

        <test>
            <testName>KVP_Add_Key_Values</testName>
            <testScript>KVP_VerifyKeyValue.sh</testScript>
            <files>remote-scripts\ica\KVP_VerifyKeyValue.sh,
                tools/KVP/kvp_client32,tools/KVP/kvp_client64</files>
            <PreTest>setupScripts\AddKeyValue.ps1</PreTest>
            <timeout>600</timeout>
            <onError>Continue</onError>
            <noReboot>True</noReboot>
            <testparams>
                <param>TC_COVERED=KVP-02</param>
                <param>Key=EEE</param>
                <param>Value=555</param>
                <param>Pool=0</param>
            </testparams>
        </test>

        <test>
            <testName>KVP_Modify_Key_Values</testName>
            <testScript>KVP_VerifyKeyValue.sh</testScript>
            <files>remote-scripts\ica\KVP_VerifyKeyValue.sh,
                tools/KVP/kvp_client32,tools/KVP/kvp_client64</files>
            <preTest>setupscripts\ModifyKeyValue.ps1</preTest>
            <timeout>600</timeout>
            <onError>Continue</onError>
            <noReboot>True</noReboot>
            <testparams>
                <param>TC_COVERED=KVP-03</param>
                <param>Key=EEE</param>
                <param>Value=999</param>
                <param>Pool=0</param>
            </testparams>
        </test>

        <test>
            <testName>KVP_Remove_Key_Values</testName>
            <testScript>setupscripts\KVP_DeleteKeyValue.ps1</testScript>
            <timeout>600</timeout>
            <onError>Continue</onError>
            <noReboot>True</noReboot>
            <testparams>
                <param>TC_COVERED=KVP-04</param>
                <param>Key=EEE</param>
                <param>Value=999</param>
                <param>Pool=0</param>
            </testparams>
        </test>

        <test>
            <testName>KVP_Push_Key_Values</testName>
            <testScript>setupscripts\KVP_VerifyGuestCreatedItem.ps1</testScript>
            <files>tools/KVP/kvp_client32,tools/KVP/kvp_client64</files>
            <timeout>600</timeout>
            <onError>Abort</onError>
            <noReboot>True</noReboot>
            <testparams>
                <param>TC_COVERED=KVP-05</param>
                <param>Key=BBB</param>
                <param>Value=111</param>
            </testparams>
        </test>

        <test>
                <testName>KVP_DeleteNonExistKVPOnGuest</testName>
                <testScript>setupscripts\KVP_DeleteNonExistKeyValue.ps1</testScript>
                <timeout>600</timeout>
                <onError>Abort</onError>
                <noReboot>True</noReboot>
                <testparams>
                        <param>TC_COVERED=KVP-06</param>
                        <param>Key=AAA</param>
                        <param>Value=000</param>
                        <param>Pool=0</param>
                </testparams>
        </test>

        <test>
                <testName>KVP_ModifyNonExistKVPOnGuest</testName>
                <testScript>setupscripts\KVP_ModifyNonExistKeyValue.ps1</testScript>
                <timeout>600</timeout>
                <onError>Abort</onError>
                <noReboot>True</noReboot>
                <testparams>
                        <param>TC_COVERED=KVP-07</param>
                        <param>Key=AAA</param>
                        <param>Value=000</param>
                        <param>Pool=0</param>
                </testparams>
        </test>

        <test>
            <testName>KVP_VerifyHostInjectedItems</testName>
            <testScript>KVP_VerifyHostInjectedItems.sh</testScript>
            <files>remote-scripts\ica\KVP_VerifyHostInjectedItems.sh,
                tools/KVP/kvp_client32,tools/KVP/kvp_client64</files>
            <timeout>600</timeout>
            <onError>Abort</onError>
            <noReboot>True</noReboot>
            <testparams>
                <param>TC_COVERED=KVP-10</param>
                <param>Pool=3</param>
                <param>Items=11</param>
            </testparams>
        </test>

        <test>
            <testName>KVP_TestRescind</testName>
            <testScript>SetupScripts\KVP_TestRescind.ps1</testScript>
            <timeout>600</timeout>
            <onError>Continue</onError>
            <noReboot>False</noReboot>
            <testparams>
                <param>TC_COVERED=KVP-11</param>
                <!-- Number of times to disable and reenable the KVP service -->
                <param>CycleCount=20</param>
            </testparams>
        </test>

        <test>
            <testName>KVP_Max_Read</testName>
            <testScript>SetupScripts\Kvp_Max_Read.ps1</testScript>
            <files>tools/KVP/kvp_client64, tools/KVP/kvp_client32</files>
            <timeout>600</timeout>
            <onError>Continue</onError>
            <noReboot>True</noReboot>
            <testparams>
                <param>TC_COVERED=KVP-12</param>
                <param>Pool=1</param>
                <!-- Number of key pairs to be added in the kvp pool -->
                <param>Entries=250</param>
            </testparams>
        </test>
    </testCases>

    <VMs>
        <vm>
            <hvServer>localhost</hvServer>
            <vmName>VM_NAME</vmName>
            <os>Linux</os>
            <ipv4></ipv4>
            <sshKey>rhel5_id_rsa.ppk</sshKey>
            <suite>KVP</suite>
            <hardware>
                <create>true</create>
                <numCPUs>4</numCPUs>
                <memSize>2048</memSize>
                <disableDiff>True</disableDiff>
                <generation>1</generation>
                <nic>VMBus,External</nic>
            </hardware>
        </vm>
    </VMs>

</config>


text:
import {iocProvide} from "../Container";
import {EventEmitter} from "../ioc/wrapper/EventEmitter";
//
@iocProvide(UtilState)
export class UtilState extends EventEmitter {

	/**
	 * current state
	 */
	private current : number = -1;

	/**
	 * constructor method
	 */
	constructor() {
		super();
	}

	/**
	 * set state
	 */
	public set(state: number) : void {
		if(this.current !== state) {
			this.current = state;
			//emit event
			this.emit("change");
		}
	}
}


text:
var time = {"hour":0, "min":0, "sec":0};
var myTimer;

//Increments and updates the timer everytime it is called
function timer(){
	if (time["sec"] < 60)
		time["sec"]++;
	else if (time["sec"] == 60)
	{
		time["sec"] = 0;
		time["min"]++;
		if (time["min"] == 60)
		{
			time["min"] = 0;
			time["hour"]++;
		}
	}
	updateTimer(getTime());
}

//Stops the timer
function stopTimer(){
	clearInterval(myTimer);
}

//Gets the time in the correct format
function getTime(){
	return time["hour"]+":"+time["min"]+":"+time["sec"];
}

//Resets time to 00:00:00
function resetTimer(){
	time = {"hour":0, "min":0, "sec":0};
	updateTimer(getTime());
}

//Updates the time on the UI
function updateTimer(time)
{
	$("#timer").html("
"+time+"s
");
}

//Updates the % correctness in UI
function updateCorrectness(perCorrect)
{
	$("#correct").html("
"+perCorrect+"% Correct
");
}

//Update the % accuracy needed in UI based on given img
function updateAcc(img)
{
	slackVal = ACCVALS[img];
	$("#acc-needed").html("
Accuracy Needed: "+ slackVal + "%
");
}

//Update html display in UI
function updateHtml(html)
{
	$("#result").html(strip(html));
}

//Update the goal image in UI
function updateGoal(img)
{
	if (img == "goal")
		$("#goalimage").attr("src", goalImgSrc);
	else if (img == "mismatch")
		$("#goalimage").attr("src", misMatchSrc);
}

//Change start button from Start/Submit/Restart
function updateButton(btn)
{
	if (btn == "start")
		$("#start").html('<button type="button" onclick="start()" class="btn btn-success">START</button>');
	else if (btn == "submit")
		$("#start").html('<button type="button" onclick="submit()" class="btn btn-primary">SUBMIT</button>');
	else if (btn == "restart")
		$("#start").html('<button type="button" onclick="start()" class="btn btn-success">RESTART</button>');
}

//Change area from Title/TextArea/Highscores
function updateArea(type)
{
	if (type == "title")
		$("#left-content").html('

Push Start to begin
');
	else if (type == "textarea")
		$("#left-content").html('<textarea id ="text-input" border="3" rows="28" cols="95" name="input" ><!DOCTYPE html>\n\n\n\n\n\n\n\n</textarea>');
	else if (type == "highscores")
	{
		$("#left-content").html("");
		$("#score").val(getTime());

		$("#score-form").submit();
	}
}


text:
/**************************************************************************************************************************
* EventBox Class
* Inherit from this class,  it provides register clients and trigger event on each clients' related function.
* @constructor
* @this {EventBox}
* @author Brian Chen
*/
function EventBox() {
    this.clients = {};
    this.events = {};
}

/**
* trigger a event on a client or all clients or @this
* @this {EventBox}
* @param {string|null|this} a client name, or null to specify all clients, or this object to trigger on self events.
* @param {string} event name
* @param {...*} aditional event arguments
* @return {*} client event result
*/
EventBox.prototype.trigger = function (clientName, eventName) {
    if (!eventName || typeof eventName !== 'string') throw 'Invalid eventName!';
    var args = Array.prototype.slice.call(arguments, 2);
    if (clientName === this) {
        var handlers = this.events[eventName];
        if (handlers && handlers.length) {
            for (var i = 0; i < handlers.length; i++) {
                handlers[i].apply(this, args);
            }
        }
        return true;
    } else if (clientName === null) {
        for (var key in this.clients) {
            var target = this.clients.hasOwnProperty(key) && this.clients[key],
                fn = target && target[eventName];
            if (typeof fn === 'function') fn.apply(target, args);
        }
        return true;
    } else if (typeof clientName === 'string'){
        var client = this.clients[clientName],
            event = client && client[eventName];
        if (typeof event === 'function') return event.apply(client, args);
        return false;
    } else {
		throw 'Invalid clientName!';
	}
};

/**
* register client
* @param {string} clientName
* @param {object} client object with event receivers
*/
EventBox.prototype.register = function (clientName, client) {
    if (!clientName || typeof clientName !== 'string') throw 'Invalid clientName!';
    this.clients[clientName] = client;
};

/**
* bind event receiver on @this
* @this {EventBox}
* @param {string} eventName
* @param {function} event receiver
*/
EventBox.prototype.on = function (eventName, callback) {
    if (!eventName || typeof eventName !== 'string') throw 'Invalid eventName!';
    if (typeof callback !== 'function') throw 'Invalid callback function!';
    if (!this.events[eventName]) this.events[eventName] = [callback];
    else this.events[eventName].push(callback);
};


text:
package org.hisp.dhis.query;

import org.hisp.dhis.schema.Schema;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author Morten Olav Hansen <mortenoh@gmail.com>
 */
public abstract class Criteria
{
    protected List<Criterion> criterions = new ArrayList<>();

    protected Set<String> aliases = new HashSet<>();

    protected final Schema schema;

    public Criteria( Schema schema )
    {
        this.schema = schema;
    }

    public List<Criterion> getCriterions()
    {
        return criterions;
    }

    public Set<String> getAliases()
    {
        return aliases;
    }

    public Criteria add( Criterion criterion )
    {
        if ( !Restriction.class.isInstance( criterion ) )
        {
            this.criterions.add( criterion ); // if conjunction/disjunction just add it and move forward
            return this;
        }

        Restriction restriction = (Restriction) criterion;

        this.criterions.add( restriction );

        return this;
    }

    public Criteria add( Criterion... criterions )
    {
        for ( Criterion criterion : criterions )
        {
            add( criterion );
        }

        return this;
    }

    public Criteria add( Collection<Criterion> criterions )
    {
        criterions.forEach( this::add );
        return this;
    }
}


text:
from thumbor.context import Context, ServerParameters
from thumbor.config import Config
from thumbor.importer import Importer

from pyvows import Vows, expect
ctx = Vows.Context

import thumbor.engines.pil as PIL
from os.path import join, abspath, dirname

FIXTURES_FOLDER = join(abspath(dirname(__file__)), 'fixtures')

class MockImage:
    def __init__(self, mode, width, height):
        self.mode = mode
        self.width = width
        self.height = height
        self.calls = []

    def convert(self, mode):
        self.calls.append('convert')
        self.mode = mode
        return self

    def resize(self, size, filter):
        self.calls.append('resize')
        self.width = size[0]
        self.height = size[1]
        return self

@Vows.batch
class PilEngineVows(ctx):

    class ReadingJpegImage(ctx):
        def topic(self):
            config = Config()
            server = ServerParameters(
                8889, 'localhost', 'thumbor.conf', None, 'info', None
            )

            context = Context(server, config, Importer(config))

            with open("%s/quantization.jpg" % FIXTURES_FOLDER, "rb") as f:
                buffer = f.read()

            engine = PIL.Engine(context=context)
            engine.load(buffer, '.jpg')

            return engine

        def should_store_subsampling_in_engine(self, engine):
            # "Possible subsampling values are 0, 1 and 2 that correspond to 4:4:4, 4:2:2
            # and 4:1:1 (or 4:2:0?)." (PIL/JpegPresets.py)
            expect(engine.subsampling).to_equal(0)

        def should_store_quantization_in_engine(self, engine):
            expect(len(engine.qtables)).to_equal(2)

    class WritingJpegImage(ctx):
        def topic(self):
            config = Config()
            server = ServerParameters(
                8889, 'localhost', 'thumbor.conf', None, 'info', None
            )
            config.PILLOW_COPY_JPEG_SETTINGS = True
            context = Context(server, config, Importer(config))

            with open("%s/quantization.jpg" % FIXTURES_FOLDER, "rb") as f:
                buffer = f.read()

            engine = PIL.Engine(context=context)
            engine.load(buffer, '.jpg')
            engine.read('.jpg', None)

            return engine.image

        def should_save_with_stored_subsampling_if_quality_is_None(self, image):
            expect(image.encoderinfo.get('subsampling')).to_equal(0)

        def should_save_with_stored_qtables_if_quality_is_None(self, image):
            expect(len(image.encoderinfo.get('qtables'))).to_equal(2)

    class ResizedPaletteImage(ctx):
        def topic(self):
            engine = PIL.Engine(None)
            engine.image = MockImage('P', 640, 480)
            engine.resize(320, 240)
            return engine.image

        def should_convert_p_to_rgba(self, image):
            expect(image.mode).to_equal('RGBA')
            expect((image.width, image.height)).to_equal((320, 240))
            expect(image.calls.index('convert') < image.calls.index('resize')).to_be_true()

    class ResizedNonPaletteImage(ctx):
        def topic(self):
            engine = PIL.Engine(None)
            engine.image = MockImage('other', 640, 480)
            engine.resize(160, 120)
            return engine.image

        def should_not_convert_non_palette_images(self, image):
            expect(image.mode).to_equal('other')  # unchanged
            expect((image.width, image.height)).to_equal((160, 120))
            expect(image.calls).Not.to_include(['convert'])

    class ShouldRaiseIfFiltersNotAvailable(ctx):
        @Vows.capture_error
        def topic(self):
            FILTERS_AVAILABLE_BAK = PIL.FILTERS_AVAILABLE
            PIL.FILTERS_AVAILABLE = False
            engine = PIL.Engine(None)
            try:
                return engine.paste(None, None, True)
            finally:
                PIL.FILTERS_AVAILABLE = FILTERS_AVAILABLE_BAK

        def should_be_an_error(self, topic):
            expect(topic).to_be_an_error()
            expect(topic).to_be_an_error_like(RuntimeError)
            expected = 'You need filters enabled to use paste with merge. Please reinstall thumbor with proper ' + \
                'compilation of its filters.'
            expect(topic).to_have_an_error_message_of(expected)


text:
'use strict';

let router = require('express').Router();
let config = require('config');

router.get('/applicable-sales-tax', function(req, res) {
  res.json(config.applicableSalesTax);
});

module.exports = router;


text:
"""
Test bundle for the log service

:author: Thomas Calmant
"""

# iPOPO
from pelix.ipopo.decorators import ComponentFactory, Requires

# Log service
from pelix.misc import LOG_SERVICE

# ------------------------------------------------------------------------------

__version__ = (1, 0, 0)

SIMPLE_FACTORY = "log.test.simple"

# ------------------------------------------------------------------------------
# Auto-instantiated component (tests the decorator)

@ComponentFactory(SIMPLE_FACTORY)
@Requires("logger", LOG_SERVICE)
class LoggerComponent(object):
    """
    Dummy instantiated component
    """
    def log(self, level, message):
        """
        Logs something

        :param level: Log level
        :param message: Log message
        """
        self.logger.log(level, message)

    @staticmethod
    def remove_name():
        """
        Removes __name__ from globals
        """
        del globals()['__name__']


text:
<?php
namespace Admin\Model;

// Add these import statements
use Zend\Db\TableGateway\TableGateway;

class AdminTable
{
    protected $tableGateway;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    public function checkLogin($username, $password)
    {
        $rowset = $this->tableGateway->select(array('username' => $username,'password' => md5($password)));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row record");
        }
        return row;
    }

    public function getUser($id)
    {
        $id  = (int) $id;
        $rowset = $this->tableGateway->select(array('user_id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function deleteAlbum($id)
    {
        $this->tableGateway->delete(array('user_id' => $id));
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.SecurityDevOps.Models
{
    public partial class AzureDevOpsOrgMetadata : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            if (Optional.IsDefined(AutoDiscovery))
            {
                writer.WritePropertyName("autoDiscovery");
                writer.WriteStringValue(AutoDiscovery.Value.ToString());
            }
            if (Optional.IsCollectionDefined(Projects))
            {
                writer.WritePropertyName("projects");
                writer.WriteStartArray();
                foreach (var item in Projects)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
        }

        internal static AzureDevOpsOrgMetadata DeserializeAzureDevOpsOrgMetadata(JsonElement element)
        {
            Optional<string> name = default;
            Optional<AutoDiscovery> autoDiscovery = default;
            Optional<IList<AzureDevOpsProjectMetadata>> projects = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("autoDiscovery"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    autoDiscovery = new AutoDiscovery(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("projects"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<AzureDevOpsProjectMetadata> array = new List<AzureDevOpsProjectMetadata>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(AzureDevOpsProjectMetadata.DeserializeAzureDevOpsProjectMetadata(item));
                    }
                    projects = array;
                    continue;
                }
            }
            return new AzureDevOpsOrgMetadata(name.Value, Optional.ToNullable(autoDiscovery), Optional.ToList(projects));
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
  ~ Copyright 2013-2015 The GDG Frisbee Project
  ~
  ~ 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.
-->

<android.support.v4.widget.DrawerLayout
  android:id="@+id/drawer"
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:card_view="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:fitsSystemWindows="true"
  android:orientation="vertical">

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/toolbar_actionbar" />

    <LinearLayout
      android:baselineAligned="false"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="horizontal">

      <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3" />

      <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:orientation="vertical"
        android:paddingLeft="@dimen/keyline_1_minus_12dp"
        android:paddingRight="@dimen/keyline_1_minus_12dp">

        <ImageView
          android:id="@+id/special_logo"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="center_horizontal"
          android:padding="@dimen/keyline_1"
          tools:src="@drawable/ic_ioextended"
          tools:ignore="InconsistentLayout"/>

        <android.support.v7.widget.CardView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          card_view:cardCornerRadius="2dp"
          card_view:cardElevation="4dp"
          card_view:cardUseCompatPadding="true">

          <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
              android:id="@+id/special_description"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:padding="@dimen/keyline_1"
              tools:text="@string/ioextended_description"
              tools:ignore="InconsistentLayout" />
          </ScrollView>
        </android.support.v7.widget.CardView>

      </LinearLayout>

    </LinearLayout>

  </LinearLayout>

  <include layout="@layout/navdrawer" />

</android.support.v4.widget.DrawerLayout>


text:
namespace Ui {
class WelcomeWidget;
}

namespace Multitrack {

class WelcomeWidget : public QWidget {
  Q_OBJECT

public:
  explicit WelcomeWidget(QWidget *parent = 0);
  ~WelcomeWidget();

  void UpdateRecentProjects(const QVector<RecentProject> &recent_projects);

signals:
  void New();
  void Open();
  void RecentProjectChosen(int index);

private slots:
  void on_tableWidgetRecent_doubleClicked(const QModelIndex &index);

private:
  Ui::WelcomeWidget *ui;
  QWidget *parent_;
};

}  // namespace Multitrack

#endif  // MULTITRACK_WELCOMEWIDGET_H


text:
import os
import shlex

import pytest
from nbformat.v4.nbbase import new_code_cell, new_notebook

import jupytext
from jupytext.cli import jupytext as jupytext_cli

from .utils import requires_black, requires_myst, requires_user_kernel_python3

doc_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "docs")

@requires_user_kernel_python3
@requires_black
@requires_myst
@pytest.mark.skipif(
    not os.path.isdir(doc_path), reason="Documentation folder is missing"
)
def test_jupytext_commands_in_the_documentation_work(tmpdir):
    # Read the documentation as a bash notebook
    using_cli = os.path.join(doc_path, "using-cli.md")
    assert os.path.isfile(using_cli)
    using_cli_nb = jupytext.read(using_cli)

    # Run the commands in tmpdir on a sample notebook
    jupytext.write(
        new_notebook(cells=[new_code_cell("1+1")]), str(tmpdir.join("notebook.ipynb"))
    )
    os.chdir(str(tmpdir))

    cmd_tested = 0
    for cell in using_cli_nb.cells:
        if cell.cell_type != "code":
            continue
        if not cell.source.startswith("jupytext"):
            continue
        for cmd in cell.source.splitlines():
            if not cmd.startswith("jupytext"):
                continue

            # Do not test commands that involve reading a notebook from stdin
            if "read ipynb from stdin" in cmd:
                continue

            # We can't run pytest inside pytest
            if "pytest {}" in cmd:
                continue

            # We need to remove the comments that may follow the jupytext command
            if "#" in cmd:
                left, comment = cmd.rsplit("#", 1)
                if '"' not in comment:
                    cmd = left

            print(f"Testing: {cmd}")
            args = shlex.split(cmd)[1:]
            assert not jupytext_cli(args), cmd
            cmd_tested += 1

    assert cmd_tested >= 10


text:
<?php

$time = $this->Controller("/App/Controllers/JSON/Time",$this->model);
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

echo "retry: 2000\n";
echo "event: ".$time->ViewData('event')."\n";
echo "data: ".$time->ViewData('data')."\n";
echo "\n";
ob_end_flush();
flush();
?>


text:
package main

import (
	"encoding/xml"
	"io/ioutil"
	"net/http"
)

var NicoAPIUrls = map[string]string{
	"login":        "https://secure.nicovideo.jp/secure/login?site=niconico",
	"getthumbinfo": "http://ext.nicovideo.jp/api/getthumbinfo/",
	"getflv":       "http://flapi.nicovideo.jp/api/getflv/",
}

type NicoVideoErrorInfo struct {
	XMLName     xml.Name `xml:"error"`
	Code        string   `xml:"code"`
	Description string   `xml:"description"`
}

type NicoVideoTag struct {
	XMLName xml.Name `xml:"tag"`
	Lock    string   `xml:"lock,attr"`
	Value   string   `xml:",innerxml"`
}

type NicoVideoTags struct {
	XMLName xml.Name       `xml:"tags"`
	Domain  string         `xml:"domain,attr"`
	Tag     []NicoVideoTag `xml:"tag"`
}

type NicoVideoInfo struct {
	XMLName       xml.Name        `xml:"thumb"`
	VideoId       string          `xml:"video_id"`
	Title         string          `xml:"title"`
	Description   string          `xml:"description"`
	ThumbnailUrl  string          `xml:"thumbnail_url"`
	FirstRetrieve string          `xml:"first_retrieve"`
	Length        string          `xml:"length"`
	MovieType     string          `xml:"movie_type"`
	SizeHigh      int             `xml:"size_high"`
	SizeLow       int             `xml:"size_low"`
	ViewCounter   int             `xml:"view_counter"`
	CommentNum    int             `xml:"comment_num"`
	MylistCounter int             `xml:"mylist_counter"`
	LastResBody   string          `xml:"last_res_body"`
	WatchUrl      string          `xml:"watch_url"`
	ThumbType     string          `xml:"thumb_type"`
	Embeddable    int             `xml:"embeddable"`
	NoLivePlay    int             `xml:"no_live_play"`
	Tags          []NicoVideoTags `xml:"tags"`
	UserId        int             `xml:"user_id"`
}

type NicoVideoThumbResponse struct {
	XMLName   xml.Name           `xml:"nicovideo_thumb_response"`
	Status    string             `xml:"status,attr"`
	ErrorInfo NicoVideoErrorInfo `xml:"error"`
	VideoInfo NicoVideoInfo      `xml:"thumb"`
}

func GetVideoThumbResponse(videoId string) (result NicoVideoThumbResponse, err error) {
	resp, _ := http.Get(NicoAPIUrls["getthumbinfo"] + videoId)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	err = xml.Unmarshal(body, &result)
	return
}

func GetVideoTitle(videoId string) (title string) {
	resp, err := GetVideoThumbResponse(videoId)

	if err != nil {
		return
	}

	if resp.Status != "ok" {
		return
	}

	title = resp.VideoInfo.Title
	return
}

func GetAllKindsOfVideoTags(videoId string) (allTags []string, lockedTags []string, unlockedTags []string) {
	resp, err := GetVideoThumbResponse(videoId)

	if err != nil {
		return
	}

	if resp.Status != "ok" {
		return
	}

	videoInfo := resp.VideoInfo
	for _, tag := range videoInfo.Tags[0].Tag {
		allTags = append(allTags, tag.Value)

		switch tag.Lock {
		case "1":
			lockedTags = append(lockedTags, tag.Value)
		default:
			unlockedTags = append(unlockedTags, tag.Value)
		}
	}
	return
}

func GetVideoTags(videoId string) (tags []string) {
	tags, _, _ = GetAllKindsOfVideoTags(videoId)
	return
}

func GetLockedVideoTags(videoId string) (lockedTags []string) {
	_, lockedTags, _ = GetAllKindsOfVideoTags(videoId)
	return
}

func GetUnlockedVideoTags(videoId string) (unlockedTags []string) {
	_, _, unlockedTags = GetAllKindsOfVideoTags(videoId)
	return
}


text:
package honkhonk.threadwatch.adapters;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;

import honkhonk.threadwatch.R;
import honkhonk.threadwatch.helpers.Common;
import honkhonk.threadwatch.models.ThreadModel;

/**
 * Handles display of threads in the list
 * Created by Gunbard on 10/15/2016.
 */

public class ThreadListAdapter extends ArrayAdapter<ThreadModel> {
    /**
     * Tag for logging
     */
    final private static String TAG = ThreadListAdapter.class.getSimpleName();

    /**
     * List of threads
     */
    private ArrayList<ThreadModel> threads;

    /**
     * Context for getting resources
     */
    private ThreadListAdapterListener context;

    public interface ThreadListAdapterListener {
        void onListItemLongPress(final int position);
    }

    public ThreadListAdapter(ThreadListAdapterListener context,
                             @LayoutRes int resource,
                             @IdRes int textViewResourceId,
                             @NonNull ArrayList<ThreadModel> threads) {
        super((Context) context, resource, textViewResourceId, threads);
        this.threads = threads;
        this.context = context;
    }

    @Override
    @NonNull
    public View getView(final int position, View convertView, @NonNull ViewGroup parent) {
        final View view = super.getView(position, convertView, parent);

        if (position >= threads.size()) {
            Log.e(TAG, "Tried to show a thread outside of bounds of data source");
            return view;
        }

        final ThreadModel thread = threads.get(position);

        final TextView boardName = view.findViewById(R.id.boardTitle);
        boardName.setText("/" + thread.board + "/");

        final SharedPreferences appSettings =
                PreferenceManager.getDefaultSharedPreferences((Context) this.context);

        final boolean showThumbnails = appSettings.getBoolean("pref_view_thumbnails", true);

        final ImageView thumbnailView = view.findViewById(R.id.thumbnailView);
        if (thread.thumbnail != null && showThumbnails) {
            byte[] decodedString = Base64.decode(thread.thumbnail, Base64.DEFAULT);
            Bitmap decodedImage = BitmapFactory.decodeByteArray(decodedString, 0,
                    decodedString.length);
            thumbnailView.setImageBitmap(decodedImage);
            thumbnailView.setVisibility(View.VISIBLE);

        } else {
            thumbnailView.setVisibility(View.GONE);
        }

        final TextView title = view.findViewById(R.id.threadTitle);
        final String titleText = thread.getTitle();

        if (titleText != null && !titleText.equals("") && !thread.firstRefresh) {
            title.setText(thread.getTitle());
        } else {
            title.setText(((Context) context).getResources().getString(R.string.no_thread_data));
        }

        final TextView newPosts = view.findViewById(R.id.newPosts);
        if (thread.replyCountDelta != 0) {
            newPosts.setText("(" + thread.replyCountDelta + ")") ;
        } else {
            newPosts.setText("");
        }

        final TextView lastPageWarningText = view.findViewById(R.id.lastPageWarning);
        if (thread.currentPage >= Common.LAST_PAGE) {
            lastPageWarningText.setVisibility(View.VISIBLE);
        } else {
            lastPageWarningText.setVisibility(View.GONE);
        }

        if (thread.newRepliesToYou) {
            newPosts.setTextColor(ContextCompat.getColor((Context) context, R.color.colorYou));
        } else {
            newPosts.setTextColor(ContextCompat.getColor((Context) context,
                    android.R.color.secondary_text_light));
        }

        if (thread.disabled) {
            view.setAlpha(0.5f);
        } else {
            view.setAlpha(1.0f);
        }

        if (thread.archived) {
            view.setBackgroundColor(ContextCompat.getColor((Context) context,
                    R.color.colorArchivedThread));
        } else if (thread.closed) {
            view.setBackgroundColor(ContextCompat.getColor((Context) context,
                    R.color.colorClosedThread));
        } else if (thread.notFound) {
            view.setBackgroundColor(ContextCompat.getColor((Context) context,
                    R.color.colorNotFoundThread));
        } else {
            view.setBackgroundColor(ContextCompat.getColor((Context) context,
                    R.color.colorThreadBackground));
        }

        // Set up preview event
        boardName.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                context.onListItemLongPress(position);
                return true;
            }
        });

        return view;
    }
}


text:
In docstrings, Sphinx cross-reference targets now use intersphinx, even if the
target is an internal link (``link`` is now ``'astropy:link``).
When built in Astropy these links are interpreted as internal links. When built
in affiliate packages, the link target is set by the key 'astropy' in the
intersphinx mapping.


text:
module CursorPagination
  VERSION = "0.0.3"
end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="60dp"
        android:src="@drawable/ic_launcher"
        android:layout_height="60dp"/>

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="test"
        android:textSize="18sp"
        android:layout_toRightOf="@id/imageview"/>
</RelativeLayout>