text:
package org.odata4j.producer.resources;

import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ContextResolver;

import org.odata4j.core.Guid;
import org.odata4j.core.ODataConstants;
import org.odata4j.core.ODataHttpMethod;
import org.odata4j.core.ODataVersion;
import org.odata4j.core.OEntity;
import org.odata4j.edm.EdmEntitySet;
import org.odata4j.exceptions.NotFoundException;
import org.odata4j.exceptions.UnsupportedMediaTypeException;
import org.odata4j.format.FormatWriter;
import org.odata4j.format.FormatWriterFactory;
import org.odata4j.format.writer.BufferOrFileResponseWriter;
import org.odata4j.internal.InternalUtil;
import org.odata4j.producer.CountResponse;
import org.odata4j.producer.EntitiesResponse;
import org.odata4j.producer.EntityResponse;
import org.odata4j.producer.ODataContext;
import org.odata4j.producer.ODataContextImpl;
import org.odata4j.producer.ODataProducer;
import org.odata4j.producer.QueryInfo;

// ignoreParens below is there to trim the parentheses from the entity set name when they are present - e.g. '/my.svc/Users()'.
@Path("{entitySetName: [^/()]+?}{ignoreParens: (?:\\(\\))?}")
public class EntitiesRequestResource extends BaseResource {

  private static final Logger log = Logger.getLogger(EntitiesRequestResource.class.getName());

  @POST
  @Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8, ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8, ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8 })
  public Response createEntity(
      @Context HttpHeaders httpHeaders,
      @Context UriInfo uriInfo,
      @Context ContextResolver<ODataProducer> producerResolver,
      @Context SecurityContext securityContext,
      @QueryParam("$format") String format,
      @QueryParam("$callback") String callback,
      @PathParam("entitySetName") String entitySetName,
      InputStream payload) throws Exception {

    // visual studio will send a soap mex request
    if (entitySetName.equals("mex") && httpHeaders.getMediaType() != null && httpHeaders.getMediaType().toString().startsWith("application/soap+xml"))
      throw new UnsupportedMediaTypeException("SOAP mex requests are not supported");

    ODataProducer producer = producerResolver.getContext(ODataProducer.class);

    // the OData URI scheme makes it impossible to have unique @Paths that refer
    // to functions and entity sets
    if (producer.getMetadata().containsEdmFunctionImport(entitySetName)) {
      // functions that return collections of entities should support the
      // same set of query options as entity set queries so give them everything.
      log("callFunction", "functionName", entitySetName);

      ODataHttpMethod callingMethod = ODataHttpMethod.POST;
      List<String> xheader = httpHeaders.getRequestHeader("X-HTTP-METHOD");
      if (xheader != null && xheader.size() > 0) {
        callingMethod = ODataHttpMethod.fromString(xheader.get(0));
      }

      QueryInfo query = QueryInfo.newBuilder().setCustomOptions(OptionsQueryParser.parseCustomOptions(uriInfo)).build();
      return FunctionResource.callFunction(callingMethod, httpHeaders, uriInfo, securityContext, producer, entitySetName, format, callback, query, null, null, payload);
    }

    log("createEntity", "entitySetName", entitySetName);

    // is this a new media resource?
    // check for HasStream
    EdmEntitySet entitySet = producer.getMetadata().findEdmEntitySet(entitySetName);
    if (entitySet == null) {
      throw new NotFoundException();
    }

    ODataContext odataContext = ODataContextImpl.builder()
        .aspect(httpHeaders)
        .aspect(securityContext)
        .aspect(producer)
        .aspect(entitySet)
        .aspect(uriInfo)
        .build();

    /*
     * First check if we have a slug header present in the request if it is not
     * then treat it as a normal entity creation and not an MLE.
     * If slug header is present then we will treat the POST request as a MLE request.
     */
    String slugHeader = httpHeaders.getRequestHeader("Slug") != null ? httpHeaders.getRequestHeader("Slug").get(0) : null;

    if (entitySet.getType().getHasStream() != null && Boolean.TRUE.equals(entitySet.getType().getHasStream())
        && slugHeader != null && !slugHeader.equals("")) { // getHasStream can return null
      // yes it is!
      return createMediaLinkEntry(httpHeaders, uriInfo, securityContext, producer, entitySet, payload, odataContext);
    }

    // also on the plus side we can now parse the stream directly off the wire....
    return createEntity(httpHeaders, uriInfo, securityContext, producer, entitySetName,
        this.getRequestEntity(httpHeaders, uriInfo, payload, producer.getMetadata(), entitySetName, null), odataContext, null);
  }

  protected Response createEntity(
      HttpHeaders httpHeaders,
      UriInfo uriInfo,
      SecurityContext securityContext,
      ODataProducer producer,
      String entitySetName,
      OEntity entity,
      ODataContext odataContext, List<MediaType> mediaTypeList) throws Exception {

    EntityResponse response = producer.createEntity(odataContext, entitySetName, entity);
    FormatWriter<EntityResponse> writer = null;
    if (mediaTypeList != null) {
      writer = FormatWriterFactory.getFormatWriter(EntityResponse.class, mediaTypeList, null, null);
    }
    else {
      writer = FormatWriterFactory.getFormatWriter(EntityResponse.class, httpHeaders.getAcceptableMediaTypes(), null, null);
    }

    StringWriter sw = new StringWriter();
    writer.write(uriInfo, sw, response);

    String relid = InternalUtil.getEntityRelId(response.getEntity());
    String entryId = uriInfo.getBaseUri().toString() + relid;

    String responseEntity = sw.toString();

    return Response
        .ok(responseEntity, writer.getContentType())
        .status(Status.CREATED)
        .location(URI.create(entryId))
        .header(ODataConstants.Headers.DATA_SERVICE_VERSION,
            ODataConstants.DATA_SERVICE_VERSION_HEADER).build();
  }

  protected Response createMediaLinkEntry(
      HttpHeaders httpHeaders,
      UriInfo uriInfo,
      SecurityContext securityContext,
      ODataProducer producer,
      EdmEntitySet entitySet,
      InputStream payload,
      ODataContext odataContext) throws Exception {

    log("createMediaLinkEntity", "entitySetName", entitySet.getName());

    OEntity mle = super.createOrUpdateMediaLinkEntry(httpHeaders, uriInfo, entitySet, producer, payload, null, odataContext);

    // return the mle
    return createEntity(httpHeaders,
        uriInfo,
        securityContext,
        producer,
        entitySet.getName(),
        mle,
        odataContext, null);
  }

  @PUT
  public Response functionCallPut(
      @Context HttpHeaders httpHeaders,
      @Context UriInfo uriInfo,
      @Context ContextResolver<ODataProducer> producerResolver,
      @Context SecurityContext securityContext,
      @QueryParam("$format") String format,
      @QueryParam("$callback") String callback,
      @PathParam("entitySetName") String functionName,
      InputStream payload) throws Exception {

    Response response;
    log("functionCallDelete", "function", functionName);

    ODataProducer producer = producerResolver.getContext(ODataProducer.class);

    // the OData URI scheme makes it impossible to have unique @Paths that refer
    // to functions and entity sets
    if (producer.getMetadata().containsEdmFunctionImport(functionName)) {
      // functions that return collections of entities should support the
      // same set of query options as entity set queries so give them everything.

      QueryInfo query = QueryInfo.newBuilder().setCustomOptions(OptionsQueryParser.parseCustomOptions(uriInfo)).build();
      response = FunctionResource.callFunction(ODataHttpMethod.PUT, httpHeaders, uriInfo, securityContext, producer, functionName, format, callback, query);
    } else {
      throw new NotFoundException(functionName);
    }

    return response;
  }

  @DELETE
  public Response functionCallDelete(
      @Context HttpHeaders httpHeaders,
      @Context UriInfo uriInfo,
      @Context ContextResolver<ODataProducer> producerResolver,
      @Context SecurityContext securityContext,
      @QueryParam("$format") String format,
      @QueryParam("$callback") String callback,
      @PathParam("entitySetName") String functionName,
      InputStream payload) throws Exception {

    Response response;
    log("functionCallDelete", "function", functionName);

    ODataProducer producer = producerResolver.getContext(ODataProducer.class);

    // the OData URI scheme makes it impossible to have unique @Paths that refer
    // to functions and entity sets
    if (producer.getMetadata().containsEdmFunctionImport(functionName)) {
      // functions that return collections of entities should support the
      // same set of query options as entity set queries so give them everything.

      QueryInfo query = QueryInfo.newBuilder().setCustomOptions(OptionsQueryParser.parseCustomOptions(uriInfo)).build();
      response = FunctionResource.callFunction(ODataHttpMethod.DELETE, httpHeaders, uriInfo, securityContext, producer, functionName, format, callback, query);
    } else {
      throw new NotFoundException(functionName);
    }

    return response;
  }

  @GET
  @Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8,
      ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8,
      ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8 })
  public Response getEntities(
      @Context HttpHeaders httpHeaders,
      @Context UriInfo uriInfo,
      @Context ContextResolver<ODataProducer> producerResolver,
      @Context SecurityContext securityContext,
      @PathParam("entitySetName") String entitySetName,
      @QueryParam("$inlinecount") String inlineCount,
      @QueryParam("$top") String top,
      @QueryParam("$skip") String skip,
      @QueryParam("$filter") String filter,
      @QueryParam("$orderby") String orderBy,
      @QueryParam("$format") String format,
      @QueryParam("$callback") String callback,
      @QueryParam("$skiptoken") String skipToken,
      @QueryParam("$expand") String expand,
      @QueryParam("$select") String select)
      throws Exception {

    ODataProducer producer = producerResolver.getContext(ODataProducer.class);

    return getEntitiesImpl(httpHeaders, uriInfo, securityContext, producer, entitySetName, false, inlineCount, top, skip,
        filter, orderBy, format, callback, skipToken, expand, select);
  }

  @GET
  @Path("{count: [$]count}")
  @Produces({ ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8,
      ODataConstants.TEXT_JAVASCRIPT_CHARSET_UTF8,
      ODataConstants.TEXT_PLAIN_CHARSET_UTF8,
      ODataConstants.APPLICATION_JAVASCRIPT_CHARSET_UTF8 })
  public Response getEntitiesCount(
      @Context HttpHeaders httpHeaders,
      @Context UriInfo uriInfo,
      @Context ContextResolver<ODataProducer> producerResolver,
      @Context SecurityContext securityContext,
      @PathParam("entitySetName") String entitySetName,
      @PathParam("count") String count,
      @QueryParam("$inlinecount") String inlineCount,
      @QueryParam("$top") String top,
      @QueryParam("$skip") String skip,
      @QueryParam("$filter") String filter,
      @QueryParam("$orderby") String orderBy,
      @QueryParam("$format") String format,
      @QueryParam("$callback") String callback,
      @QueryParam("$skiptoken") String skipToken,
      @QueryParam("$expand") String expand,
      @QueryParam("$select") String select) throws Exception {

    log("getEntitiesCount",
        "entitySetName", entitySetName,
        "inlineCount", inlineCount,
        "top", top,
        "skip", skip,
        "filter", filter,
        "orderBy", orderBy,
        "format", format,
        "callback", callback,
        "skipToken", skipToken,
        "expand", expand,
        "select", select);

    ODataProducer producer = producerResolver.getContext(ODataProducer.class);

    return getEntitiesImpl(httpHeaders, uriInfo, securityContext, producer, entitySetName, true, inlineCount, top, skip,
        filter, orderBy, format, callback, skipToken, expand, select);
  }

  protected Response getEntitiesImpl(
      HttpHeaders httpHeaders,
      UriInfo uriInfo,
      SecurityContext securityContext,
      ODataProducer producer,
      String entitySetName,
      boolean isCount,
      String inlineCount,
      String top,
      String skip,
      String filter,
      String orderBy,
      String format,
      String callback,
      String skipToken,
      String expand,
      String select) throws Exception {

    QueryInfo query = new QueryInfo(
        OptionsQueryParser.parseInlineCount(inlineCount),
        OptionsQueryParser.parseTop(top),
        OptionsQueryParser.parseSkip(skip),
        OptionsQueryParser.parseFilter(filter),
        OptionsQueryParser.parseOrderBy(orderBy),
        OptionsQueryParser.parseSkipToken(skipToken),
        OptionsQueryParser.parseCustomOptions(uriInfo),
        OptionsQueryParser.parseExpand(expand),
        OptionsQueryParser.parseSelect(select));

    ODataContextImpl odataContext = ODataContextImpl.builder()
        .aspect(httpHeaders)
        .aspect(uriInfo)
        .aspect(securityContext)
        .aspect(producer)
        .build();

    // the OData URI scheme makes it impossible to have unique @Paths that refer
    // to functions and entity sets
    if (producer.getMetadata().containsEdmFunctionImport(entitySetName)) {

      log("callFunction",
          "functionName", entitySetName,
          "inlineCount", inlineCount,
          "top", top,
          "skip", skip,
          "filter", filter,
          "orderBy", orderBy,
          "format", format,
          "callback", callback,
          "skipToken", skipToken,
          "expand", expand,
          "select", select);
      // functions that return collections of entities should support the
      // same set of query options as entity set queries so give them everything.
      return FunctionResource.callFunction(ODataHttpMethod.GET, httpHeaders, uriInfo, securityContext, producer, entitySetName, format, callback, query);
    }

    log("getEntities",
        "entitySetName", entitySetName,
        "inlineCount", inlineCount,
        "top", top,
        "skip", skip,
        "filter", filter,
        "orderBy", orderBy,
        "format", format,
        "callback", callback,
        "skipToken", skipToken,
        "expand", expand,
        "select", select);

    Response response = null;
    if (isCount) {
      CountResponse countResponse = producer.getEntitiesCount(odataContext, entitySetName, query);

      String entity = Long.toString(countResponse.getCount());

      ODataVersion version = ODataConstants.DATA_SERVICE_VERSION;

      response = Response
          .ok(entity, ODataConstants.TEXT_PLAIN_CHARSET_UTF8)
          .header(ODataConstants.Headers.DATA_SERVICE_VERSION, version.asString)
          .build();
    }
    else {
      EntitiesResponse entitiesResponse = producer.getEntities(odataContext, entitySetName, query);

      if (entitiesResponse == null) {
        throw new NotFoundException(entitySetName);
      }

      FormatWriter<EntitiesResponse> fw =
          FormatWriterFactory.getFormatWriter(
              EntitiesResponse.class,
              httpHeaders.getAcceptableMediaTypes(),
              format,
              callback);

      //Use the buffered response writer for setting the response using the charset based on the media type
      BufferOrFileResponseWriter responseWriter = new BufferOrFileResponseWriter(fw.getContentType());

      fw.write(uriInfo, responseWriter, entitiesResponse);

      //Close the response writer and send the object to be written out
      responseWriter.close();

      ODataVersion version = ODataConstants.DATA_SERVICE_VERSION;

      response = Response
          .ok(responseWriter.getResponseHolder(), fw.getContentType())
          .header(ODataConstants.Headers.DATA_SERVICE_VERSION, version.asString)
          .build();
    }
    return response;
  }

  @POST
  @Path("{batch: [$]batch}")
  @Consumes(ODataBatchProvider.MULTIPART_MIXED)
  @Produces(ODataConstants.APPLICATION_ATOM_XML_CHARSET_UTF8)
  public Response processBatch(
      @Context ContextResolver<ODataProducer> producerResolver,
      @Context HttpHeaders headers,
      @Context Request request,
      @Context SecurityContext securityContext,
      @QueryParam("$format") String format,
      @QueryParam("$callback") String callback,
      List<BatchBodyPart> bodyParts) throws Exception {

    log("processBatch", "bodyParts.size", bodyParts.size());

    EntityRequestResource er = new EntityRequestResource();

    String changesetBoundary = "changesetresponse_"
        + Guid.randomGuid().toString();
    String batchBoundary = "batchresponse_" + Guid.randomGuid().toString();
    StringBuilder batchResponse = new StringBuilder("\n--");
    batchResponse.append(batchBoundary);

    batchResponse
        .append("\n").append(ODataConstants.Headers.CONTENT_TYPE).append(": multipart/mixed; boundary=")
        .append(changesetBoundary);

    batchResponse.append('\n');

    ODataProducer producer = producerResolver.getContext(ODataProducer.class);

    ODataContext odataContext = ODataContextImpl.builder()
        .aspect(headers)
        .aspect(securityContext)
        .aspect(producer)
        .build();

    for (BatchBodyPart bodyPart : bodyParts) {
      HttpHeaders httpHeaders = bodyPart.getHttpHeaders();
      UriInfo uriInfo = bodyPart.getUriInfo();
      String entitySetName = bodyPart.getEntitySetName();
      String entityId = bodyPart.getEntityKey();
      String entityString = bodyPart.getEntity();
      Response response = null;

      switch (bodyPart.getHttpMethod()) {
      case POST:
        response = this.createEntity(httpHeaders, uriInfo, securityContext, producer,
            entitySetName,
            getRequestEntity(httpHeaders, uriInfo, entityString, producer.getMetadata(), entitySetName, null), odataContext, null);
        break;
      case PUT:
        response = er.updateEntity(httpHeaders, uriInfo, securityContext, producerResolver,
            entitySetName, entityId, entityString, odataContext);
        break;
      case MERGE:
        response = er.mergeEntity(httpHeaders, uriInfo, producerResolver, securityContext, entitySetName,
            entityId, entityString);
        break;
      case DELETE:
        response = er.deleteEntity(httpHeaders, uriInfo, producerResolver, securityContext, format, callback, entitySetName, entityId);
        break;
      case GET:
        throw new UnsupportedOperationException("Not supported yet.");
      }

      batchResponse.append("\n--").append(changesetBoundary);
      batchResponse.append("\n").append(ODataConstants.Headers.CONTENT_TYPE).append(": application/http");
      batchResponse.append("\nContent-Transfer-Encoding: binary\n");

      batchResponse.append(ODataBatchProvider.createResponseBodyPart(
          bodyPart,
          response));
    }

    batchResponse.append("--").append(changesetBoundary).append("--\n");
    batchResponse.append("--").append(batchBoundary).append("--\n");

    return Response
        .status(Status.ACCEPTED)
        .type(ODataBatchProvider.MULTIPART_MIXED + ";boundary="
            + batchBoundary).header(
            ODataConstants.Headers.DATA_SERVICE_VERSION,
            ODataConstants.DATA_SERVICE_VERSION_HEADER)
        .entity(batchResponse.toString()).build();
  }

  @Path("{navProp: [^$/()]+?}")
  public BaseResource getNavProperty(
      @Context ContextResolver<ODataProducer> producerResolver,
      @PathParam("entitySetName") String entitySetName,
      @PathParam("navProp") String functionName) {

    ODataProducer producer = producerResolver.getContext(ODataProducer.class);
    if (producer.getMetadata().containsEdmFunctionImport(functionName)) {
      return new FunctionResource();
    } else {
      throw new NotFoundException(functionName);
    }
  }

  private static void log(String operation, Object... namedArgs) {
    if (!log.isLoggable(Level.FINE))
      return;
    StringBuilder sb = new StringBuilder(operation).append('(');
    if (namedArgs != null && namedArgs.length > 0) {
      for (int i = 0; i < namedArgs.length; i += 2) {
        if (i > 0)
          sb.append(',');
        sb.append(namedArgs[i]).append('=').append(namedArgs[i + 1]);
      }
    }
    log.fine(sb.append(')').toString());
  }

}


text:
class String
  # casts to an integer if applicable,
  # else leaves it alone.
  def to_i?
    Integer(self)
  rescue
    self
  end
end

redpajama_set_name: RedPajamaGithub


text:
from __future__ import annotations

import functools

from orderedset import OrderedSet

from dxtbx.model.experiment_list import ExperimentList
from libtbx.phil import parse

import dials.util
from dials.array_family import flex
from dials.util import Sorry
from dials.util.export_mtz import match_wavelengths
from dials.util.options import ArgumentParser, reflections_and_experiments_from_files

help_message = """

Utility script to split experiments and reflections from single files into
multiple files with one experiment per output experiment file and one
reflection file per output experiment file. Alternative options include
splitting by unique detector model or splitting by wavelength. The data
can also be split into chunks rather than individual output files if
required.

Example::

  dials.split_experiments combined.expt combined.refl
"""

class Script:
    def __init__(self):
        """Initialise the script."""
        # The phil scope
        phil_scope = parse(
            """
      by_detector = False
        .type = bool
        .help = "If True, instead of producing separate files for each"
                "experiment, experiments are grouped by unique detector"
                "model in the input set of experiments. For example, if"
                "there are five detector models in the input data, five"
                "sets of files will be produced, each containing"
                "experiments that reference a single detector model."
      by_wavelength = False
        .type = bool
        .help = "If True, group experiments by wavelength, from low to high"
                "(using a relative tolerance of 1e-4 to match wavelengths)."
      output {
        experiments_prefix = split
          .type = str
          .help = "Filename prefix for the split experimental models"

        reflections_prefix = split
          .type = str
          .help = "Filename prefix for the split reflections"

        template = "{prefix}_{index:0{maxindexlength:d}d}.{extension}"
          .type = str
          .expert_level = 2
          .help = "Template python format string for output filenames."
                  "Replaced variables are prefix (with"
                  "output.{experiments_prefix, reflections_prefix}),"
                  "index (number of split experiment), maxindexlength"
                  "(number of digits of total number of split experiments)"
                  "and extension (default file extension for model and"
                  "reflection files)"

        chunk_size = None
          .type = int
          .expert_level = 2
          .help = "If not None, instead of creating many individual"
                  "files, create composite files with no more than"
                  "chunk_size experiments per file."
        chunk_sizes = None
          .type = ints
          .expert_level = 2
          .help = "If not None, instead of creating many individual"
                  "files, create composite files with the number of"
                  "datasets given in the chunk_sizes list."

      }
    """,
            process_includes=True,
        )

        # The script usage
        usage = (
            "usage: dials.split_experiments [options] [param.phil] "
            "experiments1.expt experiments2.expt reflections1.refl "
            "reflections2.refl..."
        )

        # Create the parser
        self.parser = ArgumentParser(
            usage=usage,
            phil=phil_scope,
            read_reflections=True,
            read_experiments=True,
            check_format=False,
            epilog=help_message,
        )

    def run(self, args=None):
        """Execute the script."""

        # Parse the command line
        params, _ = self.parser.parse_args(args, show_diff_phil=True)

        # Try to load the models and data
        if not params.input.experiments:
            print("No Experiments found in the input")
            self.parser.print_help()
            return
        if params.input.reflections:
            if len(params.input.reflections) != len(params.input.experiments):
                raise Sorry(
                    "The number of input reflections files does not match the "
                    "number of input experiments"
                )
        reflections, experiments = reflections_and_experiments_from_files(
            params.input.reflections, params.input.experiments
        )
        if reflections:
            reflections = reflections[0]
        else:
            reflections = None

        experiments_template = functools.partial(
            params.output.template.format,
            prefix=params.output.experiments_prefix,
            maxindexlength=len(str(len(experiments) - 1)),
            extension="expt",
        )

        reflections_template = functools.partial(
            params.output.template.format,
            prefix=params.output.reflections_prefix,
            maxindexlength=len(str(len(experiments) - 1)),
            extension="refl",
        )

        if params.output.chunk_sizes:
            if not sum(params.output.chunk_sizes) == len(experiments):
                raise Sorry(
                    "Sum of chunk sizes list (%s) not equal to number of experiments (%s)"
                    % (sum(params.output.chunk_sizes), len(experiments))
                )

        if params.by_wavelength:
            if reflections:
                if not reflections.experiment_identifiers():
                    raise Sorry(
                        "Unable to split by wavelength as no experiment "
                        "identifiers are set in the reflection table."
                    )
            if all(experiments.identifiers() == ""):
                raise Sorry(
                    "Unable to split by wavelength as no experiment "
                    "identifiers are set in the experiment list."
                )

            wavelengths = match_wavelengths(experiments)
            for i, wl in enumerate(sorted(wavelengths.keys())):
                expids = []
                new_exps = ExperimentList()
                exp_nos = wavelengths[wl]
                imageset_ids = []  # record imageset ids to set in refl table
                imagesets_found = OrderedSet()
                for j in exp_nos:
                    expids.append(experiments[j].identifier)  # string
                    new_exps.append(experiments[j])
                    imagesets_found.add(experiments[j].imageset)
                    imageset_ids.append(imagesets_found.index(experiments[j].imageset))
                experiment_filename = experiments_template(index=i)
                print(
                    f"Saving experiments with wavelength {wl} to {experiment_filename}"
                )
                new_exps.as_json(experiment_filename)
                if reflections:
                    refls = reflections.select_on_experiment_identifiers(expids)
                    refls["imageset_id"] = flex.int(refls.size(), 0)
                    # now set the imageset ids
                    for k, iset_id in enumerate(imageset_ids):
                        # select the experiment based on id (unique per sweep),
                        # and set the imageset_id (not necessarily unique per sweep
                        # if imageset is shared)
                        sel = refls["id"] == k
                        refls["imageset_id"].set_selected(sel, iset_id)
                    reflections_filename = reflections_template(index=i)
                    print(
                        "Saving reflections with wavelength %s to %s"
                        % (wl, reflections_filename)
                    )
                    refls.as_file(reflections_filename)

        elif params.by_detector:
            assert (
                not params.output.chunk_size
            ), "chunk_size + by_detector is not implemented"
            if reflections is None:
                split_data = {
                    detector: {"experiments": ExperimentList()}
                    for detector in experiments.detectors()
                }
            else:
                split_data = {
                    detector: {
                        "experiments": ExperimentList(),
                        "reflections": flex.reflection_table(),
                        "imagesets_found": OrderedSet(),
                    }
                    for detector in experiments.detectors()
                }
            for i, experiment in enumerate(experiments):
                split_expt_id = experiments.detectors().index(experiment.detector)
                experiment_filename = experiments_template(index=split_expt_id)
                print("Adding experiment %d to %s" % (i, experiment_filename))
                split_data[experiment.detector]["experiments"].append(experiment)
                if reflections is not None:
                    reflections_filename = reflections_template(index=split_expt_id)
                    split_data[experiment.detector]["imagesets_found"].add(
                        experiment.imageset
                    )
                    print(
                        "Adding reflections for experiment %d to %s"
                        % (i, reflections_filename)
                    )
                    if reflections.experiment_identifiers().keys():
                        # first find which id value corresponds to experiment in question
                        identifier = experiment.identifier
                        id_ = None
                        for k in reflections.experiment_identifiers().keys():
                            if reflections.experiment_identifiers()[k] == identifier:
                                id_ = k
                                break
                        if id_ is None:
                            raise Sorry(
                                "Unable to find id matching experiment identifier in reflection table."
                            )
                        ref_sel = reflections.select(reflections["id"] == id_)
                        # now reset ids and reset/update identifiers map
                        for k in ref_sel.experiment_identifiers().keys():
                            del ref_sel.experiment_identifiers()[k]
                        new_id = len(split_data[experiment.detector]["experiments"]) - 1
                        ref_sel["id"] = flex.int(len(ref_sel), new_id)
                        ref_sel.experiment_identifiers()[new_id] = identifier
                    else:
                        ref_sel = reflections.select(reflections["id"] == i)
                        ref_sel["id"] = flex.int(
                            len(ref_sel),
                            len(split_data[experiment.detector]["experiments"]) - 1,
                        )
                    iset_id = split_data[experiment.detector]["imagesets_found"].index(
                        experiment.imageset
                    )
                    ref_sel["imageset_id"] = flex.int(ref_sel.size(), iset_id)
                    split_data[experiment.detector]["reflections"].extend(ref_sel)

            for i, detector in enumerate(experiments.detectors()):
                experiment_filename = experiments_template(index=i)
                print("Saving experiment %d to %s" % (i, experiment_filename))
                split_data[detector]["experiments"].as_json(experiment_filename)

                if reflections is not None:
                    reflections_filename = reflections_template(index=i)
                    print(
                        "Saving reflections for experiment %d to %s"
                        % (i, reflections_filename)
                    )
                    split_data[detector]["reflections"].as_file(reflections_filename)
        elif params.output.chunk_size or params.output.chunk_sizes:

            def save_chunk(chunk_id, expts, refls):
                experiment_filename = experiments_template(index=chunk_id)
                print("Saving chunk %d to %s" % (chunk_id, experiment_filename))
                expts.as_json(experiment_filename)
                if refls is not None:
                    reflections_filename = reflections_template(index=chunk_id)
                    print(
                        "Saving reflections for chunk %d to %s"
                        % (chunk_id, reflections_filename)
                    )
                    refls.as_file(reflections_filename)

            chunk_counter = 0
            chunk_expts = ExperimentList()
            if reflections:
                chunk_refls = flex.reflection_table()
            else:
                chunk_refls = None
            next_iset_id = 0
            imagesets_found = OrderedSet()
            for i, experiment in enumerate(experiments):
                chunk_expts.append(experiment)
                if reflections:
                    if reflections.experiment_identifiers().keys():
                        # first find which id value corresponds to experiment in question
                        identifier = experiment.identifier
                        id_ = None
                        for k in reflections.experiment_identifiers().keys():
                            if reflections.experiment_identifiers()[k] == identifier:
                                id_ = k
                                break
                        if id_ is None:
                            raise Sorry(
                                "Unable to find id matching experiment identifier in reflection table."
                            )
                        ref_sel = reflections.select(reflections["id"] == id_)
                        # now reset ids and reset/update identifiers map
                        for k in ref_sel.experiment_identifiers().keys():
                            del ref_sel.experiment_identifiers()[k]
                        new_id = len(chunk_expts) - 1
                        ref_sel["id"] = flex.int(len(ref_sel), new_id)
                        ref_sel.experiment_identifiers()[new_id] = identifier
                    else:
                        ref_sel = reflections.select(reflections["id"] == i)
                        ref_sel["id"] = flex.int(len(ref_sel), len(chunk_expts) - 1)
                    if experiment.imageset not in imagesets_found:
                        imagesets_found.add(experiment.imageset)
                        ref_sel["imageset_id"] = flex.int(ref_sel.size(), next_iset_id)
                        next_iset_id += 1
                    else:
                        iset_id = imagesets_found.index(experiment.imageset)
                        ref_sel["imageset_id"] = flex.int(ref_sel.size(), iset_id)
                    chunk_refls.extend(ref_sel)
                if params.output.chunk_sizes:
                    chunk_limit = params.output.chunk_sizes[chunk_counter]
                else:
                    chunk_limit = params.output.chunk_size
                if len(chunk_expts) == chunk_limit:
                    save_chunk(chunk_counter, chunk_expts, chunk_refls)
                    chunk_counter += 1
                    chunk_expts = ExperimentList()
                    if reflections:
                        chunk_refls = flex.reflection_table()
                    else:
                        chunk_refls = None
            if len(chunk_expts) > 0:
                save_chunk(chunk_counter, chunk_expts, chunk_refls)
        else:
            for i, experiment in enumerate(experiments):

                experiment_filename = experiments_template(index=i)
                print("Saving experiment %d to %s" % (i, experiment_filename))
                ExperimentList([experiment]).as_json(experiment_filename)

                if reflections is not None:
                    reflections_filename = reflections_template(index=i)
                    print(
                        "Saving reflections for experiment %d to %s"
                        % (i, reflections_filename)
                    )
                    ref_sel = reflections.select(reflections["id"] == i)
                    if ref_sel.experiment_identifiers().keys():
                        identifier = ref_sel.experiment_identifiers()[i]
                        for k in ref_sel.experiment_identifiers().keys():
                            del ref_sel.experiment_identifiers()[k]
                        ref_sel["id"] = flex.int(ref_sel.size(), 0)
                        ref_sel.experiment_identifiers()[0] = identifier
                    else:
                        ref_sel["id"] = flex.int(len(ref_sel), 0)
                    ref_sel["imageset_id"] = flex.int(len(ref_sel), 0)
                    ref_sel.as_file(reflections_filename)

        return

@dials.util.show_mail_handle_errors()
def run(args=None):
    script = Script()
    script.run(args)

if __name__ == "__main__":
    run()


text:
using namespace arangodb;

AgencyCallback::AgencyCallback(AgencyComm& agency, std::string const& key,
                               std::function<bool(VPackSlice const&)> const& cb,
                               bool needsValue, bool needsInitialValue)
    : key(key), _agency(agency), _cb(cb), _needsValue(needsValue) {
  if (_needsValue && needsInitialValue) {
    refetchAndUpdate(true);
  }
}

void AgencyCallback::refetchAndUpdate(bool needToAcquireMutex) {
  if (!_needsValue) {
    // no need to pass any value to the callback
    if (needToAcquireMutex) {
      CONDITION_LOCKER(locker, _cv);
      executeEmpty();
    } else {
      executeEmpty();
    }
    return;
  }

  AgencyCommResult result = _agency.getValues(key);

  if (!result.successful()) {
    LOG(ERR) << "Callback getValues to agency was not successful: "
             << result.errorCode() << " " << result.errorMessage();
    return;
  }

  std::vector<std::string> kv =
      basics::StringUtils::split(AgencyCommManager::path(key), '/');
  kv.erase(std::remove(kv.begin(), kv.end(), ""), kv.end());

  std::shared_ptr<VPackBuilder> newData = std::make_shared<VPackBuilder>();
  newData->add(result.slice()[0].get(kv));

  if (needToAcquireMutex) {
    CONDITION_LOCKER(locker, _cv);
    checkValue(newData);
  } else {
    checkValue(newData);
  }
}

void AgencyCallback::checkValue(std::shared_ptr<VPackBuilder> newData) {
  // Only called from refetchAndUpdate, we always have the mutex when
  // we get here!
  if (!_lastData || !_lastData->slice().equals(newData->slice())) {
    LOG_TOPIC(DEBUG, Logger::CLUSTER) << "AgencyCallback: Got new value "
                                      << newData->slice().typeName() << " "
                                      << newData->toJson();
    if (execute(newData)) {
      _lastData = newData;
    } else {
      LOG_TOPIC(DEBUG, Logger::CLUSTER) << "Callback was not successful for "
                                        << newData->toJson();
    }
  }
}

bool AgencyCallback::executeEmpty() {
  // only called from refetchAndUpdate, we always have the mutex when
  // we get here!
  LOG_TOPIC(DEBUG, Logger::CLUSTER) << "Executing (empty)";
  bool result = _cb(VPackSlice::noneSlice());
  if (result) {
    _cv.signal();
  }
  return result;
}

bool AgencyCallback::execute(std::shared_ptr<VPackBuilder> newData) {
  // only called from refetchAndUpdate, we always have the mutex when
  // we get here!
  LOG_TOPIC(DEBUG, Logger::CLUSTER) << "Executing";
  bool result = _cb(newData->slice());
  if (result) {
    _cv.signal();
  }
  return result;
}

void AgencyCallback::executeByCallbackOrTimeout(double maxTimeout) {
  // One needs to acquire the mutex of the condition variable
  // before entering this function!
  if (!_cv.wait(static_cast<uint64_t>(maxTimeout * 1000000.0))) {
    LOG_TOPIC(DEBUG, Logger::CLUSTER)
        << "Waiting done and nothing happended. Refetching to be sure";
    // mop: watches have not triggered during our sleep...recheck to be sure
    refetchAndUpdate(false);
  }
}


text:
package v1beta1

import (
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
)

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

const (
	// MachineFinalizer is set on PrepareForCreate callback.
	MachineFinalizer = "machine.machine.openshift.io"

	// MachineClusterLabelName is the label set on machines linked to a cluster.
	MachineClusterLabelName = "cluster.k8s.io/cluster-name"

	// MachineClusterIDLabel is the label that a machine must have to identify the
	// cluster to which it belongs.
	MachineClusterIDLabel = "machine.openshift.io/cluster-api-cluster"
)

type MachineStatusError string

const (
	// Represents that the combination of configuration in the MachineSpec
	// is not supported by this cluster. This is not a transient error, but
	// indicates a state that must be fixed before progress can be made.
	//
	// Example: the ProviderSpec specifies an instance type that doesn't exist,
	InvalidConfigurationMachineError MachineStatusError = "InvalidConfiguration"

	// This indicates that the MachineSpec has been updated in a way that
	// is not supported for reconciliation on this cluster. The spec may be
	// completely valid from a configuration standpoint, but the controller
	// does not support changing the real world state to match the new
	// spec.
	//
	// Example: the responsible controller is not capable of changing the
	// container runtime from docker to rkt.
	UnsupportedChangeMachineError MachineStatusError = "UnsupportedChange"

	// This generally refers to exceeding one's quota in a cloud provider,
	// or running out of physical machines in an on-premise environment.
	InsufficientResourcesMachineError MachineStatusError = "InsufficientResources"

	// There was an error while trying to create a Node to match this
	// Machine. This may indicate a transient problem that will be fixed
	// automatically with time, such as a service outage, or a terminal
	// error during creation that doesn't match a more specific
	// MachineStatusError value.
	//
	// Example: timeout trying to connect to GCE.
	CreateMachineError MachineStatusError = "CreateError"

	// There was an error while trying to update a Node that this
	// Machine represents. This may indicate a transient problem that will be
	// fixed automatically with time, such as a service outage,
	//
	// Example: error updating load balancers
	UpdateMachineError MachineStatusError = "UpdateError"

	// An error was encountered while trying to delete the Node that this
	// Machine represents. This could be a transient or terminal error, but
	// will only be observable if the provider's Machine controller has
	// added a finalizer to the object to more gracefully handle deletions.
	//
	// Example: cannot resolve EC2 IP address.
	DeleteMachineError MachineStatusError = "DeleteError"

	// TemplateClonedFromGroupKindAnnotation is the infrastructure machine
	// annotation that stores the group-kind of the infrastructure template resource
	// that was cloned for the machine. This annotation is set only during cloning a
	// template. Older/adopted machines will not have this annotation.
	TemplateClonedFromGroupKindAnnotation = "machine.openshift.io/cloned-from-groupkind"

	// TemplateClonedFromNameAnnotation is the infrastructure machine annotation that
	// stores the name of the infrastructure template resource
	// that was cloned for the machine. This annotation is set only during cloning a
	//  template. Older/adopted machines will not have this annotation.
	TemplateClonedFromNameAnnotation = "machine.openshift.io/cloned-from-name"

	// This error indicates that the machine did not join the cluster
	// as a new node within the expected timeframe after instance
	// creation at the provider succeeded
	//
	// Example use case: A controller that deletes Machines which do
	// not result in a Node joining the cluster within a given timeout
	// and that are managed by a MachineSet
	JoinClusterTimeoutMachineError = "JoinClusterTimeoutError"
)

type ClusterStatusError string

const (
	// InvalidConfigurationClusterError indicates that the cluster
	// configuration is invalid.
	InvalidConfigurationClusterError ClusterStatusError = "InvalidConfiguration"

	// UnsupportedChangeClusterError indicates that the cluster
	// spec has been updated in an unsupported way. That cannot be
	// reconciled.
	UnsupportedChangeClusterError ClusterStatusError = "UnsupportedChange"

	// CreateClusterError indicates that an error was encountered
	// when trying to create the cluster.
	CreateClusterError ClusterStatusError = "CreateError"

	// UpdateClusterError indicates that an error was encountered
	// when trying to update the cluster.
	UpdateClusterError ClusterStatusError = "UpdateError"

	// DeleteClusterError indicates that an error was encountered
	// when trying to delete the cluster.
	DeleteClusterError ClusterStatusError = "DeleteError"
)

type MachineSetStatusError string

const (
	// Represents that the combination of configuration in the MachineTemplateSpec
	// is not supported by this cluster. This is not a transient error, but
	// indicates a state that must be fixed before progress can be made.
	//
	// Example: the ProviderSpec specifies an instance type that doesn't exist.
	InvalidConfigurationMachineSetError MachineSetStatusError = "InvalidConfiguration"
)

type MachineDeploymentStrategyType string

const (
	// Replace the old MachineSet by new one using rolling update
	// i.e. gradually scale down the old MachineSet and scale up the new one.
	RollingUpdateMachineDeploymentStrategyType MachineDeploymentStrategyType = "RollingUpdate"
)

// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// Machine is the Schema for the machines API
// +k8s:openapi-gen=true
// +kubebuilder:subresource:status
// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase",description="Phase of machine"
// +kubebuilder:printcolumn:name="Type",type="string",JSONPath=".metadata.labels['machine\\.openshift\\.io/instance-type']",description="Type of instance"
// +kubebuilder:printcolumn:name="Region",type="string",JSONPath=".metadata.labels['machine\\.openshift\\.io/region']",description="Region associated with machine"
// +kubebuilder:printcolumn:name="Zone",type="string",JSONPath=".metadata.labels['machine\\.openshift\\.io/zone']",description="Zone associated with machine"
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Machine age"
// +kubebuilder:printcolumn:name="Node",type="string",JSONPath=".status.nodeRef.name",description="Node associated with machine",priority=1
// +kubebuilder:printcolumn:name="ProviderID",type="string",JSONPath=".spec.providerID",description="Provider ID of machine created in cloud provider",priority=1
// +kubebuilder:printcolumn:name="State",type="string",JSONPath=".metadata.annotations['machine\\.openshift\\.io/instance-state']",description="State of instance",priority=1
// Compatibility level 2: Stable within a major release for a minimum of 9 months or 3 minor releases (whichever is longer).
// +openshift:compatibility-gen:level=2
type Machine struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty"`

	Spec   MachineSpec   `json:"spec,omitempty"`
	Status MachineStatus `json:"status,omitempty"`
}

// MachineSpec defines the desired state of Machine
type MachineSpec struct {
	// ObjectMeta will autopopulate the Node created. Use this to
	// indicate what labels, annotations, name prefix, etc., should be used
	// when creating the Node.
	// +optional
	ObjectMeta `json:"metadata,omitempty"`

	// LifecycleHooks allow users to pause operations on the machine at
	// certain predefined points within the machine lifecycle.
	// +optional
	LifecycleHooks LifecycleHooks `json:"lifecycleHooks,omitempty"`

	// The list of the taints to be applied to the corresponding Node in additive
	// manner. This list will not overwrite any other taints added to the Node on
	// an ongoing basis by other entities. These taints should be actively reconciled
	// e.g. if you ask the machine controller to apply a taint and then manually remove
	// the taint the machine controller will put it back) but not have the machine controller
	// remove any taints
	// +optional
	Taints []corev1.Taint `json:"taints,omitempty"`

	// ProviderSpec details Provider-specific configuration to use during node creation.
	// +optional
	ProviderSpec ProviderSpec `json:"providerSpec"`

	// ProviderID is the identification ID of the machine provided by the provider.
	// This field must match the provider ID as seen on the node object corresponding to this machine.
	// This field is required by higher level consumers of cluster-api. Example use case is cluster autoscaler
	// with cluster-api as provider. Clean-up logic in the autoscaler compares machines to nodes to find out
	// machines at provider which could not get registered as Kubernetes nodes. With cluster-api as a
	// generic out-of-tree provider for autoscaler, this field is required by autoscaler to be
	// able to have a provider view of the list of machines. Another list of nodes is queried from the k8s apiserver
	// and then a comparison is done to find out unregistered machines and are marked for delete.
	// This field will be set by the actuators and consumed by higher level entities like autoscaler that will
	// be interfacing with cluster-api as generic provider.
	// +optional
	ProviderID *string `json:"providerID,omitempty"`
}

// LifecycleHooks allow users to pause operations on the machine at
// certain prefedined points within the machine lifecycle.
type LifecycleHooks struct {
	// PreDrain hooks prevent the machine from being drained.
	// This also blocks further lifecycle events, such as termination.
	// +optional
	PreDrain []LifecycleHook `json:"preDrain,omitempty"`

	// PreTerminate hooks prevent the machine from being terminated.
	// PreTerminate hooks be actioned after the Machine has been drained.
	// +optional
	PreTerminate []LifecycleHook `json:"preTerminate,omitempty"`
}

// LifecycleHook represents a single instance of a lifecycle hook
type LifecycleHook struct {
	// Name defines a unique name for the lifcycle hook.
	// The name should be unique and descriptive, ideally 1-3 words, in CamelCase or
	// it may be namespaced, eg. foo.example.com/CamelCase.
	// Names must be unique and should only be managed by a single entity.
	// +kubebuilder:validation:Pattern=`^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$`
	// +kubebuilder:validation:MinLength:=3
	// +kubebuilder:validation:MaxLength:=256
	// +required
	Name string `json:"name"`

	// Owner defines the owner of the lifecycle hook.
	// This should be descriptive enough so that users can identify
	// who/what is responsible for blocking the lifecycle.
	// This could be the name of a controller (e.g. clusteroperator/etcd)
	// or an administrator managing the hook.
	// +kubebuilder:validation:MinLength:=3
	// +kubebuilder:validation:MaxLength:=512
	// +required
	Owner string `json:"owner"`
}

// MachineStatus defines the observed state of Machine
type MachineStatus struct {
	// NodeRef will point to the corresponding Node if it exists.
	// +optional
	NodeRef *corev1.ObjectReference `json:"nodeRef,omitempty"`

	// LastUpdated identifies when this status was last observed.
	// +optional
	LastUpdated *metav1.Time `json:"lastUpdated,omitempty"`

	// ErrorReason will be set in the event that there is a terminal problem
	// reconciling the Machine and will contain a succinct value suitable
	// for machine interpretation.
	//
	// This field should not be set for transitive errors that a controller
	// faces that are expected to be fixed automatically over
	// time (like service outages), but instead indicate that something is
	// fundamentally wrong with the Machine's spec or the configuration of
	// the controller, and that manual intervention is required. Examples
	// of terminal errors would be invalid combinations of settings in the
	// spec, values that are unsupported by the controller, or the
	// responsible controller itself being critically misconfigured.
	//
	// Any transient errors that occur during the reconciliation of Machines
	// can be added as events to the Machine object and/or logged in the
	// controller's output.
	// +optional
	ErrorReason *MachineStatusError `json:"errorReason,omitempty"`

	// ErrorMessage will be set in the event that there is a terminal problem
	// reconciling the Machine and will contain a more verbose string suitable
	// for logging and human consumption.
	//
	// This field should not be set for transitive errors that a controller
	// faces that are expected to be fixed automatically over
	// time (like service outages), but instead indicate that something is
	// fundamentally wrong with the Machine's spec or the configuration of
	// the controller, and that manual intervention is required. Examples
	// of terminal errors would be invalid combinations of settings in the
	// spec, values that are unsupported by the controller, or the
	// responsible controller itself being critically misconfigured.
	//
	// Any transient errors that occur during the reconciliation of Machines
	// can be added as events to the Machine object and/or logged in the
	// controller's output.
	// +optional
	ErrorMessage *string `json:"errorMessage,omitempty"`

	// ProviderStatus details a Provider-specific status.
	// It is recommended that providers maintain their
	// own versioned API types that should be
	// serialized/deserialized from this field.
	// +optional
	// +kubebuilder:validation:XPreserveUnknownFields
	ProviderStatus *runtime.RawExtension `json:"providerStatus,omitempty"`

	// Addresses is a list of addresses assigned to the machine. Queried from cloud provider, if available.
	// +optional
	Addresses []corev1.NodeAddress `json:"addresses,omitempty"`

	// LastOperation describes the last-operation performed by the machine-controller.
	// This API should be useful as a history in terms of the latest operation performed on the
	// specific machine. It should also convey the state of the latest-operation for example if
	// it is still on-going, failed or completed successfully.
	// +optional
	LastOperation *LastOperation `json:"lastOperation,omitempty"`

	// Phase represents the current phase of machine actuation.
	// One of: Failed, Provisioning, Provisioned, Running, Deleting
	// +optional
	Phase *string `json:"phase,omitempty"`

	// Conditions defines the current state of the Machine
	Conditions Conditions `json:"conditions,omitempty"`
}

// LastOperation represents the detail of the last performed operation on the MachineObject.
type LastOperation struct {
	// Description is the human-readable description of the last operation.
	Description *string `json:"description,omitempty"`

	// LastUpdated is the timestamp at which LastOperation API was last-updated.
	LastUpdated *metav1.Time `json:"lastUpdated,omitempty"`

	// State is the current status of the last performed operation.
	// E.g. Processing, Failed, Successful etc
	State *string `json:"state,omitempty"`

	// Type is the type of operation which was last performed.
	// E.g. Create, Delete, Update etc
	Type *string `json:"type,omitempty"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// MachineList contains a list of Machine
// Compatibility level 2: Stable within a major release for a minimum of 9 months or 3 minor releases (whichever is longer).
// +openshift:compatibility-gen:level=2
type MachineList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata,omitempty"`
	Items           []Machine `json:"items"`
}


text:
<!doctype html>

<meta name="viewport" content="width=device-width">

  <input type="button" id="btnBack" value="Back"/>

    <input type="button" id="btnPrev" value="<"/>
    <input type="text"  id="textTest" readonly />
    <input type="button" id="btnNext" value=">"/>

   <input type="button" id="btnExit" value="Exit"/>
  Open Web Test

  <textarea class="listhide suitehide" id="testinfo" rows=4 disabled>
  </textarea>

  <input type="button"  id="btnRun" value="Run"/>
  <input type="button" id="btnSave" value="Save"/>
  <input type="button" id="btnPass" value="PASS"/>
  <input type="button" id="btnFail" value="FAIL"/>
  <input type="button" id="btnBlock" value="BLOCK"/>


text:
/**
 * Main style.
 *
 */
html,
body {
  height: 100%;
}

body,
app-root {
  position: relative;
  font: 12px/1.5em "Helvetica Neue",Helvetica,"Hiragino Sans GB","Segoe UI","Microsoft Yahei",Tahoma,Arial,STHeiti,sans-serif;
  background: #fff;
  overflow-x: hidden;
}


text:
layout: default
---

Black SPIDER Cross Bracelet

$19.99

Black stained wooden beads with woodgrain seperators finished with wooden cross charm.

    Add To Cart


text:
class TestSearchMapping

  include Serch::Mappable

  map :author, :a, [:b, true], [:c, 'David']

  map [:now, :time], :a, :b

  map :d

  map_from :a, :nested_map

  def a
    self
  end

  def b(c = false)
    if c
      self.class
    else
      self
    end
  end

  def self.c(name)
    name
  end

  def d
    "lol"
  end

  def now
    Time.now.to_i
  end

  def time
    self.now
  end

  def nested_map
    AnotherTestSearchMapping.new
  end

end

class AnotherTestSearchMapping

  include Serch::Mappable

  map :special

  def special
    1
  end

end

describe Serch::Mapping do

  before do
    @test = TestSearchMapping.new
  end

  subject { @test.to_map }

  it { should be_a Hash }

  it { should_not be_empty }

  it "should contain the correct keys" do
    expect(subject.keys).to include :author, :now, :time, :d, :special
  end

  it "should contain the correct author value" do
    expect(subject[:author]).to include "David"
  end

  it "should contain the now value" do
    expect(subject[:now]).to_not be_nil
  end

  it "should contain the time value" do
    expect(subject[:time]).to_not be_nil
  end

  it "should contain the correct time values" do
    expect(subject[:now]).to eq subject[:time]
  end

  it "should contain the correct value for d" do
    expect(subject[:d]).to eq "lol"
  end

  it "should contain the correct value for special" do
    expect(subject[:special]).to eq 1
  end

end


text: Artifact ID bla bla bla Adiel


text:
.rule-with-all-defined-functions {
  attr: -85;
}

.rule-with-some-undefined-functions {
  attr: subtract(30, user-need-handle-this-case-by-self(200));
}


text:
package net.mindengine.galen.suite;

import java.awt.Dimension;
import java.util.List;

import net.mindengine.galen.browser.BrowserFactory;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

public class GalenPageTest {

    private String title;
    private String url;
    private Dimension screenSize;
    private List<GalenPageAction> actions;
    private BrowserFactory browserFactory;

    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public Dimension getScreenSize() {
        return screenSize;
    }
    public void setScreenSize(Dimension screenSize) {
        this.screenSize = screenSize;
    }
    public List<GalenPageAction> getActions() {
        return actions;
    }
    public void setActions(List<GalenPageAction> actions) {
        this.actions = actions;
    }
    public GalenPageTest withActions(List<GalenPageAction> actions) {
        setActions(actions);
        return this;
    }

    public GalenPageTest withSize(Dimension size) {
        setScreenSize(size);
        return this;
    }
    public GalenPageTest withUrl(String url) {
        this.url = url;
        return this;
    }
    public GalenPageTest withSize(int width, int height) {
        this.screenSize = new Dimension(width, height);
        return this;
    }
    public GalenPageTest withBrowserFactory(BrowserFactory browserFactory) {
        this.setBrowserFactory(browserFactory);
        return this;
    }
    public BrowserFactory getBrowserFactory() {
        return browserFactory;
    }
    public void setBrowserFactory(BrowserFactory browserFactory) {
        this.browserFactory = browserFactory;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder() //@formatter:off
            .append(this.actions)
            .append(this.browserFactory)
            .append(this.screenSize)
            .append(this.url)
            .toHashCode(); //@formatter:on
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this) //@formatter:off
            .append("url", this.url)
            .append("screenSize", this.screenSize)
            .append("browserFactory", this.browserFactory)
            .append("actions", this.actions)
            .toString(); //@formatter:on
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof GalenPageTest)) {
            return false;
        }
        GalenPageTest rhs = (GalenPageTest)obj;

        return new EqualsBuilder() //@formatter:off
            .append(this.actions, rhs.actions)
            .append(this.browserFactory, rhs.browserFactory)
            .append(this.screenSize, rhs.screenSize)
            .append(this.url, rhs.url)
            .isEquals(); //@formatter:on
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public GalenPageTest withTitle(String title) {
        setTitle(title);
        return this;
    }

}


text:
/* Generated by Font Squirrel (https://www.fontsquirrel.com) on March 21, 2017 */

@font-face {
    font-family: 'LT Tofino';
    src: url('tofino-book-webfont.woff2') format('woff2');
    font-weight: 300;
    font-style: normal;
    font-stretch: normal;
    font-kerning: normal;
    font-variant: normal;
}

@font-face {
    font-family: 'LT Tofino';
    src: url('tofino-bookitalic-webfont.woff2') format('woff2');
    font-weight: 300;
    font-style: italic;
    font-stretch: normal;
    font-kerning: normal;
    font-variant: normal;
}

@font-face {
    font-family: 'LT Tofino';
    src: url('tofino-regular-webfont.woff2') format('woff2');
    font-weight: 400;
    font-style: normal;
    font-stretch: normal;
    font-kerning: normal;
    font-variant: normal;
}

@font-face {
    font-family: 'LT Tofino';
    src: url('tofino-regularitalic-webfont.woff2') format('woff2');
    font-weight: 400;
    font-style: italic;
    font-stretch: normal;
    font-kerning: normal;
    font-variant: normal;
}

@font-face {
    font-family: 'LT Tofino';
    src: url('tofino-medium-webfont.woff2') format('woff2');
    font-weight: 500;
    font-style: normal;
    font-stretch: normal;
    font-kerning: normal;
    font-variant: normal;
}

@font-face {
    font-family: 'LT Tofino';
    src: url('tofino-mediumitalic-webfont.woff2') format('woff2');
    font-weight: 500;
    font-style: italic;
    font-stretch: normal;
    font-kerning: normal;
    font-variant: normal;
}

@font-face {
    font-family: 'LT Tofino';
    src: url('tofino-bold-webfont.woff2') format('woff2');
    font-weight: 600;
    font-style: normal;
    font-stretch: normal;
    font-kerning: normal;
    font-variant: normal;
}

@font-face {
    font-family: 'LT Tofino';
    src: url('tofino-bolditalic-webfont.woff2') format('woff2');
    font-weight: 600;
    font-style: italic;
    font-stretch: normal;
    font-kerning: normal;
    font-variant: normal;
}

@font-face {
    font-family: 'LT Tofino';
    src: url('tofino-black-webfont.woff2') format('woff2');
    font-weight: 800;
    font-style: normal;
    font-stretch: normal;
    font-kerning: normal;
    font-variant: normal;
}

@font-face {
    font-family: 'LT Tofino';
    src: url('tofino-blackitalic-webfont.woff2') format('woff2');
    font-weight: 800;
    font-style: italic;
    font-stretch: normal;
    font-kerning: normal;
    font-variant: normal;
}

.tofino {
  font-family: "LT Tofino", -apple-system,BlinkMacSystemFont,avenir next,avenir,helvetica neue,helvetica,ubuntu,roboto,noto,segoe ui,arial,sans-serif;
  font-weight: 300;
}

.tofino.b,
h1,
h2,
h3,
h4,
h5,
h6 {
  font-weight: 500;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
  <report_format_detail>
    <FileFormat>
      <FormatID>2260</FormatID>
      <FormatName>QuarkXPress Document</FormatName>
      <FormatVersion>1-2</FormatVersion>
      <FormatAliases>
      </FormatAliases>
      <FormatFamilies>
      </FormatFamilies>
      <FormatTypes>Presentation</FormatTypes>
      <FormatDisclosure>
      </FormatDisclosure>
      <FormatDescription>QuarkXPress is desktop publishing software for creating and editing page layouts that can be run on Mac and Windows operating systems. It was first released in 1987. It can be used to creating a variety of layouts, from single-page flyers to multi-media projects required for magazines, newspapers and catalogues. Versions 1-3 were available on Macintosh only and may lack an extension.</FormatDescription>
      <BinaryFileFormat>
      </BinaryFileFormat>
      <ByteOrders>
      </ByteOrders>
      <ReleaseDate>
      </ReleaseDate>
      <WithdrawnDate>
      </WithdrawnDate>
      <ProvenanceSourceID>220</ProvenanceSourceID>
      <ProvenanceName>The Church of Jesus Christ of Latter-Day Saints / The Church of Jesus Christ of Latter-Day Saints</ProvenanceName>
      <ProvenanceSourceDate>30 Sep 2020</ProvenanceSourceDate>
      <ProvenanceDescription>
      </ProvenanceDescription>
      <LastUpdatedDate>30 Sep 2020</LastUpdatedDate>
      <FormatNote>
      </FormatNote>
      <FormatRisk>
      </FormatRisk>
      <TechnicalEnvironment>
      </TechnicalEnvironment>
      <FileFormatIdentifier>
        <Identifier>application/vnd.Quark.QuarkXPress</Identifier>
        <IdentifierType>MIME</IdentifierType>
      </FileFormatIdentifier>
      <FileFormatIdentifier>
        <Identifier>fmt/1442</Identifier>
        <IdentifierType>PUID</IdentifierType>
      </FileFormatIdentifier>
      <Developers>
        <DeveloperID>91</DeveloperID>
        <DeveloperName>
        </DeveloperName>
        <OrganisationName>Quark, Inc</OrganisationName>
        <DeveloperCompoundName>Quark, Inc</DeveloperCompoundName>
      </Developers>
      <Support>
        <SupportID>91</SupportID>
        <SupportName>
        </SupportName>
        <OrganisationName>Quark, Inc</OrganisationName>
        <SupportCompoundName>Quark, Inc</SupportCompoundName>
      </Support>
      <InternalSignature>
        <SignatureID>1801</SignatureID>
        <SignatureName>QuarkXPress 1-2 variant 1</SignatureName>
        <SignatureNote>BOF: 0x001C001C</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>2095</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>0</MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>001C001C</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
      <InternalSignature>
        <SignatureID>1802</SignatureID>
        <SignatureName>QuarkXPress 1-2 variant 2</SignatureName>
        <SignatureNote>BOF: 0x00260026</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>2094</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>0</MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>00260026</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
    </FileFormat>
    <SearchCriteria>Criteria</SearchCriteria>
  </report_format_detail>
</PRONOM-Report>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Writ. 3 (Syn. Stip. Polyporoids) 126 (1912)

#### Original name
Fomes paulensis Henn.

### Remarks
null


text:
package com.bbn.kbp.events;

import com.bbn.bue.common.HasDocID;
import com.bbn.bue.common.TextGroupImmutable;
import com.bbn.bue.common.symbols.Symbol;
import com.bbn.nlp.events.HasEventArgType;
import com.bbn.nlp.events.HasEventType;

import com.google.common.base.Function;

import org.immutables.func.Functional;
import org.immutables.value.Value;

@Value.Immutable
@Functional
@TextGroupImmutable
public abstract class DocLevelEventArg implements HasDocID, HasEventType, HasEventArgType,
    WithDocLevelEventArg {

  public abstract Symbol docID();

  public abstract Symbol eventArgumentType();

  public abstract Symbol eventType();

  public abstract Symbol realis();

  public abstract String corefID();

  @Override
  public String toString() {
    return docID().asString() + "/" + eventType().asString()
        + "-" + eventArgumentType().asString() + "/" + realis().asString()
        + "/" + corefID();
  }

  public enum TypeRoleFunction implements Function<DocLevelEventArg, String> {
    INSTANCE;

    @Override
    public String apply(final DocLevelEventArg input) {
      return input.eventType().asString() + "-" + input.eventArgumentType().asString();
    }
  }

  public static class Builder extends ImmutableDocLevelEventArg.Builder {

  }
}


text:
/*Pop Up Machine Content CSS*/

@import "https://fonts.googleapis.com/css?family=Pacifico|Dosis";
.box {
    width: 30%;
    margin: 0 auto;
    background: rgba(255, 255, 255, 0.2);
    padding: 35px;
    border: 2px solid #fff;
    border-radius: 20px/50px;
    background-clip: padding-box;
    text-align: center;
}

/*controls how the popupStockEdit window is hidden when not activated*/

.overlay {
    position: fixed;
    top: -130px;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.7);
    /*transition: opacity 300ms;*/
    /*Take the transition away to disable phantom images */
    visibility: hidden;
    opacity: 0;
    z-index: 1;
}

.overlay:target {
    visibility: visible;
    opacity: 1;
}

/*This edits the popup meny */

.popup {
    margin: 10em auto;
    padding-top: 1em;
    padding-left: 2em;
    padding-right: 2em;
    padding-bottom: 1em;
    background: rgb(116, 70, 16);
    border-radius: 5px;
    width: 15%;
    min-width: 15em;
    position: relative;
    transition: all 1s ease-in-out;
    text-align: center;
    font-family: Dosis, sans-serif;
}

/*This edits the text in the top of the popup */

.popup h2 {
    margin: 1em;
    color: #E8E1CB;
    font-size: 27px;
}

.popup h3 {
    font-size: 20px;
    color: #E8E1CB;
    font-weight: bold;
    margin: 1em;
}

/*This edits the exit-cross in the top */

.popup #closeCross {
    position: absolute;
    top: 0.2em;
    right: 0.2em;
    height: 1.5em;
    width: 1.5em;
    transition: all 200ms;
    font-size: 40px;
    text-decoration: none;
    color: #E8E1CB;
    background-color: #F03A47;
    border-radius: 6px;
    box-shadow: 1px 1px 10px #000000;
}

/*This highlights the exit-cross when hovered over */

.popup #closeCross:hover {
    color: rgb(116, 70, 16);
}

.popup .content {
    max-height: 100%;
    overflow: auto;
}

@media screen and (max-width: 700px) {
    .box {
        width: 70%;
    }
    .popup {
        width: 70%;
    }
}

/*First element that has been clicked*/

popupUserEdit.product {
    margin: .1em;
    width: 43%;
    /*For some reason, this magic number works...*/
}

popupUserEdit.slotElement {
    background-color: #E8E1CB;
    text-align: left;
}

popupUserEdit.slotLeft {
    background-color: #E8E1CB;
    margin: auto;
}

/*Buttons in bottom*/

#save {
    margin: .1em;
    font-size: 25px;
    font-weight: bold;
    color: #E8E1CB;
    font-family: Dosis, sans-serif;
    /* Just to have something to work with, otherwise links and non-links gor different fonts*/
    border: 1px solid #E8E1CB;
    border-radius: 1em;
    padding: .1em .3em .1em;
    background-color: rgb(0, 132, 0);
    text-decoration: none;
    box-shadow: 4px 4px 5px #000000;
}

#cancel {
    margin: .1em;
    font-size: 25px;
    font-weight: bold;
    color: #E8E1CB;
    font-family: Dosis, sans-serif;
    /* Just to have something to work with, otherwise links and non-links gor different fonts*/
    border: 1px solid #E8E1CB;
    border-radius: 1em;
    padding: .1em .3em .1em;
    background-color: #F03A47;
    text-decoration: none;
    box-shadow: 4px 4px 5px #000000;
}


text:
package org.apache.hadoop.hbase.client;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.coprocessor.RegionObserver;
import org.apache.hadoop.hbase.regionserver.MiniBatchOperationInProgress;
import org.apache.hadoop.hbase.testclassification.ClientTests;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Threads;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;

import org.apache.hbase.thirdparty.com.google.common.io.Closeables;

@Category({ MediumTests.class, ClientTests.class })
public class TestAsyncTableNoncedRetry {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
    HBaseClassTestRule.forClass(TestAsyncTableNoncedRetry.class);

  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();

  private static final TableName TABLE_NAME = TableName.valueOf("async");

  private static final byte[] FAMILY = Bytes.toBytes("cf");

  private static final byte[] QUALIFIER = Bytes.toBytes("cq");

  private static final byte[] QUALIFIER2 = Bytes.toBytes("cq2");

  private static final byte[] QUALIFIER3 = Bytes.toBytes("cq3");

  private static final byte[] VALUE = Bytes.toBytes("value");

  private static AsyncConnection ASYNC_CONN;

  @Rule
  public TestName testName = new TestName();

  private byte[] row;

  private static final AtomicInteger CALLED = new AtomicInteger();

  private static final long SLEEP_TIME = 2000;

  private static final long RPC_TIMEOUT = SLEEP_TIME / 4 * 3; // three fourths of the sleep time

  // The number of miniBatchOperations that are executed in a RegionServer
  private static int miniBatchOperationCount;

  public static final class SleepOnceCP implements RegionObserver, RegionCoprocessor {

    @Override
    public Optional<RegionObserver> getRegionObserver() {
      return Optional.of(this);
    }

    @Override
    public void postBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c,
      MiniBatchOperationInProgress<Mutation> miniBatchOp) {
      // We sleep when the last of the miniBatchOperations is executed
      if (CALLED.getAndIncrement() == miniBatchOperationCount - 1) {
        Threads.sleepWithoutInterrupt(SLEEP_TIME);
      }
    }
  }

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    TEST_UTIL.startMiniCluster(1);
    TEST_UTIL.getAdmin()
      .createTable(TableDescriptorBuilder.newBuilder(TABLE_NAME)
        .setColumnFamily(ColumnFamilyDescriptorBuilder.of(FAMILY))
        .setCoprocessor(SleepOnceCP.class.getName()).build());
    TEST_UTIL.waitTableAvailable(TABLE_NAME);
    ASYNC_CONN = ConnectionFactory.createAsyncConnection(TEST_UTIL.getConfiguration()).get();
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    Closeables.close(ASYNC_CONN, true);
    TEST_UTIL.shutdownMiniCluster();
  }

  @Before
  public void setUp() throws IOException, InterruptedException {
    row = Bytes.toBytes(testName.getMethodName().replaceAll("[^0-9A-Za-z]", "_"));
    CALLED.set(0);
  }

  @Test
  public void testAppend() throws InterruptedException, ExecutionException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    Result result = table.append(new Append(row).addColumn(FAMILY, QUALIFIER, VALUE)).get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertArrayEquals(VALUE, result.getValue(FAMILY, QUALIFIER));
  }

  @Test
  public void testAppendWhenReturnResultsEqualsFalse()
    throws InterruptedException, ExecutionException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    Result result = table
      .append(new Append(row).addColumn(FAMILY, QUALIFIER, VALUE).setReturnResults(false)).get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertTrue(result.isEmpty());
  }

  @Test
  public void testIncrement() throws InterruptedException, ExecutionException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    long result = table.incrementColumnValue(row, FAMILY, QUALIFIER, 1L).get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertEquals(1L, result);
  }

  @Test
  public void testIncrementWhenReturnResultsEqualsFalse()
    throws InterruptedException, ExecutionException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    Result result = table
      .increment(new Increment(row).addColumn(FAMILY, QUALIFIER, 1L).setReturnResults(false)).get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertTrue(result.isEmpty());
  }

  @Test
  public void testIncrementInRowMutations()
    throws InterruptedException, ExecutionException, IOException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setWriteRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    Result result =
      table.mutateRow(new RowMutations(row).add(new Increment(row).addColumn(FAMILY, QUALIFIER, 1L))
        .add((Mutation) new Delete(row).addColumn(FAMILY, QUALIFIER2))).get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertEquals(1L, Bytes.toLong(result.getValue(FAMILY, QUALIFIER)));
  }

  @Test
  public void testAppendInRowMutations()
    throws InterruptedException, ExecutionException, IOException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setWriteRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    Result result =
      table.mutateRow(new RowMutations(row).add(new Append(row).addColumn(FAMILY, QUALIFIER, VALUE))
        .add((Mutation) new Delete(row).addColumn(FAMILY, QUALIFIER2))).get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertArrayEquals(VALUE, result.getValue(FAMILY, QUALIFIER));
  }

  @Test
  public void testIncrementAndAppendInRowMutations()
    throws InterruptedException, ExecutionException, IOException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setWriteRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    Result result =
      table.mutateRow(new RowMutations(row).add(new Increment(row).addColumn(FAMILY, QUALIFIER, 1L))
        .add(new Append(row).addColumn(FAMILY, QUALIFIER2, VALUE))).get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertEquals(1L, Bytes.toLong(result.getValue(FAMILY, QUALIFIER)));
    assertArrayEquals(VALUE, result.getValue(FAMILY, QUALIFIER2));
  }

  @Test
  public void testIncrementInCheckAndMutate() throws InterruptedException, ExecutionException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    CheckAndMutateResult result =
      table.checkAndMutate(CheckAndMutate.newBuilder(row).ifNotExists(FAMILY, QUALIFIER2)
        .build(new Increment(row).addColumn(FAMILY, QUALIFIER, 1L))).get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertTrue(result.isSuccess());
    assertEquals(1L, Bytes.toLong(result.getResult().getValue(FAMILY, QUALIFIER)));
  }

  @Test
  public void testAppendInCheckAndMutate() throws InterruptedException, ExecutionException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    CheckAndMutateResult result =
      table.checkAndMutate(CheckAndMutate.newBuilder(row).ifNotExists(FAMILY, QUALIFIER2)
        .build(new Append(row).addColumn(FAMILY, QUALIFIER, VALUE))).get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertTrue(result.isSuccess());
    assertArrayEquals(VALUE, result.getResult().getValue(FAMILY, QUALIFIER));
  }

  @Test
  public void testIncrementInRowMutationsInCheckAndMutate()
    throws InterruptedException, ExecutionException, IOException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    CheckAndMutateResult result =
      table.checkAndMutate(CheckAndMutate.newBuilder(row).ifNotExists(FAMILY, QUALIFIER3)
        .build(new RowMutations(row).add(new Increment(row).addColumn(FAMILY, QUALIFIER, 1L))
          .add((Mutation) new Delete(row).addColumn(FAMILY, QUALIFIER2))))
        .get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertTrue(result.isSuccess());
    assertEquals(1L, Bytes.toLong(result.getResult().getValue(FAMILY, QUALIFIER)));
  }

  @Test
  public void testAppendInRowMutationsInCheckAndMutate()
    throws InterruptedException, ExecutionException, IOException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    CheckAndMutateResult result =
      table.checkAndMutate(CheckAndMutate.newBuilder(row).ifNotExists(FAMILY, QUALIFIER3)
        .build(new RowMutations(row).add(new Append(row).addColumn(FAMILY, QUALIFIER, VALUE))
          .add((Mutation) new Delete(row).addColumn(FAMILY, QUALIFIER2))))
        .get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertTrue(result.isSuccess());
    assertArrayEquals(VALUE, result.getResult().getValue(FAMILY, QUALIFIER));
  }

  @Test
  public void testIncrementAndAppendInRowMutationsInCheckAndMutate()
    throws InterruptedException, ExecutionException, IOException {
    assertEquals(0, CALLED.get());
    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 1;
    CheckAndMutateResult result =
      table.checkAndMutate(CheckAndMutate.newBuilder(row).ifNotExists(FAMILY, QUALIFIER3)
        .build(new RowMutations(row).add(new Increment(row).addColumn(FAMILY, QUALIFIER, 1L))
          .add(new Append(row).addColumn(FAMILY, QUALIFIER2, VALUE))))
        .get();

    // make sure we called twice and the result is still correct
    assertEquals(2, CALLED.get());
    assertTrue(result.isSuccess());
    assertEquals(1L, Bytes.toLong(result.getResult().getValue(FAMILY, QUALIFIER)));
    assertArrayEquals(VALUE, result.getResult().getValue(FAMILY, QUALIFIER2));
  }

  @Test
  public void testBatch() throws InterruptedException, ExecutionException, IOException {
    byte[] row2 = Bytes.toBytes(Bytes.toString(row) + "2");
    byte[] row3 = Bytes.toBytes(Bytes.toString(row) + "3");
    byte[] row4 = Bytes.toBytes(Bytes.toString(row) + "4");
    byte[] row5 = Bytes.toBytes(Bytes.toString(row) + "5");
    byte[] row6 = Bytes.toBytes(Bytes.toString(row) + "6");

    assertEquals(0, CALLED.get());

    AsyncTable<?> table = ASYNC_CONN.getTableBuilder(TABLE_NAME)
      .setRpcTimeout(RPC_TIMEOUT, TimeUnit.MILLISECONDS).build();

    miniBatchOperationCount = 6;
    List<Object> results =
      table.batchAll(Arrays.asList(new Append(row).addColumn(FAMILY, QUALIFIER, VALUE),
        new Increment(row2).addColumn(FAMILY, QUALIFIER, 1L),
        new RowMutations(row3).add(new Increment(row3).addColumn(FAMILY, QUALIFIER, 1L))
          .add(new Append(row3).addColumn(FAMILY, QUALIFIER2, VALUE)),
        CheckAndMutate.newBuilder(row4).ifNotExists(FAMILY, QUALIFIER2)
          .build(new Increment(row4).addColumn(FAMILY, QUALIFIER, 1L)),
        CheckAndMutate.newBuilder(row5).ifNotExists(FAMILY, QUALIFIER2)
          .build(new Append(row5).addColumn(FAMILY, QUALIFIER, VALUE)),
        CheckAndMutate.newBuilder(row6).ifNotExists(FAMILY, QUALIFIER3)
          .build(new RowMutations(row6).add(new Increment(row6).addColumn(FAMILY, QUALIFIER, 1L))
            .add(new Append(row6).addColumn(FAMILY, QUALIFIER2, VALUE)))))
        .get();

    // make sure we called twice and the result is still correct

    // should be called 12 times as 6 miniBatchOperations are called twice
    assertEquals(12, CALLED.get());

    assertArrayEquals(VALUE, ((Result) results.get(0)).getValue(FAMILY, QUALIFIER));

    assertEquals(1L, Bytes.toLong(((Result) results.get(1)).getValue(FAMILY, QUALIFIER)));

    assertEquals(1L, Bytes.toLong(((Result) results.get(2)).getValue(FAMILY, QUALIFIER)));
    assertArrayEquals(VALUE, ((Result) results.get(2)).getValue(FAMILY, QUALIFIER2));

    CheckAndMutateResult result;

    result = (CheckAndMutateResult) results.get(3);
    assertTrue(result.isSuccess());
    assertEquals(1L, Bytes.toLong(result.getResult().getValue(FAMILY, QUALIFIER)));

    result = (CheckAndMutateResult) results.get(4);
    assertTrue(result.isSuccess());
    assertArrayEquals(VALUE, result.getResult().getValue(FAMILY, QUALIFIER));

    result = (CheckAndMutateResult) results.get(5);
    assertTrue(result.isSuccess());
    assertEquals(1L, Bytes.toLong(result.getResult().getValue(FAMILY, QUALIFIER)));
    assertArrayEquals(VALUE, result.getResult().getValue(FAMILY, QUALIFIER2));
  }
}


text:
package ca.uhn.fhir.mdm.rules.matcher;

import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.r4.model.BaseDateTimeType;
import org.hl7.fhir.r4.model.DateTimeType;
import org.hl7.fhir.r4.model.DateType;

public class HapiDateMatcherR4 {
	// TODO KHS code duplication (tried generalizing it with generics, but it got too convoluted)
	public boolean match(IBase theLeftBase, IBase theRightBase) {
		if (theLeftBase instanceof BaseDateTimeType && theRightBase instanceof BaseDateTimeType) {
			BaseDateTimeType leftDate = (BaseDateTimeType) theLeftBase;
			BaseDateTimeType rightDate = (BaseDateTimeType) theRightBase;
			int comparison = leftDate.getPrecision().compareTo(rightDate.getPrecision());
			if (comparison == 0) {
				return leftDate.getValueAsString().equals(rightDate.getValueAsString());
			}
			BaseDateTimeType leftPDate;
			BaseDateTimeType rightPDate;
			//Left date is coarser
			if (comparison < 0) {
				leftPDate = leftDate;
				if (rightDate instanceof DateType) {
					rightPDate = new DateType(rightDate.getValue(), leftDate.getPrecision());
				} else {
					rightPDate = new DateTimeType(rightDate.getValue(), leftDate.getPrecision());
				}
			//Right date is coarser
			} else {
				rightPDate = rightDate;
				if (leftDate instanceof DateType) {
					leftPDate = new DateType(leftDate.getValue(), rightDate.getPrecision());
				} else {
					leftPDate = new DateTimeType(leftDate.getValue(), rightDate.getPrecision());
				}
			}
			return leftPDate.getValueAsString().equals(rightPDate.getValueAsString());
		}

		return false;
	}
}


text:
const mongoose = require('mongoose')

mongoose.Promise = require('bluebird')
const log = require('./log')(module)
const config = require('./config')

let connectToDB = function () {
    mongoose.connect(config.get('mongoose:uri'))
}

mongoose.connection.on('error', (err) => {
    log.error(err.message)
})

mongoose.connection.on('connected', () => {
    clearInterval(setConnection)
    log.info('Connection was established')
})

let setConnection = setInterval(connectToDB, 3000)

module.exports = mongoose


text:
<!doctype html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <link type="text/css" rel="stylesheet" href="Restaurantedadiva.css">

    <title>Web Application Starter Project</title>

        Your web browser must have JavaScript enabled
        in order for this application to display correctly.

Web Application Starter Project

        Please enter your name:


text:
extern int crypto_onetimeauth_poly1305(unsigned char *,const unsigned char *,unsigned long long,const unsigned char *);
extern int crypto_onetimeauth_poly1305_verify(const unsigned char *,const unsigned char *,unsigned long long,const unsigned char *);
#define crypto_onetimeauth_poly1305_IMPLEMENTATION "crypto_onetimeauth/poly1305/ref"
#define crypto_onetimeauth_poly1305_VERSION "-"

#endif