text:
package org.apache.cassandra.service.reads.repair;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;

import javax.annotation.Nullable;

import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.Mutation;
import org.apache.cassandra.db.ReadCommand;
import org.apache.cassandra.db.partitions.PartitionIterator;
import org.apache.cassandra.db.partitions.UnfilteredPartitionIterators;
import org.apache.cassandra.exceptions.ReadTimeoutException;
import org.apache.cassandra.locator.InetAddressAndPort;
import org.apache.cassandra.metrics.ReadRepairMetrics;
import org.apache.cassandra.net.AsyncOneResponse;
import org.apache.cassandra.net.MessageOut;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.service.reads.DataResolver;
import org.apache.cassandra.service.reads.DigestResolver;
import org.apache.cassandra.service.reads.ReadCallback;
import org.apache.cassandra.tracing.Tracing;

/**
 * 'Classic' read repair. Doesn't allow the client read to return until
 *  updates have been written to nodes needing correction.
 */
public class BlockingReadRepair implements ReadRepair, RepairListener
{
    private static final Logger logger = LoggerFactory.getLogger(BlockingReadRepair.class);

    private static final boolean DROP_OVERSIZED_READ_REPAIR_MUTATIONS =
        Boolean.getBoolean("cassandra.drop_oversized_readrepair_mutations");

    private final ReadCommand command;
    private final List<InetAddressAndPort> endpoints;
    private final long queryStartNanoTime;
    private final ConsistencyLevel consistency;

    private final Queue<BlockingPartitionRepair> repairs = new ConcurrentLinkedQueue<>();

    private volatile DigestRepair digestRepair = null;

    private static class DigestRepair
    {
        private final DataResolver dataResolver;
        private final ReadCallback readCallback;
        private final Consumer<PartitionIterator> resultConsumer;

        public DigestRepair(DataResolver dataResolver, ReadCallback readCallback, Consumer<PartitionIterator> resultConsumer)
        {
            this.dataResolver = dataResolver;
            this.readCallback = readCallback;
            this.resultConsumer = resultConsumer;
        }
    }

    public BlockingReadRepair(ReadCommand command,
                              List<InetAddressAndPort> endpoints,
                              long queryStartNanoTime,
                              ConsistencyLevel consistency)
    {
        this.command = command;
        this.endpoints = endpoints;
        this.queryStartNanoTime = queryStartNanoTime;
        this.consistency = consistency;
    }

    public UnfilteredPartitionIterators.MergeListener getMergeListener(InetAddressAndPort[] endpoints)
    {
        return new PartitionIteratorMergeListener(endpoints, command, this);
    }

    public static class BlockingPartitionRepair extends AbstractFuture<Object> implements RepairListener.PartitionRepair
    {

        final List<AsyncOneResponse<?>> responses;
        final ReadCommand command;
        final ConsistencyLevel consistency;

        public BlockingPartitionRepair(int expectedResponses, ReadCommand command, ConsistencyLevel consistency)
        {
            this.responses = new ArrayList<>(expectedResponses);
            this.command = command;
            this.consistency = consistency;
        }

        private AsyncOneResponse sendRepairMutation(Mutation mutation, InetAddressAndPort destination)
        {
            DecoratedKey key = mutation.key();
            Keyspace keyspace = Keyspace.open(mutation.getKeyspaceName());
            int messagingVersion = MessagingService.instance().getVersion(destination);

            int    mutationSize = (int) Mutation.serializer.serializedSize(mutation, messagingVersion);
            int maxMutationSize = DatabaseDescriptor.getMaxMutationSize();

            AsyncOneResponse callback = null;

            if (mutationSize <= maxMutationSize)
            {
                Tracing.trace("Sending read-repair-mutation to {}", destination);
                // use a separate verb here to avoid writing hints on timeouts
                MessageOut<Mutation> message = mutation.createMessage(MessagingService.Verb.READ_REPAIR);
                callback = MessagingService.instance().sendRR(message, destination);
                ColumnFamilyStore.metricsFor(command.metadata().id).readRepairRequests.mark();
            }
            else if (DROP_OVERSIZED_READ_REPAIR_MUTATIONS)
            {
                logger.debug("Encountered an oversized ({}/{}) read repair mutation for table {}, key {}, node {}",
                             mutationSize,
                             maxMutationSize,
                             command.metadata(),
                             command.metadata().partitionKeyType.getString(key.getKey()),
                             destination);
            }
            else
            {
                logger.warn("Encountered an oversized ({}/{}) read repair mutation for table {}, key {}, node {}",
                            mutationSize,
                            maxMutationSize,
                            command.metadata(),
                            command.metadata().partitionKeyType.getString(key.getKey()),
                            destination);

                int blockFor = consistency.blockFor(keyspace);
                Tracing.trace("Timed out while read-repairing after receiving all {} data and digest responses", blockFor);
                throw new ReadTimeoutException(consistency, blockFor - 1, blockFor, true);
            }
            return callback;
        }

        public void reportMutation(InetAddressAndPort endpoint, Mutation mutation)
        {
            AsyncOneResponse<?> response = sendRepairMutation(mutation, endpoint);

            if (response != null)
                responses.add(response);
        }

        public void finish()
        {
            Futures.addCallback(Futures.allAsList(responses), new FutureCallback<List<Object>>()
            {
                public void onSuccess(@Nullable List<Object> result)
                {
                    set(result);
                }

                public void onFailure(Throwable t)
                {
                    setException(t);
                }
            });
        }
    }

    public void awaitRepairs(long timeout)
    {
        try
        {
            Futures.allAsList(repairs).get(timeout, TimeUnit.MILLISECONDS);
        }
        catch (TimeoutException ex)
        {
            // We got all responses, but timed out while repairing
            Keyspace keyspace = Keyspace.open(command.metadata().keyspace);
            int blockFor = consistency.blockFor(keyspace);
            if (Tracing.isTracing())
                Tracing.trace("Timed out while read-repairing after receiving all {} data and digest responses", blockFor);
            else
                logger.debug("Timeout while read-repairing after receiving all {} data and digest responses", blockFor);

            throw new ReadTimeoutException(consistency, blockFor - 1, blockFor, true);
        }
        catch (InterruptedException | ExecutionException e)
        {
            throw new RuntimeException(e);
        }
    }

    public PartitionRepair startPartitionRepair()
    {
        BlockingPartitionRepair repair = new BlockingPartitionRepair(endpoints.size(), command, consistency);
        repairs.add(repair);
        return repair;
    }

    public void startRepair(DigestResolver digestResolver, List<InetAddressAndPort> allEndpoints, List<InetAddressAndPort> contactedEndpoints, Consumer<PartitionIterator> resultConsumer)
    {
        ReadRepairMetrics.repairedBlocking.mark();

        // Do a full data read to resolve the correct response (and repair node that need be)
        Keyspace keyspace = Keyspace.open(command.metadata().keyspace);
        DataResolver resolver = new DataResolver(keyspace, command, ConsistencyLevel.ALL, allEndpoints.size(), queryStartNanoTime, this);
        ReadCallback readCallback = new ReadCallback(resolver, ConsistencyLevel.ALL, contactedEndpoints.size(), command,
                                                     keyspace, allEndpoints, queryStartNanoTime, this);

        digestRepair = new DigestRepair(resolver, readCallback, resultConsumer);

        for (InetAddressAndPort endpoint : contactedEndpoints)
        {
            Tracing.trace("Enqueuing full data read to {}", endpoint);
            MessagingService.instance().sendRRWithFailure(command.createMessage(), endpoint, readCallback);
        }
    }

    public void awaitRepair() throws ReadTimeoutException
    {
        if (digestRepair != null)
        {
            digestRepair.readCallback.awaitResults();
            digestRepair.resultConsumer.accept(digestRepair.dataResolver.resolve());
        }
    }
}


text:
@-webkit-keyframes jconfirm-spin {
  from {
    -webkit-transform: rotate(0deg);
            transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
            transform: rotate(360deg);
  }
}
@keyframes jconfirm-spin {
  from {
    -webkit-transform: rotate(0deg);
            transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
            transform: rotate(360deg);
  }
}
body[class*=jconfirm-no-scroll-] {
  overflow: hidden !important;
}
.jconfirm {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  font-family: inherit;
  overflow: hidden;
}
.jconfirm .jconfirm-bg {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  -webkit-transition: opacity .4s;
          transition: opacity .4s;
}
.jconfirm .jconfirm-bg.jconfirm-bg-h {
  opacity: 0 !important;
}
.jconfirm .jconfirm-scrollpane {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: auto;
  -webkit-perspective: 500px;
          perspective: 500px;
  -webkit-perspective-origin: center;
          perspective-origin: center;
}
.jconfirm .jconfirm-box {
  background: white;
  border-radius: 4px;
  position: relative;
  outline: none;
  padding: 15px 15px 0;
  overflow: hidden;
}
@-webkit-keyframes type-blue {
  1%,
  100% {
    border-color: #3498db;
  }
  50% {
    border-color: #5faee3;
  }
}
@keyframes type-blue {
  1%,
  100% {
    border-color: #3498db;
  }
  50% {
    border-color: #5faee3;
  }
}
@-webkit-keyframes type-green {
  1%,
  100% {
    border-color: #2ecc71;
  }
  50% {
    border-color: #54d98c;
  }
}
@keyframes type-green {
  1%,
  100% {
    border-color: #2ecc71;
  }
  50% {
    border-color: #54d98c;
  }
}
@-webkit-keyframes type-red {
  1%,
  100% {
    border-color: #e74c3c;
  }
  50% {
    border-color: #ed7669;
  }
}
@keyframes type-red {
  1%,
  100% {
    border-color: #e74c3c;
  }
  50% {
    border-color: #ed7669;
  }
}
@-webkit-keyframes type-orange {
  1%,
  100% {
    border-color: #f1c40f;
  }
  50% {
    border-color: #f4d03f;
  }
}
@keyframes type-orange {
  1%,
  100% {
    border-color: #f1c40f;
  }
  50% {
    border-color: #f4d03f;
  }
}
@-webkit-keyframes type-purple {
  1%,
  100% {
    border-color: #9b59b6;
  }
  50% {
    border-color: #b07cc6;
  }
}
@keyframes type-purple {
  1%,
  100% {
    border-color: #9b59b6;
  }
  50% {
    border-color: #b07cc6;
  }
}
@-webkit-keyframes type-dark {
  1%,
  100% {
    border-color: #34495e;
  }
  50% {
    border-color: #46627f;
  }
}
@keyframes type-dark {
  1%,
  100% {
    border-color: #34495e;
  }
  50% {
    border-color: #46627f;
  }
}
.jconfirm .jconfirm-box.jconfirm-type-animated {
  -webkit-animation-duration: 2s;
          animation-duration: 2s;
  -webkit-animation-iteration-count: infinite;
          animation-iteration-count: infinite;
}
.jconfirm .jconfirm-box.jconfirm-blue {
  border-top: solid 7px #3498db;
  -webkit-animation-name: type-blue;
          animation-name: type-blue;
}
.jconfirm .jconfirm-box.jconfirm-green {
  border-top: solid 7px #2ecc71;
  -webkit-animation-name: type-green;
          animation-name: type-green;
}
.jconfirm .jconfirm-box.jconfirm-red {
  border-top: solid 7px #e74c3c;
  -webkit-animation-name: type-red;
          animation-name: type-red;
}
.jconfirm .jconfirm-box.jconfirm-orange {
  border-top: solid 7px #f1c40f;
  -webkit-animation-name: type-orange;
          animation-name: type-orange;
}
.jconfirm .jconfirm-box.jconfirm-purple {
  border-top: solid 7px #9b59b6;
  -webkit-animation-name: type-purple;
          animation-name: type-purple;
}
.jconfirm .jconfirm-box.jconfirm-dark {
  border-top: solid 7px #34495e;
  -webkit-animation-name: type-dark;
          animation-name: type-dark;
}
.jconfirm .jconfirm-box.loading {
  height: 120px;
}
.jconfirm .jconfirm-box.loading:before {
  content: '';
  position: absolute;
  left: 0;
  background: white;
  right: 0;
  top: 0;
  bottom: 0;
  border-radius: 10px;
  z-index: 1;
}
.jconfirm .jconfirm-box.loading:after {
  opacity: 0.6;
  content: '';
  height: 30px;
  width: 30px;
  border: solid 3px transparent;
  position: absolute;
  left: 50%;
  margin-left: -15px;
  border-radius: 50%;
  -webkit-animation: jconfirm-spin 1s infinite linear;
          animation: jconfirm-spin 1s infinite linear;
  border-bottom-color: dodgerblue;
  top: 50%;
  margin-top: -15px;
  z-index: 2;
}
.jconfirm .jconfirm-box div.jconfirm-closeIcon {
  height: 20px;
  width: 20px;
  position: absolute;
  top: 5px;
  right: 5px;
  cursor: pointer;
  opacity: .6;
  text-align: center;
  -webkit-transition: opacity 0.3s ease-in;
          transition: opacity 0.3s ease-in;
  font-size: 27px !important;
  line-height: 14px !important;
  display: none;
}
.jconfirm .jconfirm-box div.jconfirm-closeIcon:empty {
  display: none;
}
.jconfirm .jconfirm-box div.jconfirm-closeIcon .fa {
  font-size: 16px;
}
.jconfirm .jconfirm-box div.jconfirm-closeIcon .glyphicon {
  font-size: 16px;
}
.jconfirm .jconfirm-box div.jconfirm-closeIcon .zmdi {
  font-size: 16px;
}
.jconfirm .jconfirm-box div.jconfirm-closeIcon:hover {
  opacity: 1;
}
.jconfirm .jconfirm-box div.jconfirm-title-c {
  display: block;
  font-size: 22px;
  line-height: 20px;
}
.jconfirm .jconfirm-box div.jconfirm-title-c .jconfirm-icon-c {
  font-size: inherit;
  padding-bottom: 15px;
  display: inline-block;
  margin-right: 8px;
  vertical-align: middle;
}
.jconfirm .jconfirm-box div.jconfirm-title-c .jconfirm-icon-c i {
  vertical-align: middle;
}
.jconfirm .jconfirm-box div.jconfirm-title-c .jconfirm-icon-c:empty {
  display: none;
}
.jconfirm .jconfirm-box div.jconfirm-title-c .jconfirm-title {
  font-size: inherit;
  font-family: inherit;
  display: inline-block;
  vertical-align: middle;
  padding-bottom: 15px;
}
.jconfirm .jconfirm-box div.jconfirm-title-c .jconfirm-title:empty {
  display: none;
}
.jconfirm .jconfirm-box div.jconfirm-content-pane {
  margin-bottom: 15px;
  height: auto;
  -webkit-transition: height 0.4s ease-in;
          transition: height 0.4s ease-in;
  display: inline-block;
  width: 100%;
  position: relative;
  overflow: hidden;
}
.jconfirm .jconfirm-box div.jconfirm-content-pane .jconfirm-content img {
  max-width: 100%;
  height: auto;
}
.jconfirm .jconfirm-box div.jconfirm-content-pane .jconfirm-content:empty {
  display: none;
}
.jconfirm .jconfirm-box .jconfirm-buttons {
  padding-bottom: 11px;
}
.jconfirm .jconfirm-box .jconfirm-buttons > button {
  margin-bottom: 4px;
  margin-left: 2px;
  margin-right: 2px;
}
.jconfirm .jconfirm-box .jconfirm-buttons button {
  display: inline-block;
  padding: 6px 12px;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -ms-touch-action: manipulation;
  touch-action: manipulation;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  border-radius: 4px;
  min-height: 1em;
  outline: 0;
  -webkit-user-select: none;
     -moz-user-select: none;
      -ms-user-select: none;
          user-select: none;
  -webkit-transition: opacity 0.1s ease, background-color 0.1s ease, color 0.1s ease, box-shadow 0.1s ease, background 0.1s ease;
          transition: opacity 0.1s ease, background-color 0.1s ease, color 0.1s ease, box-shadow 0.1s ease, background 0.1s ease;
  -webkit-tap-highlight-color: transparent;
  border: none;
  background-image: none;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-blue {
  background-color: #3498db;
  color: #FFF;
  text-shadow: none;
  -webkit-transition: background .2s;
          transition: background .2s;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-blue:hover {
  background-color: #2980b9;
  color: #FFF;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-green {
  background-color: #2ecc71;
  color: #FFF;
  text-shadow: none;
  -webkit-transition: background .2s;
          transition: background .2s;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-green:hover {
  background-color: #27ae60;
  color: #FFF;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-red {
  background-color: #e74c3c;
  color: #FFF;
  text-shadow: none;
  -webkit-transition: background .2s;
          transition: background .2s;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-red:hover {
  background-color: #c0392b;
  color: #FFF;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-orange {
  background-color: #f1c40f;
  color: #FFF;
  text-shadow: none;
  -webkit-transition: background .2s;
          transition: background .2s;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-orange:hover {
  background-color: #f39c12;
  color: #FFF;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-default {
  background-color: #ecf0f1;
  color: #000;
  text-shadow: none;
  -webkit-transition: background .2s;
          transition: background .2s;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-default:hover {
  background-color: #bdc3c7;
  color: #000;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-purple {
  background-color: #9b59b6;
  color: #FFF;
  text-shadow: none;
  -webkit-transition: background .2s;
          transition: background .2s;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-purple:hover {
  background-color: #8e44ad;
  color: #FFF;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-dark {
  background-color: #34495e;
  color: #FFF;
  text-shadow: none;
  -webkit-transition: background .2s;
          transition: background .2s;
}
.jconfirm .jconfirm-box .jconfirm-buttons button.btn-dark:hover {
  background-color: #2c3e50;
  color: #FFF;
}
.jconfirm .jconfirm-clear {
  clear: both;
}
.jconfirm.jconfirm-rtl {
  direction: rtl;
}
.jconfirm.jconfirm-rtl div.jconfirm-closeIcon {
  left: 5px;
  right: auto;
}
.jconfirm.jconfirm-white .jconfirm-bg,
.jconfirm.jconfirm-light .jconfirm-bg {
  background-color: #444;
  opacity: .2;
}
.jconfirm.jconfirm-white .jconfirm-box,
.jconfirm.jconfirm-light .jconfirm-box {
  margin: 0 auto;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
}
.jconfirm.jconfirm-white .jconfirm-box .jconfirm-buttons,
.jconfirm.jconfirm-light .jconfirm-box .jconfirm-buttons {
  float: right;
}
.jconfirm.jconfirm-white .jconfirm-box .jconfirm-buttons button,
.jconfirm.jconfirm-light .jconfirm-box .jconfirm-buttons button {
  text-transform: uppercase;
  font-size: 14px;
  font-weight: bold;
  text-shadow: none;
}
.jconfirm.jconfirm-white .jconfirm-box .jconfirm-buttons button.btn-default,
.jconfirm.jconfirm-light .jconfirm-box .jconfirm-buttons button.btn-default {
  box-shadow: none;
  color: #333;
}
.jconfirm.jconfirm-white .jconfirm-box .jconfirm-buttons button.btn-default:hover,
.jconfirm.jconfirm-light .jconfirm-box .jconfirm-buttons button.btn-default:hover {
  background: #ddd;
}
.jconfirm.jconfirm-black .jconfirm-bg,
.jconfirm.jconfirm-dark .jconfirm-bg {
  background-color: darkslategray;
  opacity: .4;
}
.jconfirm.jconfirm-black .jconfirm-box,
.jconfirm.jconfirm-dark .jconfirm-box {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  background: #444;
  border-radius: 5px;
  color: white;
}
.jconfirm.jconfirm-black .jconfirm-box .jconfirm-buttons,
.jconfirm.jconfirm-dark .jconfirm-box .jconfirm-buttons {
  float: right;
}
.jconfirm.jconfirm-black .jconfirm-box .jconfirm-buttons button,
.jconfirm.jconfirm-dark .jconfirm-box .jconfirm-buttons button {
  border: none;
  background-image: none;
  text-transform: uppercase;
  font-size: 14px;
  font-weight: bold;
  text-shadow: none;
  -webkit-transition: background .1s;
          transition: background .1s;
  color: white;
}
.jconfirm.jconfirm-black .jconfirm-box .jconfirm-buttons button.btn-default,
.jconfirm.jconfirm-dark .jconfirm-box .jconfirm-buttons button.btn-default {
  box-shadow: none;
  color: #fff;
  background: none;
}
.jconfirm.jconfirm-black .jconfirm-box .jconfirm-buttons button.btn-default:hover,
.jconfirm.jconfirm-dark .jconfirm-box .jconfirm-buttons button.btn-default:hover {
  background: #666;
}
.jconfirm .jconfirm-box.hilight.jconfirm-hilight-shake {
  -webkit-animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
          animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
}
.jconfirm .jconfirm-box.hilight.jconfirm-hilight-glow {
  -webkit-animation: glow 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
          animation: glow 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
}
@-webkit-keyframes shake {
  10%,
  90% {
    -webkit-transform: translate3d(-2px, 0, 0);
            transform: translate3d(-2px, 0, 0);
  }
  20%,
  80% {
    -webkit-transform: translate3d(4px, 0, 0);
            transform: translate3d(4px, 0, 0);
  }
  30%,
  50%,
  70% {
    -webkit-transform: translate3d(-8px, 0, 0);
            transform: translate3d(-8px, 0, 0);
  }
  40%,
  60% {
    -webkit-transform: translate3d(8px, 0, 0);
            transform: translate3d(8px, 0, 0);
  }
}
@keyframes shake {
  10%,
  90% {
    -webkit-transform: translate3d(-2px, 0, 0);
            transform: translate3d(-2px, 0, 0);
  }
  20%,
  80% {
    -webkit-transform: translate3d(4px, 0, 0);
            transform: translate3d(4px, 0, 0);
  }
  30%,
  50%,
  70% {
    -webkit-transform: translate3d(-8px, 0, 0);
            transform: translate3d(-8px, 0, 0);
  }
  40%,
  60% {
    -webkit-transform: translate3d(8px, 0, 0);
            transform: translate3d(8px, 0, 0);
  }
}
@-webkit-keyframes glow {
  0%,
  100% {
    box-shadow: 0 0 3px red;
  }
  50% {
    box-shadow: 0 0 30px red;
  }
}
@keyframes glow {
  0%,
  100% {
    box-shadow: 0 0 3px red;
  }
  50% {
    box-shadow: 0 0 30px red;
  }
}
/*Transition rules*/
.jconfirm {
  -webkit-perspective: 400px;
          perspective: 400px;
}
.jconfirm .jconfirm-box {
  opacity: 1;
  -webkit-transition-property: all;
          transition-property: all;
}
.jconfirm .jconfirm-box.jconfirm-animation-top,
.jconfirm .jconfirm-box.jconfirm-animation-left,
.jconfirm .jconfirm-box.jconfirm-animation-right,
.jconfirm .jconfirm-box.jconfirm-animation-bottom,
.jconfirm .jconfirm-box.jconfirm-animation-opacity,
.jconfirm .jconfirm-box.jconfirm-animation-zoom,
.jconfirm .jconfirm-box.jconfirm-animation-scale,
.jconfirm .jconfirm-box.jconfirm-animation-none,
.jconfirm .jconfirm-box.jconfirm-animation-rotate,
.jconfirm .jconfirm-box.jconfirm-animation-rotatex,
.jconfirm .jconfirm-box.jconfirm-animation-rotatey,
.jconfirm .jconfirm-box.jconfirm-animation-scaley,
.jconfirm .jconfirm-box.jconfirm-animation-scalex {
  opacity: 0;
}
.jconfirm .jconfirm-box.jconfirm-animation-rotate {
  -webkit-transform: rotate(90deg);
      -ms-transform: rotate(90deg);
          transform: rotate(90deg);
}
.jconfirm .jconfirm-box.jconfirm-animation-rotatex {
  -webkit-transform: rotateX(90deg);
          transform: rotateX(90deg);
  -webkit-transform-origin: center;
      -ms-transform-origin: center;
          transform-origin: center;
}
.jconfirm .jconfirm-box.jconfirm-animation-rotatexr {
  -webkit-transform: rotateX(-90deg);
          transform: rotateX(-90deg);
  -webkit-transform-origin: center;
      -ms-transform-origin: center;
          transform-origin: center;
}
.jconfirm .jconfirm-box.jconfirm-animation-rotatey {
  -webkit-transform: rotatey(90deg);
      -ms-transform: rotatey(90deg);
          transform: rotatey(90deg);
  -webkit-transform-origin: center;
      -ms-transform-origin: center;
          transform-origin: center;
}
.jconfirm .jconfirm-box.jconfirm-animation-rotateyr {
  -webkit-transform: rotatey(-90deg);
      -ms-transform: rotatey(-90deg);
          transform: rotatey(-90deg);
  -webkit-transform-origin: center;
      -ms-transform-origin: center;
          transform-origin: center;
}
.jconfirm .jconfirm-box.jconfirm-animation-scaley {
  -webkit-transform: scaley(1.5);
      -ms-transform: scaley(1.5);
          transform: scaley(1.5);
  -webkit-transform-origin: center;
      -ms-transform-origin: center;
          transform-origin: center;
}
.jconfirm .jconfirm-box.jconfirm-animation-scalex {
  -webkit-transform: scalex(1.5);
      -ms-transform: scalex(1.5);
          transform: scalex(1.5);
  -webkit-transform-origin: center;
      -ms-transform-origin: center;
          transform-origin: center;
}
.jconfirm .jconfirm-box.jconfirm-animation-top {
  -webkit-transform: translate(0px, -100px);
      -ms-transform: translate(0px, -100px);
          transform: translate(0px, -100px);
}
.jconfirm .jconfirm-box.jconfirm-animation-left {
  -webkit-transform: translate(-100px, 0px);
      -ms-transform: translate(-100px, 0px);
          transform: translate(-100px, 0px);
}
.jconfirm .jconfirm-box.jconfirm-animation-right {
  -webkit-transform: translate(100px, 0px);
      -ms-transform: translate(100px, 0px);
          transform: translate(100px, 0px);
}
.jconfirm .jconfirm-box.jconfirm-animation-bottom {
  -webkit-transform: translate(0px, 100px);
      -ms-transform: translate(0px, 100px);
          transform: translate(0px, 100px);
}
.jconfirm .jconfirm-box.jconfirm-animation-zoom {
  -webkit-transform: scale(1.2);
      -ms-transform: scale(1.2);
          transform: scale(1.2);
}
.jconfirm .jconfirm-box.jconfirm-animation-scale {
  -webkit-transform: scale(0.5);
      -ms-transform: scale(0.5);
          transform: scale(0.5);
}
.jconfirm .jconfirm-box.jconfirm-animation-none {
  visibility: hidden;
}
.jconfirm.jconfirm-supervan .jconfirm-bg {
  background-color: rgba(54, 70, 93, 0.95);
}
.jconfirm.jconfirm-supervan .jconfirm-box {
  background-color: transparent;
}
.jconfirm.jconfirm-supervan .jconfirm-box div.jconfirm-closeIcon {
  color: white;
}
.jconfirm.jconfirm-supervan .jconfirm-box div.jconfirm-title-c {
  text-align: center;
  color: white;
  font-size: 28px;
  font-weight: normal;
}
.jconfirm.jconfirm-supervan .jconfirm-box div.jconfirm-title-c > * {
  padding-bottom: 25px;
}
.jconfirm.jconfirm-supervan .jconfirm-box div.jconfirm-content-pane {
  margin-bottom: 25px;
}
.jconfirm.jconfirm-supervan .jconfirm-box div.jconfirm-content {
  text-align: center;
  color: white;
}
.jconfirm.jconfirm-supervan .jconfirm-box .jconfirm-buttons {
  text-align: center;
}
.jconfirm.jconfirm-supervan .jconfirm-box .jconfirm-buttons button {
  font-size: 16px;
  border-radius: 2px;
  background: #303f53;
  text-shadow: none;
  border: none;
  color: white;
  padding: 10px;
  min-width: 100px;
}
.jconfirm.jconfirm-material .jconfirm-bg {
  background-color: rgba(0, 0, 0, 0.67);
}
.jconfirm.jconfirm-material .jconfirm-box {
  background-color: white;
  box-shadow: 0 7px 8px -4px rgba(0, 0, 0, 0.2), 0 13px 19px 2px rgba(0, 0, 0, 0.14), 0 5px 24px 4px rgba(0, 0, 0, 0.12);
  padding: 30px 25px 10px 25px;
}
.jconfirm.jconfirm-material .jconfirm-box div.jconfirm-closeIcon {
  color: rgba(0, 0, 0, 0.87);
}
.jconfirm.jconfirm-material .jconfirm-box div.jconfirm-title-c {
  color: rgba(0, 0, 0, 0.87);
  font-size: 22px;
  font-weight: bold;
}
.jconfirm.jconfirm-material .jconfirm-box div.jconfirm-content {
  text-align: left;
  color: rgba(0, 0, 0, 0.87);
}
.jconfirm.jconfirm-material .jconfirm-box .jconfirm-buttons {
  text-align: right;
}
.jconfirm.jconfirm-material .jconfirm-box .jconfirm-buttons button {
  text-transform: uppercase;
  font-weight: 500;
}
.jconfirm.jconfirm-bootstrap .jconfirm-bg {
  background-color: rgba(0, 0, 0, 0.21);
}
.jconfirm.jconfirm-bootstrap .jconfirm-box {
  background-color: white;
  box-shadow: 0 3px 8px 0px rgba(0, 0, 0, 0.2);
  border: solid 1px rgba(0, 0, 0, 0.4);
  padding: 15px 0 0;
}
.jconfirm.jconfirm-bootstrap .jconfirm-box div.jconfirm-closeIcon {
  color: rgba(0, 0, 0, 0.87);
}
.jconfirm.jconfirm-bootstrap .jconfirm-box div.jconfirm-title-c {
  color: rgba(0, 0, 0, 0.87);
  font-size: 22px;
  font-weight: bold;
  padding-left: 15px;
  padding-right: 15px;
}
.jconfirm.jconfirm-bootstrap .jconfirm-box div.jconfirm-content {
  text-align: left;
  color: rgba(0, 0, 0, 0.87);
  padding: 0px 15px;
}
.jconfirm.jconfirm-bootstrap .jconfirm-box .jconfirm-buttons {
  text-align: right;
  padding: 0px 0 0px;
  margin: -5px 0 0px;
  border-top: solid 1px #ddd;
  overflow: hidden;
  border-radius: 0 0 4px 4px;
}
.jconfirm.jconfirm-bootstrap .jconfirm-box .jconfirm-buttons button {
  font-weight: 500;
  border-radius: 0px;
  margin: 0;
  border-left: solid 1px #ddd;
}

redpajama_set_name: RedPajamaGithub


text:
"""Tests for tf.contrib.kfac.fisher_factors."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import numpy.random as npr

from tensorflow.contrib.kfac.python.ops import fisher_blocks as fb
from tensorflow.contrib.kfac.python.ops import fisher_factors as ff
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops as tf_ops
from tensorflow.python.framework import random_seed
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import variables as tf_variables
from tensorflow.python.platform import test

# We need to set these constants since the numerical values used in the tests
# were chosen when these used to be the defaults.
ff.set_global_constants(init_covariances_at_zero=False,
                        zero_debias=False,
                        init_inverses_at_zero=False)

def make_damping_func(damping):
  return fb._package_func(lambda: damping, damping)

class FisherFactorTestingDummy(ff.FisherFactor):
  """Dummy class to test the non-abstract methods on ff.FisherFactor."""

  @property
  def _var_scope(self):
    return 'dummy/a_b_c'

  @property
  def _cov_shape(self):
    raise NotImplementedError

  @property
  def _num_sources(self):
    return 1

  @property
  def _dtype(self):
    return dtypes.float32

  def _compute_new_cov(self):
    raise NotImplementedError

  def instantiate_covariance(self):
    pass

  def make_inverse_update_ops(self):
    return []

  def get_cov(self):
    return NotImplementedError

  def instantiate_inv_variables(self):
    return NotImplementedError

  def _num_towers(self):
    raise NotImplementedError

  def _get_data_device(self):
    raise NotImplementedError

  def register_matpower(self, exp, damping_func):
    raise NotImplementedError

  def register_cholesky(self, damping_func):
    raise NotImplementedError

  def register_cholesky_inverse(self, damping_func):
    raise NotImplementedError

  def get_matpower(self, exp, damping_func):
    raise NotImplementedError

  def get_cholesky(self, damping_func):
    raise NotImplementedError

  def get_cholesky_inverse(self, damping_func):
    raise NotImplementedError

  def get_cov_as_linear_operator(self):
    raise NotImplementedError

class DenseSquareMatrixFactorTestingDummy(ff.DenseSquareMatrixFactor):
  """Dummy class to test the non-abstract methods on ff.DenseSquareMatrixFactor.
  """

  def __init__(self, shape):
    self._shape = shape
    super(DenseSquareMatrixFactorTestingDummy, self).__init__()

  @property
  def _var_scope(self):
    return 'dummy/a_b_c'

  @property
  def _cov_shape(self):
    return self._shape

  @property
  def _num_sources(self):
    return 1

  @property
  def _dtype(self):
    return dtypes.float32

  def _compute_new_cov(self):
    raise NotImplementedError

  def instantiate_covariance(self):
    pass

  def _num_towers(self):
    raise NotImplementedError

  def _get_data_device(self):
    raise NotImplementedError

class NumericalUtilsTest(test.TestCase):

  def testComputeCovAgainstNumpy(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      npr.seed(0)
      random_seed.set_random_seed(200)

      x = npr.randn(100, 3)
      cov = ff.compute_cov(array_ops.constant(x))
      np_cov = np.dot(x.T, x) / x.shape[0]

      self.assertAllClose(sess.run(cov), np_cov)

  def testComputeCovAgainstNumpyWithAlternativeNormalizer(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      npr.seed(0)
      random_seed.set_random_seed(200)

      normalizer = 10.
      x = npr.randn(100, 3)
      cov = ff.compute_cov(array_ops.constant(x), normalizer=normalizer)
      np_cov = np.dot(x.T, x) / normalizer

      self.assertAllClose(sess.run(cov), np_cov)

  def testAppendHomog(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      npr.seed(0)

      m, n = 3, 4
      a = npr.randn(m, n)
      a_homog = ff.append_homog(array_ops.constant(a))
      np_result = np.hstack([a, np.ones((m, 1))])

      self.assertAllClose(sess.run(a_homog), np_result)

class NameStringUtilFunctionTest(test.TestCase):

  def _make_tensor(self):
    x = array_ops.placeholder(dtypes.float64, (3, 1))
    w = array_ops.constant(npr.RandomState(0).randn(3, 3))
    y = math_ops.matmul(w, x)
    g = gradients_impl.gradients(y, x)[0]
    return g

  def testScopeStringFromParamsSingleTensor(self):
    with tf_ops.Graph().as_default():
      g = self._make_tensor()
      scope_string = ff.scope_string_from_params(g)
      self.assertEqual('gradients_MatMul_grad_MatMul_1', scope_string)

  def testScopeStringFromParamsMultipleTensors(self):
    with tf_ops.Graph().as_default():
      x = array_ops.constant(1,)
      y = array_ops.constant(2,)
      scope_string = ff.scope_string_from_params((x, y))
      self.assertEqual('Const_Const_1', scope_string)

  def testScopeStringFromParamsMultipleTypes(self):
    with tf_ops.Graph().as_default():
      x = array_ops.constant(1,)
      y = array_ops.constant(2,)
      scope_string = ff.scope_string_from_params([[1, 2, 3], 'foo', True, 4,
                                                  (x, y)])
      self.assertEqual('1-2-3_foo_True_4_Const__Const_1', scope_string)

  def testScopeStringFromParamsUnsupportedType(self):
    with tf_ops.Graph().as_default():
      x = array_ops.constant(1,)
      y = array_ops.constant(2,)
      unsupported = 1.2  # Floats are not supported.
      with self.assertRaises(ValueError):
        ff.scope_string_from_params([[1, 2, 3], 'foo', True, 4, (x, y),
                                     unsupported])

  def testScopeStringFromName(self):
    with tf_ops.Graph().as_default():
      g = self._make_tensor()
      scope_string = ff.scope_string_from_name(g)
      self.assertEqual('gradients_MatMul_grad_MatMul_1', scope_string)

  def testScalarOrTensorToString(self):
    with tf_ops.Graph().as_default():
      self.assertEqual(ff.scalar_or_tensor_to_string(5.), repr(5.))

      g = self._make_tensor()
      scope_string = ff.scope_string_from_name(g)
      self.assertEqual(ff.scalar_or_tensor_to_string(g), scope_string)

class FisherFactorTest(test.TestCase):

  def testMakeInverseUpdateOps(self):
    with tf_ops.Graph().as_default():
      random_seed.set_random_seed(200)
      factor = FisherFactorTestingDummy()

      self.assertEqual(0, len(factor.make_inverse_update_ops()))

class DenseSquareMatrixFactorTest(test.TestCase):

  def testRegisterDampedInverse(self):
    with tf_ops.Graph().as_default():
      random_seed.set_random_seed(200)
      shape = [2, 2]
      factor = DenseSquareMatrixFactorTestingDummy(shape)
      factor_var_scope = 'dummy/a_b_c'

      damping_funcs = [make_damping_func(0.1),
                       make_damping_func(0.1),
                       make_damping_func(1e-5),
                       make_damping_func(1e-5)]
      for damping_func in damping_funcs:
        factor.register_inverse(damping_func)

      factor.instantiate_inv_variables()

      inv = factor.get_inverse(damping_funcs[0]).to_dense()
      self.assertEqual(inv, factor.get_inverse(damping_funcs[1]).to_dense())
      self.assertNotEqual(inv, factor.get_inverse(damping_funcs[2]).to_dense())
      self.assertEqual(factor.get_inverse(damping_funcs[2]).to_dense(),
                       factor.get_inverse(damping_funcs[3]).to_dense())
      factor_vars = tf_ops.get_collection(tf_ops.GraphKeys.GLOBAL_VARIABLES,
                                          factor_var_scope)
      factor_tensors = (tf_ops.convert_to_tensor(var) for var in factor_vars)

      self.assertEqual(set([inv,
                            factor.get_inverse(damping_funcs[2]).to_dense()]),
                       set(factor_tensors))
      self.assertEqual(shape, inv.get_shape())

  def testRegisterMatpower(self):
    with tf_ops.Graph().as_default():
      random_seed.set_random_seed(200)
      shape = [3, 3]
      factor = DenseSquareMatrixFactorTestingDummy(shape)
      factor_var_scope = 'dummy/a_b_c'

      # TODO(b/74201126): Change to using the same func for both once
      # Topohash is in place.
      damping_func_1 = make_damping_func(0.5)
      damping_func_2 = make_damping_func(0.5)

      factor.register_matpower(-0.5, damping_func_1)
      factor.register_matpower(2, damping_func_2)

      factor.instantiate_inv_variables()

      factor_vars = tf_ops.get_collection(tf_ops.GraphKeys.GLOBAL_VARIABLES,
                                          factor_var_scope)

      factor_tensors = (tf_ops.convert_to_tensor(var) for var in factor_vars)

      matpower1 = factor.get_matpower(-0.5, damping_func_1).to_dense()
      matpower2 = factor.get_matpower(2, damping_func_2).to_dense()

      self.assertEqual(set([matpower1, matpower2]), set(factor_tensors))

      self.assertEqual(shape, matpower1.get_shape())
      self.assertEqual(shape, matpower2.get_shape())

  def testMakeInverseUpdateOps(self):
    with tf_ops.Graph().as_default():
      random_seed.set_random_seed(200)
      factor = FisherFactorTestingDummy()

      self.assertEqual(0, len(factor.make_inverse_update_ops()))

  def testMakeInverseUpdateOpsManyInversesEigenDecomp(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      random_seed.set_random_seed(200)
      cov = np.array([[1., 2.], [3., 4.]])
      factor = DenseSquareMatrixFactorTestingDummy(cov.shape)
      factor._cov = array_ops.constant(cov, dtype=dtypes.float32)

      damping_funcs = []
      for i in range(1, ff.EIGENVALUE_DECOMPOSITION_THRESHOLD + 1):
        damping_funcs.append(make_damping_func(1./i))

      for i in range(ff.EIGENVALUE_DECOMPOSITION_THRESHOLD):
        factor.register_inverse(damping_funcs[i])

      factor.instantiate_inv_variables()
      ops = factor.make_inverse_update_ops()
      self.assertEqual(1, len(ops))

      sess.run(tf_variables.global_variables_initializer())
      new_invs = []
      sess.run(ops)
      for i in range(ff.EIGENVALUE_DECOMPOSITION_THRESHOLD):
        # The inverse op will assign the damped inverse of cov to the inv var.
        new_invs.append(
            sess.run(factor.get_inverse(damping_funcs[i]).to_dense()))

      # We want to see that the new invs are all different from each other.
      for i in range(len(new_invs)):
        for j in range(i + 1, len(new_invs)):
          # Just check the first element.
          self.assertNotEqual(new_invs[i][0][0], new_invs[j][0][0])

  def testMakeInverseUpdateOpsMatPowerEigenDecomp(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      random_seed.set_random_seed(200)
      cov = np.array([[6., 2.], [2., 4.]])
      factor = DenseSquareMatrixFactorTestingDummy(cov.shape)
      factor._cov = array_ops.constant(cov, dtype=dtypes.float32)
      exp = 2  # NOTE(mattjj): must be int to test with np.linalg.matrix_power
      damping = 0.5
      damping_func = make_damping_func(damping)

      factor.register_matpower(exp, damping_func)
      factor.instantiate_inv_variables()
      ops = factor.make_inverse_update_ops()
      self.assertEqual(1, len(ops))

      sess.run(tf_variables.global_variables_initializer())
      sess.run(ops[0])
      matpower = sess.run(factor.get_matpower(exp, damping_func).to_dense())
      matpower_np = np.linalg.matrix_power(cov + np.eye(2) * damping, exp)
      self.assertAllClose(matpower, matpower_np)

  def testMakeInverseUpdateOpsNoEigenDecomp(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      random_seed.set_random_seed(200)
      cov = np.array([[5., 2.], [2., 4.]])  # NOTE(mattjj): must be symmetric
      factor = DenseSquareMatrixFactorTestingDummy(cov.shape)
      factor._cov = array_ops.constant(cov, dtype=dtypes.float32)

      damping_func = make_damping_func(0)

      factor.register_inverse(damping_func)
      factor.instantiate_inv_variables()
      ops = factor.make_inverse_update_ops()
      self.assertEqual(1, len(ops))

      sess.run(tf_variables.global_variables_initializer())
      # The inverse op will assign the damped inverse of cov to the inv var.
      old_inv = sess.run(factor.get_inverse(damping_func).to_dense())
      self.assertAllClose(
          sess.run(ff.inverse_initializer(cov.shape, dtypes.float32)), old_inv)

      sess.run(ops)
      new_inv = sess.run(factor.get_inverse(damping_func).to_dense())
      self.assertAllClose(new_inv, np.linalg.inv(cov))

class FullFactorTest(test.TestCase):

  def testFullFactorInit(self):
    with tf_ops.Graph().as_default():
      random_seed.set_random_seed(200)
      tensor = array_ops.ones((2, 3), name='a/b/c')
      factor = ff.FullFactor((tensor,), 32)
      factor.instantiate_cov_variables()
      self.assertEqual([6, 6], factor.get_cov().get_shape().as_list())

  def testFullFactorInitFloat64(self):
    with tf_ops.Graph().as_default():
      dtype = dtypes.float64_ref
      random_seed.set_random_seed(200)
      tensor = array_ops.ones((2, 3), dtype=dtype, name='a/b/c')
      factor = ff.FullFactor((tensor,), 32)
      factor.instantiate_cov_variables()
      cov = factor.get_cov()
      self.assertEqual(cov.dtype, dtype)
      self.assertEqual([6, 6], cov.get_shape().as_list())

  def testMakeCovarianceUpdateOp(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      random_seed.set_random_seed(200)
      tensor = array_ops.constant([1., 2.], name='a/b/c')
      factor = ff.FullFactor((tensor,), 2)
      factor.instantiate_cov_variables()

      sess.run(tf_variables.global_variables_initializer())
      new_cov = sess.run(factor.make_covariance_update_op(.5))
      self.assertAllClose([[0.75, 0.5], [0.5, 1.5]], new_cov)

class NaiveDiagonalFactorTest(test.TestCase):

  def testNaiveDiagonalFactorInit(self):
    with tf_ops.Graph().as_default():
      random_seed.set_random_seed(200)
      tensor = array_ops.ones((2, 3), name='a/b/c')
      factor = ff.NaiveDiagonalFactor((tensor,), 32)
      factor.instantiate_cov_variables()
      self.assertEqual([6, 1], factor.get_cov().get_shape().as_list())

  def testNaiveDiagonalFactorInitFloat64(self):
    with tf_ops.Graph().as_default():
      dtype = dtypes.float64_ref
      random_seed.set_random_seed(200)
      tensor = array_ops.ones((2, 3), dtype=dtype, name='a/b/c')
      factor = ff.NaiveDiagonalFactor((tensor,), 32)
      factor.instantiate_cov_variables()
      cov = factor.get_cov()
      self.assertEqual(cov.dtype, dtype)
      self.assertEqual([6, 1], cov.get_shape().as_list())

  def testMakeCovarianceUpdateOp(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      random_seed.set_random_seed(200)
      tensor = array_ops.constant([1., 2.], name='a/b/c')
      factor = ff.NaiveDiagonalFactor((tensor,), 2)
      factor.instantiate_cov_variables()

      sess.run(tf_variables.global_variables_initializer())
      new_cov = sess.run(factor.make_covariance_update_op(.5))
      self.assertAllClose([[0.75], [1.5]], new_cov)

class EmbeddingInputKroneckerFactorTest(test.TestCase):

  def testInitialization(self):
    with tf_ops.Graph().as_default():
      input_ids = array_ops.constant([[0], [1], [4]])
      vocab_size = 5
      factor = ff.EmbeddingInputKroneckerFactor((input_ids,), vocab_size)
      factor.instantiate_cov_variables()
      cov = factor.get_cov()
      self.assertEqual(cov.shape.as_list(), [vocab_size])

  def testCovarianceUpdateOp(self):
    with tf_ops.Graph().as_default():
      input_ids = array_ops.constant([[0], [1], [4]])
      vocab_size = 5
      factor = ff.EmbeddingInputKroneckerFactor((input_ids,), vocab_size)
      factor.instantiate_cov_variables()
      cov_update_op = factor.make_covariance_update_op(0.0)

      with self.test_session() as sess:
        sess.run(tf_variables.global_variables_initializer())
        new_cov = sess.run(cov_update_op)
        self.assertAllClose(np.array([1., 1., 0., 0., 1.]) / 3., new_cov)

class ConvDiagonalFactorTest(test.TestCase):

  def setUp(self):
    self.batch_size = 10
    self.height = self.width = 32
    self.in_channels = 3
    self.out_channels = 1
    self.kernel_height = self.kernel_width = 3
    self.strides = [1, 2, 2, 1]
    self.data_format = 'NHWC'
    self.padding = 'SAME'
    self.kernel_shape = [
        self.kernel_height, self.kernel_width, self.in_channels,
        self.out_channels
    ]

  def testInit(self):
    with tf_ops.Graph().as_default():
      inputs = random_ops.random_uniform(
          [self.batch_size, self.height, self.width, self.in_channels])
      outputs_grads = [
          random_ops.random_uniform([
              self.batch_size, self.height // self.strides[1],
              self.width // self.strides[2], self.out_channels
          ]) for _ in range(3)
      ]

      factor = ff.ConvDiagonalFactor(
          (inputs,),
          (outputs_grads,),
          self.kernel_shape,
          self.strides,
          self.padding,
          data_format=self.data_format)
      factor.instantiate_cov_variables()

      # Ensure covariance matrix's shape makes sense.
      self.assertEqual([
          self.kernel_height * self.kernel_width * self.in_channels,
          self.out_channels
      ],
                       factor.get_cov().shape.as_list())

  def testMakeCovarianceUpdateOp(self):
    with tf_ops.Graph().as_default():
      # Construct all arguments such that convolution kernel is applied in
      # exactly one spatial location.
      inputs = np.random.randn(
          1,  # batch_size
          self.kernel_height,
          self.kernel_width,
          self.in_channels)  # in_channels
      outputs_grad = np.random.randn(
          1,  # batch_size
          1,  # output_height
          1,  # output_width
          self.out_channels)

      factor = ff.ConvDiagonalFactor(
          (constant_op.constant(inputs),),
          ((constant_op.constant(outputs_grad),),),
          self.kernel_shape,
          strides=[1, 1, 1, 1],
          padding='VALID')
      factor.instantiate_cov_variables()

      # Completely forget initial value on first update.
      cov_update_op = factor.make_covariance_update_op(0.0)

      # Ensure new covariance value is same as outer-product of inputs/outputs
      # vectorized, squared.
      with self.test_session() as sess:
        sess.run(tf_variables.global_variables_initializer())
        cov = sess.run(cov_update_op)
        expected_cov = np.outer(inputs.flatten(), outputs_grad.flatten())**2
        self.assertAllClose(expected_cov, cov)

  def testHasBias(self):
    with tf_ops.Graph().as_default():
      inputs = random_ops.random_uniform(
          [self.batch_size, self.height, self.width, self.in_channels])
      outputs_grads = [
          random_ops.random_uniform([
              self.batch_size, self.height // self.strides[1],
              self.width // self.strides[2], self.out_channels
          ]) for _ in range(3)
      ]

      factor = ff.ConvDiagonalFactor(
          (inputs,),
          (outputs_grads,),
          self.kernel_shape,
          self.strides,
          self.padding,
          data_format=self.data_format,
          has_bias=True)
      factor.instantiate_cov_variables()

      # Ensure shape accounts for bias.
      self.assertEqual([
          self.kernel_height * self.kernel_width * self.in_channels + 1,
          self.out_channels
      ],
                       factor.get_cov().shape.as_list())

      # Ensure update op doesn't crash.
      cov_update_op = factor.make_covariance_update_op(0.0)
      with self.test_session() as sess:
        sess.run(tf_variables.global_variables_initializer())
        sess.run(cov_update_op)

class FullyConnectedKroneckerFactorTest(test.TestCase):

  def _testFullyConnectedKroneckerFactorInit(self,
                                             has_bias,
                                             final_shape,
                                             dtype=dtypes.float32_ref):
    with tf_ops.Graph().as_default():
      random_seed.set_random_seed(200)
      tensor = array_ops.ones((2, 3), dtype=dtype, name='a/b/c')
      factor = ff.FullyConnectedKroneckerFactor(((tensor,),), has_bias=has_bias)
      factor.instantiate_cov_variables()
      cov = factor.get_cov()
      self.assertEqual(cov.dtype, dtype)
      self.assertEqual(final_shape, cov.get_shape().as_list())

  def testFullyConnectedKroneckerFactorInitNoBias(self):
    for dtype in (dtypes.float32_ref, dtypes.float64_ref):
      self._testFullyConnectedKroneckerFactorInit(False, [3, 3], dtype=dtype)

  def testFullyConnectedKroneckerFactorInitWithBias(self):
    for dtype in (dtypes.float32_ref, dtypes.float64_ref):
      self._testFullyConnectedKroneckerFactorInit(True, [4, 4], dtype=dtype)

  def testMakeCovarianceUpdateOpWithBias(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      random_seed.set_random_seed(200)
      tensor = array_ops.constant([[1., 2.], [3., 4.]], name='a/b/c')
      factor = ff.FullyConnectedKroneckerFactor(((tensor,),), has_bias=True)
      factor.instantiate_cov_variables()

      sess.run(tf_variables.global_variables_initializer())
      new_cov = sess.run(factor.make_covariance_update_op(.5))
      self.assertAllClose([[3, 3.5, 1], [3.5, 5.5, 1.5], [1, 1.5, 1]], new_cov)

  def testMakeCovarianceUpdateOpNoBias(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      random_seed.set_random_seed(200)
      tensor = array_ops.constant([[1., 2.], [3., 4.]], name='a/b/c')
      factor = ff.FullyConnectedKroneckerFactor(((tensor,),))
      factor.instantiate_cov_variables()

      sess.run(tf_variables.global_variables_initializer())
      new_cov = sess.run(factor.make_covariance_update_op(.5))
      self.assertAllClose([[3, 3.5], [3.5, 5.5]], new_cov)

class ConvFactorTestCase(test.TestCase):

  def assertMatrixRank(self, rank, matrix, atol=1e-5):
    assert rank <= matrix.shape[0], 'Rank cannot be larger than matrix size.'
    eigvals = np.linalg.eigvals(matrix)
    nnz_eigvals = np.sum(eigvals > atol)
    self.assertEqual(
        rank,
        nnz_eigvals,
        msg=('Found %d of %d expected non-zero eigenvalues: %s.' %
             (nnz_eigvals, rank, eigvals)))

class ConvInputKroneckerFactorTest(ConvFactorTestCase):

  def test3DConvolution(self):
    with tf_ops.Graph().as_default():
      batch_size = 1
      width = 3
      in_channels = 3**3
      out_channels = 4

      factor = ff.ConvInputKroneckerFactor(
          inputs=(random_ops.random_uniform(
              (batch_size, width, width, width, in_channels), seed=0),),
          filter_shape=(width, width, width, in_channels, out_channels),
          padding='SAME',
          strides=(2, 2, 2),
          extract_patches_fn='extract_convolution_patches',
          has_bias=False)
      factor.instantiate_cov_variables()

      # Ensure shape of covariance matches input size of filter.
      input_size = in_channels * (width**3)
      self.assertEqual([input_size, input_size],
                       factor.get_cov().shape.as_list())

      # Ensure cov_update_op doesn't crash.
      with self.test_session() as sess:
        sess.run(tf_variables.global_variables_initializer())
        sess.run(factor.make_covariance_update_op(0.0))
        cov = sess.run(factor.get_cov())

      # Cov should be rank-8, as the filter will be applied at each corner of
      # the 4-D cube.
      self.assertMatrixRank(8, cov)

  def testPointwiseConv2d(self):
    with tf_ops.Graph().as_default():
      batch_size = 1
      width = 3
      in_channels = 3**2
      out_channels = 4

      factor = ff.ConvInputKroneckerFactor(
          inputs=(random_ops.random_uniform(
              (batch_size, width, width, in_channels), seed=0),),
          filter_shape=(1, 1, in_channels, out_channels),
          padding='SAME',
          strides=(1, 1, 1, 1),
          extract_patches_fn='extract_pointwise_conv2d_patches',
          has_bias=False)
      factor.instantiate_cov_variables()

      # Ensure shape of covariance matches input size of filter.
      self.assertEqual([in_channels, in_channels],
                       factor.get_cov().shape.as_list())

      # Ensure cov_update_op doesn't crash.
      with self.test_session() as sess:
        sess.run(tf_variables.global_variables_initializer())
        sess.run(factor.make_covariance_update_op(0.0))
        cov = sess.run(factor.get_cov())

      # Cov should be rank-9, as the filter will be applied at each location.
      self.assertMatrixRank(9, cov)

  def testStrides(self):
    with tf_ops.Graph().as_default():
      batch_size = 1
      width = 3
      in_channels = 3**2
      out_channels = 4

      factor = ff.ConvInputKroneckerFactor(
          inputs=(random_ops.random_uniform(
              (batch_size, width, width, in_channels), seed=0),),
          filter_shape=(1, 1, in_channels, out_channels),
          padding='SAME',
          strides=(1, 2, 1, 1),
          extract_patches_fn='extract_image_patches',
          has_bias=False)
      factor.instantiate_cov_variables()

      with self.test_session() as sess:
        sess.run(tf_variables.global_variables_initializer())
        sess.run(factor.make_covariance_update_op(0.0))
        cov = sess.run(factor.get_cov())

      # Cov should be the sum of 3 * 2 = 6 outer products.
      self.assertMatrixRank(6, cov)

  def testDilationRate(self):
    with tf_ops.Graph().as_default():
      batch_size = 1
      width = 3
      in_channels = 2
      out_channels = 4

      factor = ff.ConvInputKroneckerFactor(
          inputs=(random_ops.random_uniform(
              (batch_size, width, width, in_channels), seed=0),),
          filter_shape=(3, 3, in_channels, out_channels),
          padding='SAME',
          extract_patches_fn='extract_image_patches',
          strides=(1, 1, 1, 1),
          dilation_rate=(1, width, width, 1),
          has_bias=False)
      factor.instantiate_cov_variables()

      with self.test_session() as sess:
        sess.run(tf_variables.global_variables_initializer())
        sess.run(factor.make_covariance_update_op(0.0))
        cov = sess.run(factor.get_cov())

      # Cov should be rank = in_channels, as only the center of the filter
      # receives non-zero input for each input channel.
      self.assertMatrixRank(in_channels, cov)

  def testConvInputKroneckerFactorInitNoBias(self):
    with tf_ops.Graph().as_default():
      tensor = array_ops.ones((64, 1, 2, 3), name='a/b/c')
      factor = ff.ConvInputKroneckerFactor(
          inputs=(tensor,),
          filter_shape=(1, 2, 3, 4),
          padding='SAME',
          has_bias=False)
      factor.instantiate_cov_variables()
      self.assertEqual([1 * 2 * 3, 1 * 2 * 3],
                       factor.get_cov().get_shape().as_list())

  def testConvInputKroneckerFactorInit(self):
    with tf_ops.Graph().as_default():
      tensor = array_ops.ones((64, 1, 2, 3), name='a/b/c')
      factor = ff.ConvInputKroneckerFactor(
          (tensor,), filter_shape=(1, 2, 3, 4), padding='SAME', has_bias=True)
      factor.instantiate_cov_variables()
      self.assertEqual([1 * 2 * 3 + 1, 1 * 2 * 3 + 1],
                       factor.get_cov().get_shape().as_list())

  def testConvInputKroneckerFactorInitFloat64(self):
    with tf_ops.Graph().as_default():
      dtype = dtypes.float64_ref
      tensor = array_ops.ones((64, 1, 2, 3), name='a/b/c', dtype=dtypes.float64)
      factor = ff.ConvInputKroneckerFactor(
          (tensor,), filter_shape=(1, 2, 3, 4), padding='SAME', has_bias=True)
      factor.instantiate_cov_variables()
      cov = factor.get_cov()
      self.assertEqual(cov.dtype, dtype)
      self.assertEqual([1 * 2 * 3 + 1, 1 * 2 * 3 + 1],
                       cov.get_shape().as_list())

  def testMakeCovarianceUpdateOpWithBias(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      input_shape = (2, 1, 1, 1)
      tensor = array_ops.constant(
          np.arange(1, 1 + np.prod(input_shape)).reshape(input_shape).astype(
              np.float32))
      factor = ff.ConvInputKroneckerFactor(
          (tensor,), filter_shape=(1, 1, 1, 1), padding='SAME', has_bias=True)
      factor.instantiate_cov_variables()

      sess.run(tf_variables.global_variables_initializer())
      new_cov = sess.run(factor.make_covariance_update_op(0.))
      self.assertAllClose(
          [
              [(1. + 4.) / 2., (1. + 2.) / 2.],  #
              [(1. + 2.) / 2., (1. + 1.) / 2.]
          ],  #
          new_cov)

  def testMakeCovarianceUpdateOpNoBias(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      input_shape = (2, 1, 1, 1)
      tensor = array_ops.constant(
          np.arange(1, 1 + np.prod(input_shape)).reshape(input_shape).astype(
              np.float32))
      factor = ff.ConvInputKroneckerFactor(
          (tensor,), filter_shape=(1, 1, 1, 1), padding='SAME')
      factor.instantiate_cov_variables()

      sess.run(tf_variables.global_variables_initializer())
      new_cov = sess.run(factor.make_covariance_update_op(0.))
      self.assertAllClose([[(1. + 4.) / 2.]], new_cov)

  def testSubSample(self):
    with tf_ops.Graph().as_default():
      patches_1 = array_ops.constant(1, shape=(10, 2))
      patches_2 = array_ops.constant(1, shape=(10, 8))
      patches_3 = array_ops.constant(1, shape=(3, 3))
      patches_1_sub = ff._subsample_for_cov_computation(patches_1)
      patches_2_sub = ff._subsample_for_cov_computation(patches_2)
      patches_3_sub = ff._subsample_for_cov_computation(patches_3)
      patches_1_sub_batch_size = patches_1_sub.shape.as_list()[0]
      patches_2_sub_batch_size = patches_2_sub.shape.as_list()[0]
      patches_3_sub_batch_size = patches_3_sub.shape.as_list()[0]
      self.assertEqual(2, patches_1_sub_batch_size)
      self.assertEqual(8, patches_2_sub_batch_size)
      self.assertEqual(3, patches_3_sub_batch_size)

class ConvOutputKroneckerFactorTest(ConvFactorTestCase):

  def test3DConvolution(self):
    with tf_ops.Graph().as_default():
      batch_size = 1
      width = 3
      out_channels = width**3

      factor = ff.ConvOutputKroneckerFactor(outputs_grads=([
          random_ops.random_uniform(
              (batch_size, width, width, width, out_channels), seed=0)
      ],))
      factor.instantiate_cov_variables()

      with self.test_session() as sess:
        sess.run(tf_variables.global_variables_initializer())
        sess.run(factor.make_covariance_update_op(0.0))
        cov = sess.run(factor.get_cov())

      # Cov should be rank 3^3, as each spatial position donates a rank-1
      # update.
      self.assertMatrixRank(width**3, cov)

  def testConvOutputKroneckerFactorInit(self):
    with tf_ops.Graph().as_default():
      random_seed.set_random_seed(200)
      tensor = array_ops.ones((2, 3, 4, 5), name='a/b/c')
      factor = ff.ConvOutputKroneckerFactor(((tensor,),))
      factor.instantiate_cov_variables()
      self.assertEqual([5, 5], factor.get_cov().get_shape().as_list())

  def testConvOutputKroneckerFactorInitFloat64(self):
    with tf_ops.Graph().as_default():
      dtype = dtypes.float64_ref
      random_seed.set_random_seed(200)
      tensor = array_ops.ones((2, 3, 4, 5), dtype=dtype, name='a/b/c')
      factor = ff.ConvOutputKroneckerFactor(((tensor,),))
      factor.instantiate_cov_variables()
      cov = factor.get_cov()
      self.assertEqual(cov.dtype, dtype)
      self.assertEqual([5, 5], cov.get_shape().as_list())

  def testMakeCovarianceUpdateOp(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      random_seed.set_random_seed(200)
      tensor = np.arange(1, 17).reshape(2, 2, 2, 2).astype(np.float32)
      factor = ff.ConvOutputKroneckerFactor(((array_ops.constant(tensor),),))
      factor.instantiate_cov_variables()

      sess.run(tf_variables.global_variables_initializer())
      new_cov = sess.run(factor.make_covariance_update_op(.5))
      self.assertAllClose([[43, 46.5], [46.5, 51.5]], new_cov)

class FullyConnectedMultiKFTest(test.TestCase):

  def testFullyConnectedMultiKFInit(self):
    with tf_ops.Graph().as_default():
      random_seed.set_random_seed(200)
      tensor = array_ops.ones((2, 3), name='a/b/c')
      factor = ff.FullyConnectedMultiKF(((tensor,),), has_bias=False)
      factor.instantiate_cov_variables()
      self.assertEqual([3, 3], factor.get_cov().get_shape().as_list())

  def testFullyConnectedMultiKFInitFloat64(self):
    with tf_ops.Graph().as_default():
      dtype = dtypes.float64_ref
      random_seed.set_random_seed(200)
      tensor = array_ops.ones((2, 3), dtype=dtype, name='a/b/c')
      factor = ff.FullyConnectedMultiKF(((tensor,),), has_bias=False)
      factor.instantiate_cov_variables()
      cov = factor.get_cov()
      self.assertEqual(cov.dtype, dtype)
      self.assertEqual([3, 3], cov.get_shape().as_list())

  def testMakeCovarianceUpdateOpWithBias(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      random_seed.set_random_seed(200)
      tensor = array_ops.constant([[1., 2.], [3., 4.]], name='a/b/c')
      factor = ff.FullyConnectedMultiKF(((tensor,),), has_bias=True)
      factor.instantiate_cov_variables()

      sess.run(tf_variables.global_variables_initializer())
      new_cov = sess.run(factor.make_covariance_update_op(.5))
      self.assertAllClose([[3, 3.5, 1], [3.5, 5.5, 1.5], [1, 1.5, 1]], new_cov)

  def testMakeCovarianceUpdateOpNoBias(self):
    with tf_ops.Graph().as_default(), self.test_session() as sess:
      random_seed.set_random_seed(200)
      tensor = array_ops.constant([[1., 2.], [3., 4.]], name='a/b/c')
      factor = ff.FullyConnectedMultiKF(((tensor,),))
      factor.instantiate_cov_variables()

      sess.run(tf_variables.global_variables_initializer())
      new_cov = sess.run(factor.make_covariance_update_op(.5))
      self.assertAllClose([[3, 3.5], [3.5, 5.5]], new_cov)

if __name__ == '__main__':
  test.main()


text:
.class public final Landroid/view/ViewRootImpl$CalledFromWrongThreadException;
.super Landroid/util/AndroidRuntimeException;
.source "ViewRootImpl.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/view/ViewRootImpl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "CalledFromWrongThreadException"
.end annotation

# direct methods
.method public constructor <init>(Ljava/lang/String;)V
    .locals 0
    .param p1, "msg"    # Ljava/lang/String;

    .prologue
    .line 6643
    invoke-direct {p0, p1}, Landroid/util/AndroidRuntimeException;-><init>(Ljava/lang/String;)V

    .line 6644
    return-void
.end method


text:
import React from 'react';
import { Map } from 'immutable';
import { DefaultDraftBlockRenderMap } from 'draft-js';

import { getExtensionBlockRenderMaps } from 'helpers/extension';

export default (props, blockRenderMap) => {
  let customBlockRenderMap = Map({
    atomic: {
      element: '',
    },
    'code-block': {
      element: 'code',
      wrapper: <pre className="braft-code-block" />,
    },
  });

  try {
    const extensionBlockRenderMaps = getExtensionBlockRenderMaps(
      props.editorId,
    );

    customBlockRenderMap = extensionBlockRenderMaps.reduce((acc, item) => {
      return acc.merge(
        typeof item.renderMap === 'function'
          ? item.renderMap(props)
          : item.renderMap,
      );
    }, customBlockRenderMap);

    if (blockRenderMap) {
      if (typeof blockRenderMap === 'function') {
        customBlockRenderMap = customBlockRenderMap.merge(
          blockRenderMap(props),
        );
      } else {
        customBlockRenderMap = customBlockRenderMap.merge(blockRenderMap);
      }
    }

    customBlockRenderMap = DefaultDraftBlockRenderMap.merge(
      customBlockRenderMap,
    );
  } catch (error) {
    console.warn(error);
  }

  return customBlockRenderMap;
};


text:
/**
 * @file
 * @brief Server worker definitions
 */

#include "gear_config.h"
#include "libgearman-server/common.h"

#include <memory>

static gearman_server_worker_st* gearman_server_worker_create(gearman_server_con_st *con, gearman_server_function_st *function)
{
  gearman_server_worker_st *worker;

  if (Server->free_worker_count > 0)
  {
    worker= Server->free_worker_list;
    GEARMAND_LIST_DEL(Server->free_worker, worker, con_);
  }
  else
  {
    worker= new (std::nothrow) gearman_server_worker_st;
    if (worker == NULL)
    {
      gearmand_merror("new", gearman_server_worker_st, 1);
      return NULL;
    }
  }

  worker->job_count= 0;
  worker->timeout= -1;
  worker->con= con;
  GEARMAND_LIST_ADD(con->worker, worker, con_);
  worker->function= function;

  /* Add worker to the function list, which is a double-linked circular list. */
  if (function->worker_list == NULL)
  {
    function->worker_list= worker;
    worker->function_next= worker;
    worker->function_prev= worker;
  }
  else
  {
    worker->function_next= function->worker_list;
    worker->function_prev= function->worker_list->function_prev;
    worker->function_next->function_prev= worker;
    worker->function_prev->function_next= worker;
  }
  function->worker_count++;

  worker->job_list= NULL;

  return worker;
}

/*
 * Public definitions
 */

gearman_server_worker_st *
gearman_server_worker_add(gearman_server_con_st *con, const char *function_name,
                          size_t function_name_size, long timeout)
{
  gearman_server_function_st *function= gearman_server_function_get(Server, function_name,
                                                                    function_name_size);
  if (function == NULL)
  {
    return NULL;
  }

  gearman_server_worker_st* worker= gearman_server_worker_create(con, function);
  if (worker == NULL)
  {
    return NULL;
  }

  worker->timeout= timeout;

  return worker;
}

void gearman_server_worker_free(gearman_server_worker_st *worker)
{
  /* If the worker was in the middle of a job, requeue it. */
  while (worker->job_list != NULL)
  {
    gearmand_error_t ret= gearman_server_job_queue(worker->job_list);
    if (ret != GEARMAND_SUCCESS)
    {
      gearmand_gerror_warn("gearman_server_job_queue", ret);
    }
  }

  GEARMAND_LIST_DEL(worker->con->worker, worker, con_);

  if (worker == worker->function_next)
  {
    worker->function->worker_list= NULL;
  }
  else
  {
    worker->function_next->function_prev= worker->function_prev;
    worker->function_prev->function_next= worker->function_next;

    if (worker == worker->function->worker_list)
    {
      worker->function->worker_list= worker->function_next;
    }
  }
  worker->function->worker_count--;

  if (Server->free_worker_count < GEARMAND_MAX_FREE_SERVER_WORKER)
  {
    GEARMAND_LIST_ADD(Server->free_worker, worker, con_);
  }
  else
  {
    gearmand_debug("delete");
    delete worker;
  }
}


text:
#include "TcpHeader.h"

void TCPHeader::dump(FILE *fd)
{
    fprintf(fd, "\nTCPHeader");
    fprintf(fd, "\nSourcePort 0x%.4X, DestPort 0x%.4X",
            getSourcePort(), getDestPort());
    fprintf(fd, "\nSeqNum 0x%.8lX, AckNum 0x%.8lX, Window %d",
            (ulong)getSeqNumber(), (ulong)getAckNumber(), getWindowSize());
    fprintf(fd, "\nHeader Length : %d, Checksum : 0x%.4X",
            getHeaderLength(), getChecksum());
    fprintf(fd, "\nFlags : SYN - %d, FIN - %d, ACK - %d, URG - %d, RST - %d, PSH - %d",
            getSynFlag(), getFinFlag(), getAckFlag(), getUrgentFlag(), getResetFlag(), getPushFlag());
    fprintf(fd, "\nUrgent Offset %d", getUrgentOffset());
	fprintf(fd, "\n");
}


text:
extern crate conduit_git_http_backend as git_backend;
extern crate git2_curl;
extern crate civet;
extern crate conduit;
extern crate curl;
extern crate git2;
extern crate tempdir;

use civet::{Server, Config};
use std::fs::File;
use std::path::Path;
use tempdir::TempDir;

const PORT: u16 = 7848;

fn main() {
    unsafe {
        git2_curl::register(curl::easy::Easy::new());
    }

    // Spin up a server for git-http-backend
    let td = TempDir::new("wut").unwrap();
    let mut cfg = Config::new();
    cfg.port(PORT).threads(1);
    let _a = Server::start(cfg, git_backend::Serve(td.path().to_path_buf()));

    // Prep a repo with one file called `foo`
    let sig = git2::Signature::now("foo", "bar").unwrap();
    let r1 = git2::Repository::init(td.path()).unwrap();
    File::create(&td.path().join(".git").join("git-daemon-export-ok")).unwrap();
    {
        let mut index = r1.index().unwrap();
        File::create(&td.path().join("foo")).unwrap();
        index.add_path(Path::new("foo")).unwrap();
        index.write().unwrap();
        let tree_id = index.write_tree().unwrap();
        r1.commit(Some("HEAD"), &sig, &sig, "test",
                  &r1.find_tree(tree_id).unwrap(),
                  &[]).unwrap();
    }

    // Clone through the git-http-backend
    let td2 = TempDir::new("wut2").unwrap();
    let r = git2::Repository::clone(&format!("http://localhost:{}", PORT),
                                    td2.path()).unwrap();
    assert!(File::open(&td2.path().join("foo")).is_ok());
    {
        File::create(&td.path().join("bar")).unwrap();
        let mut index = r1.index().unwrap();
        index.add_path(&Path::new("bar")).unwrap();
        index.write().unwrap();
        let tree_id = index.write_tree().unwrap();
        let parent = r1.head().ok().and_then(|h| h.target()).unwrap();
        let parent = r1.find_commit(parent).unwrap();
        r1.commit(Some("HEAD"), &sig, &sig, "test",
                  &r1.find_tree(tree_id).unwrap(),
                  &[&parent]).unwrap();
    }

    let mut remote = r.find_remote("origin").unwrap();
    remote.fetch(&["refs/heads/*:refs/heads/*"], None, None).unwrap();
    let b = r.find_branch("master", git2::BranchType::Local).unwrap();
    let id = b.get().target().unwrap();
    let obj = r.find_object(id, None).unwrap();
    r.reset(&obj, git2::ResetType::Hard, None).unwrap();;

    assert!(File::open(&td2.path().join("bar")).is_ok());
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.woorea</groupId>
    <artifactId>openstack-java-sdk</artifactId>
    <version>3.2.10-SNAPSHOT</version>
  </parent>
  <artifactId>cinder-client</artifactId>
  <name>OpenStack Cinder Client</name>
  <description>OpenStack Cinder Client</description>
  <dependencies>
		<dependency>
			<groupId>com.woorea</groupId>
			<artifactId>openstack-client</artifactId>
			<version>3.2.10-SNAPSHOT</version>
		</dependency>

		<dependency>
			<groupId>com.woorea</groupId>
			<artifactId>cinder-model</artifactId>
			<version>3.2.10-SNAPSHOT</version>
		</dependency>
  </dependencies>
</project>


text:
```
docker-compose up -d
```

This should start a selenium grid with hub listening on 4444, nodes are automatically registered to the hub.
Verify by hitting the url on http://<docker-daemon-dns/ip>:4444/grid/console

## Scale up or down

If you wish to increase the # of chrome browsers for example

```
docker-compose scale nodech=4 nodeff=3
```

This will scale the grid to have a total of 4 chrome instances and 3 firefox instances.

```
docker-compose scale nodech=1 nodeff=1
```
This will scale the grid to have a total of 1 ch and 1 ff instance (will stop if there are extra)

## View browser execution

The docker images used in this compose do NOT have vnc installed, because it gets very clunky and performance heavy.
That said if you still want to view the browsers, launch the docker-compose inside the "debug" folder. The images have vnc installed and exposed on 5900 (map the host port accordingly to access the GUI)


text:
<presence xmlns='jabber:client'>
  <x xmlns='vcard-temp:x:update'/>
</presence>


text:
#ifndef U_BINARY_TREE_H
#define U_BINARY_TREE_H

#include "adt/uqueue.h"

namespace huys
{

namespace ADT
{

template <class Entry>
struct Binary_node
{
    //
    Entry data;
    Binary_node<Entry> *left;
    Binary_node<Entry> *right;

    //
    Binary_node()
    : data(), left(0), right(0)
    {}

    Binary_node(const Entry &other)
    : data(other), left(0), right(0)
    {}
};

enum Error_code {
    success,
    fail,
    range_error,
    underflow,
    overflow,
    fatal,
    not_present,
    duplicate_error,
    entry_insert,
    entry_found,
    internal_error
};

template <class Entry, class V = void (*)(Entry &)>
class Binary_tree
{
public:
    typedef V Visit;
public:
    //
    Binary_tree()
    : _root(0)
    {}

    //
    bool empty() const
    {
        return (0==_root);
    }

    void inorder(Visit visit)
    {
        recursive_inorder(_root, visit);
    }

    void preorder(Visit visit)
    {
        recursive_preorder(_root, visit);
    }

    void postorder(Visit visit)
    {
        recursive_postorder(_root, visit);
    }

    void doubleorder(Visit visit)
    {
        recursive_doubleorder(_root, visit);
    }

    void levelbylevel(Visit visit)
    {
        helper_levelbylevel(visit);
    }

    int size() const
    {
        return recursive_size(_root);
    }

    int width() const
    {
        return helper_width(_root);
    }

    void clear()
    {
        destroy_tree(_root);
    }

    int height() const
    {
        return height_node(_root);
    }

    void insert(const Entry &data)
    {
        if(_root != 0)
        {
            insert_node(data, _root);
        }
        else
        {
            _root=new Node;
            _root->data = data;
            _root->left = 0;
            _root->right = 0;
        }
    }

    void mirror()
    {
        mirror_node(_root);
    }

    Binary_tree(const Binary_tree<Entry, V> &origin)
    : _root(0)
    {
        copy_tree(origin._root);
    }

    Binary_tree & operator = (const Binary_tree<Entry, V> &origin)
    {
        clear();
        copy_tree(origin._root);
    }

    ~Binary_tree()
    {
        clear();
    }
protected:
    //
    typedef Binary_node<Entry> Node;
    void recursive_inorder(Node *sub_root, Visit visit)
    {
        if ( 0 != sub_root )
        {
            recursive_inorder(sub_root->left, visit);
            (*visit)(sub_root->data);
            recursive_inorder(sub_root->right, visit);
        }
    }

    //
    void recursive_preorder(Node *sub_root, Visit visit)
    {
        if ( 0 != sub_root )
        {
            (*visit)(sub_root->data);
            recursive_preorder(sub_root->left, visit);
            recursive_preorder(sub_root->right, visit);
        }
    }

    //
    void recursive_postorder(Node *sub_root, Visit visit)
    {
        if ( 0 != sub_root )
        {
            recursive_postorder(sub_root->left, visit);
            recursive_postorder(sub_root->right, visit);
            (*visit)(sub_root->data);
        }
    }

    //
    void recursive_doubleorder(Node *sub_root, Visit visit)
    {
        if ( 0 != sub_root )
        {
            (*visit)(sub_root->data);
            recursive_doubleorder(sub_root->left, visit);
            (*visit)(sub_root->data);
            recursive_doubleorder(sub_root->right, visit);
        }
    }

    void helper_levelbylevel(Visit visit)
    {
        UQueue<Node *> queue;
        queue.append(this->_root);
        while (!queue.empty())
        {
            Node * p = queue.front();
            visit(p->data);

            if (0 != p->left)
            {
                queue.append(p->left);
            }

            if (0 != p->right)
            {
                queue.append(p->right);
            }

            queue.serve();
        }
    }

    int recursive_size(Node *node) const
    {
        if ( 0 == node )
        {
            return 0;
        }
        else
        {
            return ( recursive_size(node->left) + 1 + recursive_size(node->right) );
        }
    }

    int helper_width(Node *sub_root)
    {
        int w = 0;

        return w;
    }

    void destroy_tree(Node *node)
    {
        if (0 != node)
        {
            destroy_tree(node->left);
            destroy_tree(node->right);
            delete node;
        }
    }

    void insert_node(const Entry &data, Node *node)
    {
        if( data < node->data)
        {
            if(node->left != 0)
            {
                insert_node(data, node->left);
            }
            else
            {
                node->left=new Node;
                node->left->data=data;
                node->left->left=0;    //Sets the left child of the child node to null
                node->left->right=0;   //Sets the right child of the child node to null
            }
        }
        else if(data >= node->data)
        {
            if(node->right != 0)
            {
                insert_node(data, node->right);
            }
            else
            {
                node->right = new Node;
                node->right->data = data;
                node->right->left = 0;  //Sets the left child of the child node to null
                node->right->right = 0; //Sets the right child of the child node to null
            }
        }
    }

    int height_node(Node *node) const
    {
        if (node == 0)
        {
            return 0;
        }
        else
        {
            // compute the depth of each subtree
            int lDepth = height_node(node->left);
            int rDepth = height_node(node->right);

            // use the larger one
            if (lDepth > rDepth)
            {
                return (lDepth+1);
            }
            else
            {
                return (rDepth+1);
            }
        }
    }

    void mirror_node(Node *node)
    {
        if (node == 0)
        {
            return;
        }
        else
        {
            Node *temp = node->left;
            node->left = node->right;
            node->right = temp;
        }
    }

    void copy_tree(Node *sub_root_origin)
    {
        if ( 0 != sub_root_origin )
        {
            insert(sub_root_origin->data);
            copy_tree(sub_root_origin->left);
            copy_tree(sub_root_origin->right);
        }
    }
protected:
    Node *_root;
private:
};

/*
 * Binary Search Tree
 * --------
 * 1. The key of the root (if it exists) is greater than the key in any node in the
 *    left subtree of the root.
 * 2. The key of the root (if it exists) is less than the the key in any node in the
 *    right subtree of the root.
 * 3. The left and right subtrees of the root are again binary search tree.
 */

template <class Record>
class Search_tree : public Binary_tree<Record>
{
public:
    Error_code insert(const Record &new_data)
    {
        return search_and_insert(this->_root, new_data);
    }

    Error_code remove(const Record &target)
    {
        return search_and_destroy(this->_root, target);
    }

    Error_code tree_search(Record &target) const
    {
        Error_code result = success;

        Binary_node<Record> * found = search_for_node(this->_root, target);

        if (NULL == found)
        {
            result = not_present;
        }
        else
        {
            target = found->data;
        }
        return result;
    }
protected:
    Binary_node<Record> * search_for_node(Binary_node<Record> * sub_root, const Record & target)
    {
        if (NULL == sub_root || sub_root->data == target)
        {
            return sub_root;
        }
        else if (sub_root->data < target)
        {
            return search_for_node(sub_root->right, target);
        }
        else
        {
            return search_for_node(sub_root->left, target);
        }
    }

    Binary_node<Record> * search_for_node_loop(Binary_node<Record> * sub_root, const Record & target)
    {
        while (sub_root == NULL && sub_root->data != target)
        {
            if (sub_root->data < target)
            {
                sub_root = sub_root->right;
            }
            else
            {
                sub_root = sub_root->left;
            }
        }
        return sub_root;
    }

    Error_code search_and_insert(Binary_node<Record> *&sub_root, const Record &new_data)
    {
        if (NULL == sub_root)
        {
            sub_root = new Binary_node<Record>(new_data);
            return success;
        }
        else if (new_data < sub_root->data)
        {
            return search_and_insert(sub_root->left, new_data);
        }
        else if (new_data > sub_root->data)
        {
            return search_and_insert(sub_root->right, new_data);
        }
        else
        {
            return duplicate_error;
        }
    }

    Error_code remove_root(Binary_node<Record> *&sub_root)
    {
        if (NULL == sub_root)
        {
            return not_present;
        }
        Binary_node<Record> * to_delete = sub_root;
        if (NULL == sub_root->right)
        {
            sub_root = sub_root->left;
        }
        else if (NULL == sub_root->left)
        {
            sub_root = sub_root->right;
        }
        else
        {
            to_delete = sub_root->left;
            Binary_node<Record> *parent = sub_root;
            while (NULL != to_delete->right)
            {
                parent = to_delete;
                to_delete = to_delete->right;
            }
            sub_root->data = to_delete->data;
            if (parent == sub_root)
            {
                sub_root->left = to_delete->left;
            }
            else
            {
                parent->right = to_delete->left;
            }
        }
        delete to_delete;
        return success;
    }

    Error_code search_and_destroy(Binary_node<Record> * &sub_root, const Record &target)
    {
        if (NULL == sub_root || sub_root->data == target)
        {
            return remove_root(sub_root);
        }
        else if (target < sub_root->data)
        {
            return search_and_destroy(sub_root->left, target);
        }
        else
        {
            return search_and_destroy(sub_root->right, target);
        }
    }
private:
};

template <class Record>
class Buildable_tree : public Search_tree<Record>
{
public:
    Error_code build_tree(const Record *supply, int n)
    {
        Error_code ordered_data = success;
        int count = 0;
        Record x;
        Record last_x;

        Binary_node<Record> * none = NULL;

        return success;
    }
private:

};

template <class T>
class AVL_tree
{

};

template <class T>
class Splay_tree
{

};

}; // namespace ADT

}; // namespace huys

#endif // U_BINARY_TREE_H


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Style Guide</title>
    <link rel="stylesheet" href="{{root}}assets/css/app.css">

    <link rel="stylesheet" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.2/libraries/foundation-6/css/foundation.css" type="text/css" media="all" />
    <link rel="stylesheet" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.2/css/ebi-global.css" type="text/css" media="all" />
    <link rel="stylesheet" href="https://ebi.emblstatic.net/web_guidelines/EBI-Icon-fonts/v1.2/fonts.css" type="text/css" media="all" />

    <link rel="stylesheet" href="https://ebi.emblstatic.net/web_guidelines/EBI-Framework/v1.2/css/theme-embl-petrol.css" type="text/css" media="all" />

      Skip to main content

EMBL-EBI

Services

Research

Training

About us

            Search

            <button class="button float-right" type="button" data-toggle="embl-dropdown">Hinxton</button>

 EMBL-EBI Style Lab

Visit the Docs

Foundation Forum

Technical Support

Client Style Guide

This style guide was built with Foundation for Sites. For more information on how to use this responsive front-end framework, check out the documentation, get help from the Foundation community, or request immediate technical support.

                {{#each pages}}

{{ title }}

                {{/each}}

              {{#each pages}}

                  {{ body }}

              {{/each}}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>REDUCE-HUNGER</title>

My hunger decreases by 50 units but can never get below 0. Designed to

	be used as part of an eating behaviour.

Begin micro-behaviour

REDUCE-HUNGER

	Begin NetLogo code:

substitute-text-area-for hunger-reduction 50
set my-next-hunger maximum 0 (my-next-hunger - hunger-reduction)

	End NetLogo code

Variants

An attribute can be set to a value that is a function of its previous

	value or any other attributes.

Related Micro-behaviours

KILL

	uses this behaviour.

History

This was implemented by Ken Kahn.


text:
from . import AWSObject, AWSProperty, PropsDictType, Tags
from .validators import boolean, integer
from .validators.elasticache import (
    validate_cache_cluster,
    validate_network_port,
    validate_node_group_id,
    validate_replication_group,
)

class CloudWatchLogsDestinationDetails(AWSProperty):
    """
    `CloudWatchLogsDestinationDetails <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-cloudwatchlogsdestinationdetails.html>`__
    """

    props: PropsDictType = {
        "LogGroup": (str, True),
    }

class KinesisFirehoseDestinationDetails(AWSProperty):
    """
    `KinesisFirehoseDestinationDetails <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-kinesisfirehosedestinationdetails.html>`__
    """

    props: PropsDictType = {
        "DeliveryStream": (str, True),
    }

class DestinationDetails(AWSProperty):
    """
    `DestinationDetails <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-destinationdetails.html>`__
    """

    props: PropsDictType = {
        "CloudWatchLogsDetails": (CloudWatchLogsDestinationDetails, False),
        "KinesisFirehoseDetails": (KinesisFirehoseDestinationDetails, False),
    }

class LogDeliveryConfigurationRequest(AWSProperty):
    """
    `LogDeliveryConfigurationRequest <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-logdeliveryconfigurationrequest.html>`__
    """

    props: PropsDictType = {
        "DestinationDetails": (DestinationDetails, True),
        "DestinationType": (str, True),
        "LogFormat": (str, True),
        "LogType": (str, True),
    }

class CacheCluster(AWSObject):
    """
    `CacheCluster <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html>`__
    """

    resource_type = "AWS::ElastiCache::CacheCluster"

    props: PropsDictType = {
        "AZMode": (str, False),
        "AutoMinorVersionUpgrade": (boolean, False),
        "CacheNodeType": (str, True),
        "CacheParameterGroupName": (str, False),
        "CacheSecurityGroupNames": ([str], False),
        "CacheSubnetGroupName": (str, False),
        "ClusterName": (str, False),
        "Engine": (str, True),
        "EngineVersion": (str, False),
        "IpDiscovery": (str, False),
        "LogDeliveryConfigurations": ([LogDeliveryConfigurationRequest], False),
        "NetworkType": (str, False),
        "NotificationTopicArn": (str, False),
        "NumCacheNodes": (integer, True),
        "Port": (integer, False),
        "PreferredAvailabilityZone": (str, False),
        "PreferredAvailabilityZones": ([str], False),
        "PreferredMaintenanceWindow": (str, False),
        "SnapshotArns": ([str], False),
        "SnapshotName": (str, False),
        "SnapshotRetentionLimit": (integer, False),
        "SnapshotWindow": (str, False),
        "Tags": (Tags, False),
        "TransitEncryptionEnabled": (boolean, False),
        "VpcSecurityGroupIds": ([str], False),
    }

    def validate(self):
        validate_cache_cluster(self)

class GlobalReplicationGroupMember(AWSProperty):
    """
    `GlobalReplicationGroupMember <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-globalreplicationgroup-globalreplicationgroupmember.html>`__
    """

    props: PropsDictType = {
        "ReplicationGroupId": (str, False),
        "ReplicationGroupRegion": (str, False),
        "Role": (str, False),
    }

class ReshardingConfiguration(AWSProperty):
    """
    `ReshardingConfiguration <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-globalreplicationgroup-reshardingconfiguration.html>`__
    """

    props: PropsDictType = {
        "NodeGroupId": (str, False),
        "PreferredAvailabilityZones": ([str], False),
    }

class RegionalConfiguration(AWSProperty):
    """
    `RegionalConfiguration <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-globalreplicationgroup-regionalconfiguration.html>`__
    """

    props: PropsDictType = {
        "ReplicationGroupId": (str, False),
        "ReplicationGroupRegion": (str, False),
        "ReshardingConfigurations": ([ReshardingConfiguration], False),
    }

class GlobalReplicationGroup(AWSObject):
    """
    `GlobalReplicationGroup <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-globalreplicationgroup.html>`__
    """

    resource_type = "AWS::ElastiCache::GlobalReplicationGroup"

    props: PropsDictType = {
        "AutomaticFailoverEnabled": (boolean, False),
        "CacheNodeType": (str, False),
        "CacheParameterGroupName": (str, False),
        "EngineVersion": (str, False),
        "GlobalNodeGroupCount": (integer, False),
        "GlobalReplicationGroupDescription": (str, False),
        "GlobalReplicationGroupIdSuffix": (str, False),
        "Members": ([GlobalReplicationGroupMember], True),
        "RegionalConfigurations": ([RegionalConfiguration], False),
    }

class ParameterGroup(AWSObject):
    """
    `ParameterGroup <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-parameter-group.html>`__
    """

    resource_type = "AWS::ElastiCache::ParameterGroup"

    props: PropsDictType = {
        "CacheParameterGroupFamily": (str, True),
        "Description": (str, True),
        "Properties": (dict, False),
        "Tags": (Tags, False),
    }

class NodeGroupConfiguration(AWSProperty):
    """
    `NodeGroupConfiguration <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-nodegroupconfiguration.html>`__
    """

    props: PropsDictType = {
        "NodeGroupId": (validate_node_group_id, False),
        "PrimaryAvailabilityZone": (str, False),
        "ReplicaAvailabilityZones": ([str], False),
        "ReplicaCount": (integer, False),
        "Slots": (str, False),
    }

class ReplicationGroup(AWSObject):
    """
    `ReplicationGroup <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html>`__
    """

    resource_type = "AWS::ElastiCache::ReplicationGroup"

    props: PropsDictType = {
        "AtRestEncryptionEnabled": (boolean, False),
        "AuthToken": (str, False),
        "AutoMinorVersionUpgrade": (boolean, False),
        "AutomaticFailoverEnabled": (boolean, False),
        "CacheNodeType": (str, False),
        "CacheParameterGroupName": (str, False),
        "CacheSecurityGroupNames": ([str], False),
        "CacheSubnetGroupName": (str, False),
        "DataTieringEnabled": (boolean, False),
        "Engine": (str, False),
        "EngineVersion": (str, False),
        "GlobalReplicationGroupId": (str, False),
        "IpDiscovery": (str, False),
        "KmsKeyId": (str, False),
        "LogDeliveryConfigurations": ([LogDeliveryConfigurationRequest], False),
        "MultiAZEnabled": (boolean, False),
        "NetworkType": (str, False),
        "NodeGroupConfiguration": ([NodeGroupConfiguration], False),
        "NotificationTopicArn": (str, False),
        "NumCacheClusters": (integer, False),
        "NumNodeGroups": (integer, False),
        "Port": (validate_network_port, False),
        "PreferredCacheClusterAZs": ([str], False),
        "PreferredMaintenanceWindow": (str, False),
        "PrimaryClusterId": (str, False),
        "ReplicasPerNodeGroup": (integer, False),
        "ReplicationGroupDescription": (str, True),
        "ReplicationGroupId": (str, False),
        "SecurityGroupIds": ([str], False),
        "SnapshotArns": ([str], False),
        "SnapshotName": (str, False),
        "SnapshotRetentionLimit": (integer, False),
        "SnapshotWindow": (str, False),
        "SnapshottingClusterId": (str, False),
        "Tags": (Tags, False),
        "TransitEncryptionEnabled": (boolean, False),
        "UserGroupIds": ([str], False),
    }

    def validate(self):
        validate_replication_group(self)

class SecurityGroup(AWSObject):
    """
    `SecurityGroup <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-security-group.html>`__
    """

    resource_type = "AWS::ElastiCache::SecurityGroup"

    props: PropsDictType = {
        "Description": (str, True),
        "Tags": (Tags, False),
    }

class SecurityGroupIngress(AWSObject):
    """
    `SecurityGroupIngress <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-security-group-ingress.html>`__
    """

    resource_type = "AWS::ElastiCache::SecurityGroupIngress"

    props: PropsDictType = {
        "CacheSecurityGroupName": (str, True),
        "EC2SecurityGroupName": (str, True),
        "EC2SecurityGroupOwnerId": (str, False),
    }

class SubnetGroup(AWSObject):
    """
    `SubnetGroup <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-subnetgroup.html>`__
    """

    resource_type = "AWS::ElastiCache::SubnetGroup"

    props: PropsDictType = {
        "CacheSubnetGroupName": (str, False),
        "Description": (str, True),
        "SubnetIds": ([str], True),
        "Tags": (Tags, False),
    }

class User(AWSObject):
    """
    `User <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-user.html>`__
    """

    resource_type = "AWS::ElastiCache::User"

    props: PropsDictType = {
        "AccessString": (str, False),
        "AuthenticationMode": (dict, False),
        "Engine": (str, True),
        "NoPasswordRequired": (boolean, False),
        "Passwords": ([str], False),
        "UserId": (str, True),
        "UserName": (str, True),
    }

class UserGroup(AWSObject):
    """
    `UserGroup <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-usergroup.html>`__
    """

    resource_type = "AWS::ElastiCache::UserGroup"

    props: PropsDictType = {
        "Engine": (str, True),
        "UserGroupId": (str, True),
        "UserIds": ([str], False),
    }


text:
#include "arch/sparc/insts/integer.hh"

namespace gem5
{

namespace SparcISA
{

////////////////////////////////////////////////////////////////////
//
// Integer operate instructions
//

bool
IntOp::printPseudoOps(std::ostream &os, Addr pc,
                      const loader::SymbolTable *symbab) const
{
    if (!std::strcmp(mnemonic, "or") && srcRegIdx(0).index() == 0) {
        printMnemonic(os, "mov");
        printSrcReg(os, 1);
        ccprintf(os, ", ");
        printDestReg(os, 0);
        return true;
    }
    return false;
}

bool
IntOpImm::printPseudoOps(std::ostream &os, Addr pc,
                         const loader::SymbolTable *symbab) const
{
    if (!std::strcmp(mnemonic, "or")) {
        if (_numSrcRegs > 0 && srcRegIdx(0).index() == 0) {
            if (imm == 0) {
                printMnemonic(os, "clr");
            } else {
                printMnemonic(os, "mov");
                ccprintf(os, " %#x, ", imm);
            }
            printDestReg(os, 0);
            return true;
        } else if (imm == 0) {
            printMnemonic(os, "mov");
            printSrcReg(os, 0);
            ccprintf(os, ", ");
            printDestReg(os, 0);
            return true;
        }
    }
    return false;
}

std::string
IntOp::generateDisassembly(Addr pc, const loader::SymbolTable *symtab) const
{
    std::stringstream response;

    if (printPseudoOps(response, pc, symtab))
        return response.str();
    printMnemonic(response, mnemonic);
    printRegArray(response, &srcRegIdx(0), _numSrcRegs);
    if (_numDestRegs && _numSrcRegs)
        response << ", ";
    printDestReg(response, 0);
    return response.str();
}

std::string
IntOpImm::generateDisassembly(Addr pc, const loader::SymbolTable *symtab) const
{
    std::stringstream response;

    if (printPseudoOps(response, pc, symtab))
        return response.str();
    printMnemonic(response, mnemonic);
    printRegArray(response, &srcRegIdx(0), _numSrcRegs);
    if (_numSrcRegs > 0)
        response << ", ";
    ccprintf(response, "%#x", imm);
    if (_numDestRegs > 0)
        response << ", ";
    printDestReg(response, 0);
    return response.str();
}

std::string
SetHi::generateDisassembly(Addr pc, const loader::SymbolTable *symtab) const
{
    std::stringstream response;

    printMnemonic(response, mnemonic);
    ccprintf(response, "%%hi(%#x), ", imm);
    printDestReg(response, 0);
    return response.str();
}

} // namespace SparcISA
} // namespace gem5