text:
package org.apache.hadoop.hdfs.server.namenode;

import static org.apache.hadoop.hdfs.protocol.HdfsConstants.BLOCK_STORAGE_POLICY_ID_UNSPECIFIED;
import static org.apache.hadoop.hdfs.server.namenode.snapshot.Snapshot.CURRENT_STATE_ID;
import static org.apache.hadoop.hdfs.server.namenode.snapshot.Snapshot.NO_SNAPSHOT_ID;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.fs.permission.PermissionStatus;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy;
import org.apache.hadoop.hdfs.protocol.QuotaExceededException;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockCollection;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockInfo;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockStoragePolicySuite;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeStorageInfo;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.BlockUCState;
import org.apache.hadoop.hdfs.server.namenode.snapshot.FileDiff;
import org.apache.hadoop.hdfs.server.namenode.snapshot.FileDiffList;
import org.apache.hadoop.hdfs.server.namenode.snapshot.FileWithSnapshotFeature;
import org.apache.hadoop.hdfs.server.namenode.snapshot.Snapshot;
import org.apache.hadoop.hdfs.util.LongBitFormat;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;

/** I-node for closed file. */
@InterfaceAudience.Private
public class INodeFile extends INodeWithAdditionalFields
    implements INodeFileAttributes, BlockCollection {

  /** The same as valueOf(inode, path, false). */
  public static INodeFile valueOf(INode inode, String path
      ) throws FileNotFoundException {
    return valueOf(inode, path, false);
  }

  /** Cast INode to INodeFile. */
  public static INodeFile valueOf(INode inode, String path, boolean acceptNull)
      throws FileNotFoundException {
    if (inode == null) {
      if (acceptNull) {
        return null;
      } else {
        throw new FileNotFoundException("File does not exist: " + path);
      }
    }
    if (!inode.isFile()) {
      throw new FileNotFoundException("Path is not a file: " + path);
    }
    return inode.asFile();
  }

  /**
   * Bit format:
   * [4-bit storagePolicyID][12-bit replication][48-bit preferredBlockSize]
   */
  enum HeaderFormat {
    PREFERRED_BLOCK_SIZE(null, 48, 1),
    REPLICATION(PREFERRED_BLOCK_SIZE.BITS, 12, 1),
    STORAGE_POLICY_ID(REPLICATION.BITS, BlockStoragePolicySuite.ID_BIT_LENGTH,
        0);

    private final LongBitFormat BITS;

    private HeaderFormat(LongBitFormat previous, int length, long min) {
      BITS = new LongBitFormat(name(), previous, length, min);
    }

    static short getReplication(long header) {
      return (short)REPLICATION.BITS.retrieve(header);
    }

    static long getPreferredBlockSize(long header) {
      return PREFERRED_BLOCK_SIZE.BITS.retrieve(header);
    }

    static byte getStoragePolicyID(long header) {
      return (byte)STORAGE_POLICY_ID.BITS.retrieve(header);
    }

    static long toLong(long preferredBlockSize, short replication,
        byte storagePolicyID) {
      long h = 0;
      if (preferredBlockSize == 0) {
        preferredBlockSize = PREFERRED_BLOCK_SIZE.BITS.getMin();
      }
      h = PREFERRED_BLOCK_SIZE.BITS.combine(preferredBlockSize, h);
      h = REPLICATION.BITS.combine(replication, h);
      h = STORAGE_POLICY_ID.BITS.combine(storagePolicyID, h);
      return h;
    }

  }

  private long header = 0L;

  private BlockInfo[] blocks;

  INodeFile(long id, byte[] name, PermissionStatus permissions, long mtime,
            long atime, BlockInfo[] blklist, short replication,
            long preferredBlockSize) {
    this(id, name, permissions, mtime, atime, blklist, replication,
         preferredBlockSize, (byte) 0);
  }

  INodeFile(long id, byte[] name, PermissionStatus permissions, long mtime,
      long atime, BlockInfo[] blklist, short replication,
      long preferredBlockSize, byte storagePolicyID) {
    super(id, name, permissions, mtime, atime);
    header = HeaderFormat.toLong(preferredBlockSize, replication, storagePolicyID);
    this.blocks = blklist;
  }

  public INodeFile(INodeFile that) {
    super(that);
    this.header = that.header;
    this.blocks = that.blocks;
    this.features = that.features;
  }

  public INodeFile(INodeFile that, FileDiffList diffs) {
    this(that);
    Preconditions.checkArgument(!that.isWithSnapshot());
    this.addSnapshotFeature(diffs);
  }

  /** @return true unconditionally. */
  @Override
  public final boolean isFile() {
    return true;
  }

  /** @return this object. */
  @Override
  public final INodeFile asFile() {
    return this;
  }

  @Override
  public boolean metadataEquals(INodeFileAttributes other) {
    return other != null
        && getHeaderLong()== other.getHeaderLong()
        && getPermissionLong() == other.getPermissionLong()
        && getAclFeature() == other.getAclFeature()
        && getXAttrFeature() == other.getXAttrFeature();
  }

  /* Start of Under-Construction Feature */

  /**
   * If the inode contains a {@link FileUnderConstructionFeature}, return it;
   * otherwise, return null.
   */
  public final FileUnderConstructionFeature getFileUnderConstructionFeature() {
    return getFeature(FileUnderConstructionFeature.class);
  }

  /** Is this file under construction? */
  @Override // BlockCollection
  public boolean isUnderConstruction() {
    return getFileUnderConstructionFeature() != null;
  }

  INodeFile toUnderConstruction(String clientName, String clientMachine) {
    Preconditions.checkState(!isUnderConstruction(),
        "file is already under construction");
    FileUnderConstructionFeature uc = new FileUnderConstructionFeature(
        clientName, clientMachine);
    addFeature(uc);
    return this;
  }

  /**
   * Convert the file to a complete file, i.e., to remove the Under-Construction
   * feature.
   */
  public INodeFile toCompleteFile(long mtime) {
    Preconditions.checkState(isUnderConstruction(),
        "file is no longer under construction");
    FileUnderConstructionFeature uc = getFileUnderConstructionFeature();
    if (uc != null) {
      assertAllBlocksComplete();
      removeFeature(uc);
      this.setModificationTime(mtime);
    }
    return this;
  }

  /** Assert all blocks are complete. */
  private void assertAllBlocksComplete() {
    if (blocks == null) {
      return;
    }
    for (int i = 0; i < blocks.length; i++) {
      Preconditions.checkState(blocks[i].isComplete(), "Failed to finalize"
          + " %s %s since blocks[%s] is non-complete, where blocks=%s.",
          getClass().getSimpleName(), this, i, Arrays.asList(blocks));
    }
  }

  @Override // BlockCollection
  public void setBlock(int index, BlockInfo blk) {
    this.blocks[index] = blk;
  }

  @Override // BlockCollection, the file should be under construction
  public void convertLastBlockToUC(BlockInfo lastBlock,
      DatanodeStorageInfo[] locations) throws IOException {
    Preconditions.checkState(isUnderConstruction(),
        "file is no longer under construction");

    if (numBlocks() == 0) {
      throw new IOException("Failed to set last block: File is empty.");
    }
    lastBlock.convertToBlockUnderConstruction(BlockUCState.UNDER_CONSTRUCTION,
        locations);
  }

  void setLastBlock(BlockInfo blk) {
    blk.setBlockCollection(this);
    setBlock(numBlocks() - 1, blk);
  }

  /**
   * Remove a block from the block list. This block should be
   * the last one on the list.
   */
  BlockInfo removeLastBlock(Block oldblock) {
    Preconditions.checkState(isUnderConstruction(),
        "file is no longer under construction");
    if (blocks == null || blocks.length == 0) {
      return null;
    }
    int size_1 = blocks.length - 1;
    if (!blocks[size_1].equals(oldblock)) {
      return null;
    }

    BlockInfo ucBlock = blocks[size_1];
    //copy to a new list
    BlockInfo[] newlist = new BlockInfo[size_1];
    System.arraycopy(blocks, 0, newlist, 0, size_1);
    setBlocks(newlist);
    return ucBlock;
  }

  /* End of Under-Construction Feature */

  /* Start of Snapshot Feature */

  public FileWithSnapshotFeature addSnapshotFeature(FileDiffList diffs) {
    Preconditions.checkState(!isWithSnapshot(),
        "File is already with snapshot");
    FileWithSnapshotFeature sf = new FileWithSnapshotFeature(diffs);
    this.addFeature(sf);
    return sf;
  }

  /**
   * If feature list contains a {@link FileWithSnapshotFeature}, return it;
   * otherwise, return null.
   */
  public final FileWithSnapshotFeature getFileWithSnapshotFeature() {
    return getFeature(FileWithSnapshotFeature.class);
  }

  /** Is this file has the snapshot feature? */
  public final boolean isWithSnapshot() {
    return getFileWithSnapshotFeature() != null;
  }

  @Override
  public String toDetailString() {
    FileWithSnapshotFeature sf = this.getFileWithSnapshotFeature();
    return super.toDetailString() + (sf == null ? "" : sf.getDetailedString());
  }

  @Override
  public INodeFileAttributes getSnapshotINode(final int snapshotId) {
    FileWithSnapshotFeature sf = this.getFileWithSnapshotFeature();
    if (sf != null) {
      return sf.getDiffs().getSnapshotINode(snapshotId, this);
    } else {
      return this;
    }
  }

  @Override
  public void recordModification(final int latestSnapshotId) {
    recordModification(latestSnapshotId, false);
  }

  public void recordModification(final int latestSnapshotId, boolean withBlocks) {
    if (isInLatestSnapshot(latestSnapshotId)
        && !shouldRecordInSrcSnapshot(latestSnapshotId)) {
      // the file is in snapshot, create a snapshot feature if it does not have
      FileWithSnapshotFeature sf = this.getFileWithSnapshotFeature();
      if (sf == null) {
        sf = addSnapshotFeature(null);
      }
      // record self in the diff list if necessary
      sf.getDiffs().saveSelf2Snapshot(latestSnapshotId, this, null, withBlocks);
    }
  }

  public FileDiffList getDiffs() {
    FileWithSnapshotFeature sf = this.getFileWithSnapshotFeature();
    if (sf != null) {
      return sf.getDiffs();
    }
    return null;
  }

  /* End of Snapshot Feature */

  /** @return the replication factor of the file. */
  public final short getFileReplication(int snapshot) {
    if (snapshot != CURRENT_STATE_ID) {
      return getSnapshotINode(snapshot).getFileReplication();
    }
    return HeaderFormat.getReplication(header);
  }

  /** The same as getFileReplication(null). */
  @Override // INodeFileAttributes
  public final short getFileReplication() {
    return getFileReplication(CURRENT_STATE_ID);
  }

  @Override // BlockCollection
  public short getPreferredBlockReplication() {
    short max = getFileReplication(CURRENT_STATE_ID);
    FileWithSnapshotFeature sf = this.getFileWithSnapshotFeature();
    if (sf != null) {
      short maxInSnapshot = sf.getMaxBlockRepInDiffs();
      if (sf.isCurrentFileDeleted()) {
        return maxInSnapshot;
      }
      max = maxInSnapshot > max ? maxInSnapshot : max;
    }
    return max;
  }

  /** Set the replication factor of this file. */
  private void setFileReplication(short replication) {
    header = HeaderFormat.REPLICATION.BITS.combine(replication, header);
  }

  /** Set the replication factor of this file. */
  public final INodeFile setFileReplication(short replication,
      int latestSnapshotId) throws QuotaExceededException {
    recordModification(latestSnapshotId);
    setFileReplication(replication);
    return this;
  }

  /** @return preferred block size (in bytes) of the file. */
  @Override
  public long getPreferredBlockSize() {
    return HeaderFormat.getPreferredBlockSize(header);
  }

  @Override
  public byte getLocalStoragePolicyID() {
    return HeaderFormat.getStoragePolicyID(header);
  }

  @Override
  public byte getStoragePolicyID() {
    byte id = getLocalStoragePolicyID();
    if (id == BLOCK_STORAGE_POLICY_ID_UNSPECIFIED) {
      return this.getParent() != null ?
          this.getParent().getStoragePolicyID() : id;
    }
    return id;
  }

  private void setStoragePolicyID(byte storagePolicyId) {
    header = HeaderFormat.STORAGE_POLICY_ID.BITS.combine(storagePolicyId,
        header);
  }

  public final void setStoragePolicyID(byte storagePolicyId,
      int latestSnapshotId) throws QuotaExceededException {
    recordModification(latestSnapshotId);
    setStoragePolicyID(storagePolicyId);
  }

  @Override // INodeFileAttributes
  public long getHeaderLong() {
    return header;
  }

  /** @return the blocks of the file. */
  @Override // BlockCollection
  public BlockInfo[] getBlocks() {
    return this.blocks;
  }

  /** @return blocks of the file corresponding to the snapshot. */
  public BlockInfo[] getBlocks(int snapshot) {
    if(snapshot == CURRENT_STATE_ID || getDiffs() == null) {
      return getBlocks();
    }
    FileDiff diff = getDiffs().getDiffById(snapshot);
    BlockInfo[] snapshotBlocks = diff == null ? getBlocks() : diff.getBlocks();
    if (snapshotBlocks != null) {
      return snapshotBlocks;
    }
    // Blocks are not in the current snapshot
    // Find next snapshot with blocks present or return current file blocks
    snapshotBlocks = getDiffs().findLaterSnapshotBlocks(snapshot);
    return (snapshotBlocks == null) ? getBlocks() : snapshotBlocks;
  }

  /** Used during concat to update the BlockCollection for each block. */
  private void updateBlockCollection() {
    if (blocks != null) {
      for(BlockInfo b : blocks) {
        b.setBlockCollection(this);
      }
    }
  }

  /**
   * append array of blocks to this.blocks
   */
  void concatBlocks(INodeFile[] inodes) {
    int size = this.blocks.length;
    int totalAddedBlocks = 0;
    for(INodeFile f : inodes) {
      totalAddedBlocks += f.blocks.length;
    }

    BlockInfo[] newlist =
        new BlockInfo[size + totalAddedBlocks];
    System.arraycopy(this.blocks, 0, newlist, 0, size);

    for(INodeFile in: inodes) {
      System.arraycopy(in.blocks, 0, newlist, size, in.blocks.length);
      size += in.blocks.length;
    }

    setBlocks(newlist);
    updateBlockCollection();
  }

  /**
   * add a block to the block list
   */
  void addBlock(BlockInfo newblock) {
    if (this.blocks == null) {
      this.setBlocks(new BlockInfo[]{newblock});
    } else {
      int size = this.blocks.length;
      BlockInfo[] newlist = new BlockInfo[size + 1];
      System.arraycopy(this.blocks, 0, newlist, 0, size);
      newlist[size] = newblock;
      this.setBlocks(newlist);
    }
  }

  /** Set the blocks. */
  private void setBlocks(BlockInfo[] blocks) {
    this.blocks = blocks;
  }

  /** Clear all blocks of the file. */
  public void clearBlocks() {
    setBlocks(null);
  }

  @Override
  public void cleanSubtree(ReclaimContext reclaimContext,
      final int snapshot, int priorSnapshotId) {
    FileWithSnapshotFeature sf = getFileWithSnapshotFeature();
    if (sf != null) {
      // TODO: avoid calling getStoragePolicyID
      sf.cleanFile(reclaimContext, this, snapshot, priorSnapshotId,
          getStoragePolicyID());
    } else {
      if (snapshot == CURRENT_STATE_ID) {
        if (priorSnapshotId == NO_SNAPSHOT_ID) {
          // this only happens when deleting the current file and it is not
          // in any snapshot
          destroyAndCollectBlocks(reclaimContext);
        } else {
          FileUnderConstructionFeature uc = getFileUnderConstructionFeature();
          // when deleting the current file and it is in snapshot, we should
          // clean the 0-sized block if the file is UC
          if (uc != null) {
            uc.cleanZeroSizeBlock(this, reclaimContext.collectedBlocks);
            if (reclaimContext.removedUCFiles != null) {
              reclaimContext.removedUCFiles.add(getId());
            }
          }
        }
      }
    }
  }

  @Override
  public void destroyAndCollectBlocks(ReclaimContext reclaimContext) {
    // TODO pass in the storage policy
    reclaimContext.quotaDelta().add(computeQuotaUsage(reclaimContext.bsps,
        false));
    clearFile(reclaimContext);
    FileWithSnapshotFeature sf = getFileWithSnapshotFeature();
    if (sf != null) {
      sf.getDiffs().destroyAndCollectSnapshotBlocks(
          reclaimContext.collectedBlocks);
      sf.clearDiffs();
    }
    if (isUnderConstruction() && reclaimContext.removedUCFiles != null) {
      reclaimContext.removedUCFiles.add(getId());
    }
  }

  public void clearFile(ReclaimContext reclaimContext) {
    if (blocks != null && reclaimContext.collectedBlocks != null) {
      for (BlockInfo blk : blocks) {
        reclaimContext.collectedBlocks.addDeleteBlock(blk);
        blk.setBlockCollection(null);
      }
    }
    clearBlocks();
    if (getAclFeature() != null) {
      AclStorage.removeAclFeature(getAclFeature());
    }
    clear();
    reclaimContext.removedINodes.add(this);
  }

  @Override
  public String getName() {
    // Get the full path name of this inode.
    return getFullPathName();
  }

  // This is the only place that needs to use the BlockStoragePolicySuite to
  // derive the intended storage type usage for quota by storage type
  @Override
  public final QuotaCounts computeQuotaUsage(BlockStoragePolicySuite bsps,
      byte blockStoragePolicyId, boolean useCache, int lastSnapshotId) {
    final QuotaCounts counts = new QuotaCounts.Builder().nameSpace(1).build();

    final BlockStoragePolicy bsp = bsps.getPolicy(blockStoragePolicyId);
    FileWithSnapshotFeature sf = getFileWithSnapshotFeature();
    if (sf == null) {
      counts.add(storagespaceConsumed(bsp));
      return counts;
    }

    FileDiffList fileDiffList = sf.getDiffs();
    int last = fileDiffList.getLastSnapshotId();

    if (lastSnapshotId == Snapshot.CURRENT_STATE_ID
        || last == Snapshot.CURRENT_STATE_ID) {
      counts.add(storagespaceConsumed(bsp));
      return counts;
    }

    final long ssDeltaNoReplication;
    short replication;
    if (last < lastSnapshotId) {
      ssDeltaNoReplication = computeFileSize(true, false);
      replication = getFileReplication();
    } else {
      int sid = fileDiffList.getSnapshotById(lastSnapshotId);
      ssDeltaNoReplication = computeFileSize(sid);
      replication = getFileReplication(sid);
    }

    counts.addStorageSpace(ssDeltaNoReplication * replication);
    if (bsp != null) {
      List<StorageType> storageTypes = bsp.chooseStorageTypes(replication);
      for (StorageType t : storageTypes) {
        if (!t.supportTypeQuota()) {
          continue;
        }
        counts.addTypeSpace(t, ssDeltaNoReplication);
      }
    }
    return counts;
  }

  @Override
  public final ContentSummaryComputationContext computeContentSummary(
      final ContentSummaryComputationContext summary) {
    final ContentCounts counts = summary.getCounts();
    FileWithSnapshotFeature sf = getFileWithSnapshotFeature();
    final long fileLen;
    if (sf == null) {
      fileLen = computeFileSize();
      counts.addContent(Content.FILE, 1);
    } else {
      final FileDiffList diffs = sf.getDiffs();
      final int n = diffs.asList().size();
      counts.addContent(Content.FILE, n);
      if (n > 0 && sf.isCurrentFileDeleted()) {
        fileLen =  diffs.getLast().getFileSize();
      } else {
        fileLen = computeFileSize();
      }
    }
    counts.addContent(Content.LENGTH, fileLen);
    counts.addContent(Content.DISKSPACE, storagespaceConsumed(null)
        .getStorageSpace());

    if (getStoragePolicyID() != BLOCK_STORAGE_POLICY_ID_UNSPECIFIED){
      BlockStoragePolicy bsp = summary.getBlockStoragePolicySuite().
          getPolicy(getStoragePolicyID());
      List<StorageType> storageTypes = bsp.chooseStorageTypes(getFileReplication());
      for (StorageType t : storageTypes) {
        if (!t.supportTypeQuota()) {
          continue;
        }
        counts.addTypeSpace(t, fileLen);
      }
    }
    return summary;
  }

  /** The same as computeFileSize(null). */
  public final long computeFileSize() {
    return computeFileSize(CURRENT_STATE_ID);
  }

  /**
   * Compute file size of the current file if the given snapshot is null;
   * otherwise, get the file size from the given snapshot.
   */
  public final long computeFileSize(int snapshotId) {
    FileWithSnapshotFeature sf = this.getFileWithSnapshotFeature();
    if (snapshotId != CURRENT_STATE_ID && sf != null) {
      final FileDiff d = sf.getDiffs().getDiffById(snapshotId);
      if (d != null) {
        return d.getFileSize();
      }
    }
    return computeFileSize(true, false);
  }

  /**
   * Compute file size of the current file size
   * but not including the last block if it is under construction.
   */
  public final long computeFileSizeNotIncludingLastUcBlock() {
    return computeFileSize(false, false);
  }

  /**
   * Compute file size of the current file.
   *
   * @param includesLastUcBlock
   *          If the last block is under construction, should it be included?
   * @param usePreferredBlockSize4LastUcBlock
   *          If the last block is under construction, should we use actual
   *          block size or preferred block size?
   *          Note that usePreferredBlockSize4LastUcBlock is ignored
   *          if includesLastUcBlock == false.
   * @return file size
   */
  public final long computeFileSize(boolean includesLastUcBlock,
      boolean usePreferredBlockSize4LastUcBlock) {
    if (blocks == null || blocks.length == 0) {
      return 0;
    }
    final int last = blocks.length - 1;
    //check if the last block is BlockInfoUnderConstruction
    long size = blocks[last].getNumBytes();
    if (!blocks[last].isComplete()) {
       if (!includesLastUcBlock) {
         size = 0;
       } else if (usePreferredBlockSize4LastUcBlock) {
         size = getPreferredBlockSize();
       }
    }
    //sum other blocks
    for(int i = 0; i < last; i++) {
      size += blocks[i].getNumBytes();
    }
    return size;
  }

  /**
   * Compute size consumed by all blocks of the current file,
   * including blocks in its snapshots.
   * Use preferred block size for the last block if it is under construction.
   */
  public final QuotaCounts storagespaceConsumed(BlockStoragePolicy bsp) {
    QuotaCounts counts = new QuotaCounts.Builder().build();
    final Iterable<BlockInfo> blocks;
    FileWithSnapshotFeature sf = getFileWithSnapshotFeature();
    if (sf == null) {
      blocks = Arrays.asList(getBlocks());
    } else {
      // Collect all distinct blocks
      Set<BlockInfo> allBlocks = new HashSet<>(Arrays.asList(getBlocks()));
      List<FileDiff> diffs = sf.getDiffs().asList();
      for(FileDiff diff : diffs) {
        BlockInfo[] diffBlocks = diff.getBlocks();
        if (diffBlocks != null) {
          allBlocks.addAll(Arrays.asList(diffBlocks));
        }
      }
      blocks = allBlocks;
    }

    final short replication = getPreferredBlockReplication();
    for (BlockInfo b : blocks) {
      long blockSize = b.isComplete() ? b.getNumBytes() :
          getPreferredBlockSize();
      counts.addStorageSpace(blockSize * replication);
      if (bsp != null) {
        List<StorageType> types = bsp.chooseStorageTypes(replication);
        for (StorageType t : types) {
          if (t.supportTypeQuota()) {
            counts.addTypeSpace(t, blockSize);
          }
        }
      }
    }
    return counts;
  }

  /**
   * Return the penultimate allocated block for this file.
   */
  BlockInfo getPenultimateBlock() {
    if (blocks == null || blocks.length <= 1) {
      return null;
    }
    return blocks[blocks.length - 2];
  }

  @Override
  public BlockInfo getLastBlock() {
    return blocks == null || blocks.length == 0? null: blocks[blocks.length-1];
  }

  @Override
  public int numBlocks() {
    return blocks == null ? 0 : blocks.length;
  }

  @VisibleForTesting
  @Override
  public void dumpTreeRecursively(PrintWriter out, StringBuilder prefix,
      final int snapshotId) {
    super.dumpTreeRecursively(out, prefix, snapshotId);
    out.print(", fileSize=" + computeFileSize(snapshotId));
    // only compare the first block
    out.print(", blocks=");
    out.print(blocks == null || blocks.length == 0? null: blocks[0]);
    out.println();
  }

  /**
   * Remove full blocks at the end file up to newLength
   * @return sum of sizes of the remained blocks
   */
  public long collectBlocksBeyondMax(final long max,
      final BlocksMapUpdateInfo collectedBlocks) {
    final BlockInfo[] oldBlocks = getBlocks();
    if (oldBlocks == null) {
      return 0;
    }
    // find the minimum n such that the size of the first n blocks > max
    int n = 0;
    long size = 0;
    for(; n < oldBlocks.length && max > size; n++) {
      size += oldBlocks[n].getNumBytes();
    }
    if (n >= oldBlocks.length) {
      return size;
    }

    // starting from block n, the data is beyond max.
    // resize the array.
    truncateBlocksTo(n);

    // collect the blocks beyond max
    if (collectedBlocks != null) {
      for(; n < oldBlocks.length; n++) {
        collectedBlocks.addDeleteBlock(oldBlocks[n]);
      }
    }
    return size;
  }

  /**
   * compute the quota usage change for a truncate op
   * @param newLength the length for truncation
   **/
  void computeQuotaDeltaForTruncate(
      long newLength, BlockStoragePolicy bsps,
      QuotaCounts delta) {
    final BlockInfo[] blocks = getBlocks();
    if (blocks == null || blocks.length == 0) {
      return;
    }

    long size = 0;
    for (BlockInfo b : blocks) {
      size += b.getNumBytes();
    }

    BlockInfo[] sblocks = null;
    FileWithSnapshotFeature sf = getFileWithSnapshotFeature();
    if (sf != null) {
      FileDiff diff = sf.getDiffs().getLast();
      sblocks = diff != null ? diff.getBlocks() : null;
    }

    for (int i = blocks.length - 1; i >= 0 && size > newLength;
         size -= blocks[i].getNumBytes(), --i) {
      BlockInfo bi = blocks[i];
      long truncatedBytes;
      if (size - newLength < bi.getNumBytes()) {
        // Record a full block as the last block will be copied during
        // recovery
        truncatedBytes = bi.getNumBytes() - getPreferredBlockSize();
      } else {
        truncatedBytes = bi.getNumBytes();
      }

      // The block exist in snapshot, adding back the truncated bytes in the
      // existing files
      if (sblocks != null && i < sblocks.length && bi.equals(sblocks[i])) {
        truncatedBytes -= bi.getNumBytes();
      }

      delta.addStorageSpace(-truncatedBytes * getPreferredBlockReplication());
      if (bsps != null) {
        List<StorageType> types = bsps.chooseStorageTypes(
            getPreferredBlockReplication());
        for (StorageType t : types) {
          if (t.supportTypeQuota()) {
            delta.addTypeSpace(t, -truncatedBytes);
          }
        }
      }
    }
  }

  void truncateBlocksTo(int n) {
    final BlockInfo[] newBlocks;
    if (n == 0) {
      newBlocks = BlockInfo.EMPTY_ARRAY;
    } else {
      newBlocks = new BlockInfo[n];
      System.arraycopy(getBlocks(), 0, newBlocks, 0, n);
    }
    // set new blocks
    setBlocks(newBlocks);
  }

  public void collectBlocksBeyondSnapshot(BlockInfo[] snapshotBlocks,
                                          BlocksMapUpdateInfo collectedBlocks) {
    BlockInfo[] oldBlocks = getBlocks();
    if(snapshotBlocks == null || oldBlocks == null)
      return;
    // Skip blocks in common between the file and the snapshot
    int n = 0;
    while(n < oldBlocks.length && n < snapshotBlocks.length &&
          oldBlocks[n] == snapshotBlocks[n]) {
      n++;
    }
    truncateBlocksTo(n);
    // Collect the remaining blocks of the file
    while(n < oldBlocks.length) {
      collectedBlocks.addDeleteBlock(oldBlocks[n++]);
    }
  }

  /** Exclude blocks collected for deletion that belong to a snapshot. */
  void excludeSnapshotBlocks(int snapshotId,
                             BlocksMapUpdateInfo collectedBlocks) {
    if(collectedBlocks == null || collectedBlocks.getToDeleteList().isEmpty())
      return;
    FileWithSnapshotFeature sf = getFileWithSnapshotFeature();
    if(sf == null)
      return;
    BlockInfo[] snapshotBlocks =
        getDiffs().findEarlierSnapshotBlocks(snapshotId);
    if(snapshotBlocks == null)
      return;
    List<BlockInfo> toDelete = collectedBlocks.getToDeleteList();
    for(BlockInfo blk : snapshotBlocks) {
      if(toDelete.contains(blk))
        collectedBlocks.removeDeleteBlock(blk);
    }
  }

  /**
   * @return true if the block is contained in a snapshot or false otherwise.
   */
  boolean isBlockInLatestSnapshot(BlockInfo block) {
    FileWithSnapshotFeature sf = this.getFileWithSnapshotFeature();
    if (sf == null || sf.getDiffs() == null) {
      return false;
    }
    BlockInfo[] snapshotBlocks = getDiffs()
        .findEarlierSnapshotBlocks(getDiffs().getLastSnapshotId());
    return snapshotBlocks != null &&
        Arrays.asList(snapshotBlocks).contains(block);
  }
}


text:
package drinkwater.test.jndi;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import java.util.Hashtable;

public class MockInitialContextFactory implements InitialContextFactory {

    private static final ThreadLocal<Context> currentContext = new ThreadLocal<Context>();

    @Override
    public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
        return currentContext.get();
    }

    public static void setCurrentContext(Context context) {
        currentContext.set(context);
    }

    public static void clearCurrentContext() {
        currentContext.remove();
    }

}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;

namespace CslaSample.Business
{

    /// <summary>
    /// FolderEdit (editable child object).<br/>
    /// This is a generated base class of <see cref="FolderEdit"/> business object.
    /// </summary>
    /// <remarks>
    /// This class is an item of <see cref="FolderEditCollection"/> collection.
    /// </remarks>
    [Serializable]
    public partial class FolderEdit : BusinessBase<FolderEdit>
    {

        #region Static Fields

        private static int _lastID;

        #endregion

        #region Business Properties

        /// <summary>
        /// Maintains metadata about <see cref="FolderId"/> property.
        /// </summary>
        [NotUndoable]
        public static readonly PropertyInfo<int> FolderIdProperty = RegisterProperty<int>(p => p.FolderId, "Folder Id");
        /// <summary>
        /// Gets the Folder Id.
        /// </summary>
        /// <value>The Folder Id.</value>
        public int FolderId
        {
            get { return GetProperty(FolderIdProperty); }
        }

        /// <summary>
        /// Maintains metadata about <see cref="FolderName"/> property.
        /// </summary>
        public static readonly PropertyInfo<string> FolderNameProperty = RegisterProperty<string>(p => p.FolderName, "Folder Name");
        /// <summary>
        /// Gets or sets the Folder Name.
        /// </summary>
        /// <value>The Folder Name.</value>
        public string FolderName
        {
            get { return GetProperty(FolderNameProperty); }
            set { SetProperty(FolderNameProperty, value); }
        }

        /// <summary>
        /// Maintains metadata about <see cref="DocumentCount"/> property.
        /// </summary>
        [NotUndoable]
        public static readonly PropertyInfo<int> DocumentCountProperty = RegisterProperty<int>(p => p.DocumentCount, "Document Count");
        /// <summary>
        /// Gets the Document Count.
        /// </summary>
        /// <value>The Document Count.</value>
        public int DocumentCount
        {
            get { return GetProperty(DocumentCountProperty); }
        }

        /// <summary>
        /// Maintains metadata about <see cref="CreateDate"/> property.
        /// </summary>
        public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date");
        /// <summary>
        /// Gets the Create Date.
        /// </summary>
        /// <value>The Create Date.</value>
        public SmartDate CreateDate
        {
            get { return GetProperty(CreateDateProperty); }
        }

        /// <summary>
        /// Maintains metadata about <see cref="ChangeDate"/> property.
        /// </summary>
        public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
        /// <summary>
        /// Gets the Change Date.
        /// </summary>
        /// <value>The Change Date.</value>
        public SmartDate ChangeDate
        {
            get { return GetProperty(ChangeDateProperty); }
        }

        #endregion

        #region Factory Methods

        /// <summary>
        /// Factory method. Creates a new <see cref="FolderEdit"/> object.
        /// </summary>
        /// <returns>A reference to the created <see cref="FolderEdit"/> object.</returns>
        internal static FolderEdit NewFolderEdit()
        {
            return DataPortal.CreateChild<FolderEdit>();
        }

        /// <summary>
        /// Factory method. Loads a <see cref="FolderEdit"/> object from the given SafeDataReader.
        /// </summary>
        /// <param name="dr">The SafeDataReader to use.</param>
        /// <returns>A reference to the fetched <see cref="FolderEdit"/> object.</returns>
        internal static FolderEdit GetFolderEdit(SafeDataReader dr)
        {
            FolderEdit obj = new FolderEdit();
            // show the framework that this is a child object
            obj.MarkAsChild();
            obj.Fetch(dr);
            obj.MarkOld();
            // check all object rules and property rules
            obj.BusinessRules.CheckRules();
            return obj;
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="FolderEdit"/> class.
        /// </summary>
        /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
        [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
        public FolderEdit()
        {
            // Use factory methods and do not use direct creation.

            // show the framework that this is a child object
            MarkAsChild();
        }

        #endregion

        #region Business Rules and Property Authorization

        /// <summary>
        /// Override this method in your business class to be notified when you need to set up shared business rules.
        /// </summary>
        /// <remarks>
        /// This method is automatically called by CSLA.NET when your object should associate
        /// per-type validation rules with its properties.
        /// </remarks>
        protected override void AddBusinessRules()
        {
            base.AddBusinessRules();

            // Property Business Rules

            // FolderName
            BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(FolderNameProperty));
            BusinessRules.AddRule(new CslaContrib.Rules.CommonRules.CollapseSpace(FolderNameProperty) { Priority = 1 });
            BusinessRules.AddRule(new Csla.Rules.CommonRules.MaxLength(FolderNameProperty, 30) { Priority = 2 });
            BusinessRules.AddRule(new CslaContrib.Rules.CommonRules.NoDuplicates<FolderEditCollection,FolderEdit>(FolderNameProperty) { Priority = 3 });

            AddBusinessRulesExtend();
        }

        /// <summary>
        /// Allows the set up of custom shared business rules.
        /// </summary>
        partial void AddBusinessRulesExtend();

        #endregion

        #region Data Access

        /// <summary>
        /// Loads default values for the <see cref="FolderEdit"/> object properties.
        /// </summary>
        [RunLocal]
        protected override void Child_Create()
        {
            LoadProperty(FolderIdProperty, System.Threading.Interlocked.Decrement(ref _lastID));
            LoadProperty(DocumentCountProperty, 0);
            LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now));
            LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty));
            var args = new DataPortalHookArgs();
            OnCreate(args);
            base.Child_Create();
        }

        /// <summary>
        /// Loads a <see cref="FolderEdit"/> object from the given SafeDataReader.
        /// </summary>
        /// <param name="dr">The SafeDataReader to use.</param>
        private void Fetch(SafeDataReader dr)
        {
            // Value properties
            LoadProperty(FolderIdProperty, dr.GetInt32("FolderId"));
            LoadProperty(FolderNameProperty, dr.GetString("FolderName"));
            LoadProperty(DocumentCountProperty, dr.GetInt32("DocumentCount"));
            LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true));
            LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true));
            var args = new DataPortalHookArgs(dr);
            OnFetchRead(args);
        }

        /// <summary>
        /// Inserts a new <see cref="FolderEdit"/> object in the database.
        /// </summary>
        private void Child_Insert()
        {
            SimpleAuditTrail();
            using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.CslaSampleConnection, false))
            {
                using (var cmd = new SqlCommand("AddFolderEdit", ctx.Connection))
                {
                    cmd.Transaction = ctx.Transaction;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@FolderId", ReadProperty(FolderIdProperty)).Direction = ParameterDirection.Output;
                    cmd.Parameters.AddWithValue("@FolderName", ReadProperty(FolderNameProperty)).DbType = DbType.String;
                    cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2;
                    cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
                    var args = new DataPortalHookArgs(cmd);
                    OnInsertPre(args);
                    cmd.ExecuteNonQuery();
                    OnInsertPost(args);
                    LoadProperty(FolderIdProperty, (int) cmd.Parameters["@FolderId"].Value);
                }
            }
        }

        /// <summary>
        /// Updates in the database all changes made to the <see cref="FolderEdit"/> object.
        /// </summary>
        private void Child_Update()
        {
            if (!IsDirty)
                return;

            SimpleAuditTrail();
            using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.CslaSampleConnection, false))
            {
                using (var cmd = new SqlCommand("UpdateFolderEdit", ctx.Connection))
                {
                    cmd.Transaction = ctx.Transaction;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@FolderId", ReadProperty(FolderIdProperty)).DbType = DbType.Int32;
                    cmd.Parameters.AddWithValue("@FolderName", ReadProperty(FolderNameProperty)).DbType = DbType.String;
                    cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2;
                    var args = new DataPortalHookArgs(cmd);
                    OnUpdatePre(args);
                    cmd.ExecuteNonQuery();
                    OnUpdatePost(args);
                }
            }
        }

        private void SimpleAuditTrail()
        {
            LoadProperty(ChangeDateProperty, DateTime.Now);
            if (IsNew)
            {
                LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty));
            }
        }

        /// <summary>
        /// Self deletes the <see cref="FolderEdit"/> object from database.
        /// </summary>
        private void Child_DeleteSelf()
        {
            // audit the object, just in case soft delete is used on this object
            SimpleAuditTrail();
            using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.CslaSampleConnection, false))
            {
                using (var cmd = new SqlCommand("DeleteFolderEdit", ctx.Connection))
                {
                    cmd.Transaction = ctx.Transaction;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@FolderId", ReadProperty(FolderIdProperty)).DbType = DbType.Int32;
                    var args = new DataPortalHookArgs(cmd);
                    OnDeletePre(args);
                    cmd.ExecuteNonQuery();
                    OnDeletePost(args);
                }
            }
        }

        #endregion

        #region DataPortal Hooks

        /// <summary>
        /// Occurs after setting all defaults for object creation.
        /// </summary>
        partial void OnCreate(DataPortalHookArgs args);

        /// <summary>
        /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
        /// </summary>
        partial void OnDeletePre(DataPortalHookArgs args);

        /// <summary>
        /// Occurs in DataPortal_Delete, after the delete operation, before Commit().
        /// </summary>
        partial void OnDeletePost(DataPortalHookArgs args);

        /// <summary>
        /// Occurs after setting query parameters and before the fetch operation.
        /// </summary>
        partial void OnFetchPre(DataPortalHookArgs args);

        /// <summary>
        /// Occurs after the fetch operation (object or collection is fully loaded and set up).
        /// </summary>
        partial void OnFetchPost(DataPortalHookArgs args);

        /// <summary>
        /// Occurs after the low level fetch operation, before the data reader is destroyed.
        /// </summary>
        partial void OnFetchRead(DataPortalHookArgs args);

        /// <summary>
        /// Occurs after setting query parameters and before the update operation.
        /// </summary>
        partial void OnUpdatePre(DataPortalHookArgs args);

        /// <summary>
        /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
        /// </summary>
        partial void OnUpdatePost(DataPortalHookArgs args);

        /// <summary>
        /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
        /// </summary>
        partial void OnInsertPre(DataPortalHookArgs args);

        /// <summary>
        /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
        /// </summary>
        partial void OnInsertPost(DataPortalHookArgs args);

        #endregion

    }
}


text:
<!DOCTYPE html>

  <meta charset=utf-8 />
  <title>guitypist</title>

  <link rel="stylesheet" type="text/css" media="screen" href="client/css/index.css" />

Guitypist

  <textarea class="output" spellcheck="false"></textarea>
  <textarea class="debug"></textarea>


text:
using GraphExec.Security;
using System.Collections.Generic;

namespace GraphExec.Tests.User
{
    public sealed class LoginUser : IUser
    {
        public LoginUser()
        {
            this.Permissions = new List<string>();
        }

        public string Name { get; set; }

        public string Email { get; set; }

        public List<string> Permissions { get; set; }
    }
}


text:
package org.earthtime.ratioDataModels.detritalUraniumAndThoriumModels;

import com.thoughtworks.xstream.XStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.earthtime.UPb_Redux.ReduxConstants;
import org.earthtime.UPb_Redux.utilities.ETSerializer;
import org.earthtime.reduxLabData.ReduxLabDataList;
import org.earthtime.UPb_Redux.valueModels.ValueModel;
import org.earthtime.UPb_Redux.valueModels.ValueModelXMLConverter;
import org.earthtime.XMLExceptions.BadOrMissingXMLSchemaException;
import org.earthtime.dataDictionaries.DetritalUThRatiosEnum;
import org.earthtime.exceptions.ETException;
import org.earthtime.ratioDataModels.AbstractRatiosDataModel;
import org.earthtime.utilities.DateHelpers;

/**
 *
 * @author samuelbowring
 */
public class DetritalUraniumAndThoriumModel extends AbstractRatiosDataModel {

    // class variables
    private static final long serialVersionUID = -1767799823303336291L;
    private static final String classNameAliasForXML = "DetritalUraniumAndThoriumModel";
    private static Map<String, AbstractRatiosDataModel> modelInstances
            = new HashMap<>();

    private static final ValueModel[] myRatios = new ValueModel[3];
    private static final Map<String, BigDecimal> correlations = new HashMap<>();

    static {
        myRatios[0] = new ValueModel(//
                "ar232Th_238U", //
                new BigDecimal(1.2), //
                "ABS", //
                new BigDecimal(0.3), BigDecimal.ZERO);
        myRatios[1] = new ValueModel(//
                "ar230Th_238U", //
                new BigDecimal(1.0), //
                "ABS", //
                new BigDecimal(0.25), BigDecimal.ZERO);
        myRatios[2] = new ValueModel(//
                "ar234U_238U", //
                new BigDecimal(1.0), //
                "ABS", //
                new BigDecimal(0.25), BigDecimal.ZERO);

        correlations.put("rhoAr232Th_238U__ar230Th_238U", new BigDecimal(0.0));
        correlations.put("rhoAr232Th_238U__ar234U_238U", new BigDecimal(0.0));
        correlations.put("rhoAr230Th_238U__ar234U_238U", new BigDecimal(0.5));
    }
    private static final AbstractRatiosDataModel noneModel
            = new DetritalUraniumAndThoriumModel( //
                    ReduxConstants.NONE, //
                    1, 0, //
                    "No Lab",//
                    "2000-01-01",//
                    "Placeholder model",//
                    "Placeholder model");
    private static final AbstractRatiosDataModel SecularEquilibriumDetritalUraniumThoriumInitialModel
            = createInstance(
                    "Secular Equilibrium ThU=3.8",
                    1, 0,//
                    "public domain",//
                    "2017-01-01",//
                    "Noah McLean",//
                    "",//
                    myRatios, //
                    correlations);

    private boolean initial = true;

    /**
     *
     *
     * @param modelName
     * @param versionNumber
     * @param minorVersionNumber the value of minorVersionNumber
     * @param labName the value of labName
     * @param dateCertified the value of dateCertified
     * @param reference
     * @param comment
     */
    private DetritalUraniumAndThoriumModel(//
            String modelName,
            int versionNumber,
            int minorVersionNumber,
            String labName,
            String dateCertified,
            String reference,
            String comment) {

        super(modelName, versionNumber, minorVersionNumber, labName, dateCertified, reference, comment);

        initializeNewRatiosAndRhos(false);
    }

    /**
     *
     * @param updateOnly
     */
    @Override
    public final void initializeNewRatiosAndRhos(boolean updateOnly) {
        // DetritalUraniumAndThoriumModel has a defined set of ratios
        ArrayList<ValueModel> holdRatios = new ArrayList<>();
        for (DetritalUThRatiosEnum ratio : DetritalUThRatiosEnum.values()) {
            holdRatios.add( //
                    new ValueModel(ratio.getName(),
                            BigDecimal.ZERO,
                            "ABS",
                            BigDecimal.ZERO,
                            BigDecimal.ZERO));
        }

        ratios = holdRatios.toArray(new ValueModel[holdRatios.size()]);

        Arrays.sort(ratios, new DataValueModelNameComparator());

        buildRhosMap();

    }

    /**
     *
     * @param modelName
     * @param versionNumber
     * @param minorVersionNumber
     * @return
     */
    public static AbstractRatiosDataModel getInstance(String modelName, int versionNumber, int minorVersionNumber) {
        return modelInstances.get(makeNameAndVersion(modelName, versionNumber, minorVersionNumber));
    }

    /**
     *
     *
     * @param modelName
     * @param versionNumber
     * @param minorVersionNumber
     * @param labName
     * @param reference
     * @param dateCertified
     * @param comment
     * @param ratios
     * @param rhos
     * @return
     */
    public static AbstractRatiosDataModel createInstance(//
            String modelName, //
            int versionNumber, //
            int minorVersionNumber, //
            String labName,//
            String dateCertified,//
            String reference, //
            String comment, //
            ValueModel[] ratios, //
            Map<String, BigDecimal> rhos) {

        AbstractRatiosDataModel myModel = modelInstances.get(makeNameAndVersion(modelName, versionNumber, minorVersionNumber));

        if (myModel == null) {
            myModel = new DetritalUraniumAndThoriumModel(//
                    modelName, //
                    versionNumber, minorVersionNumber,//
                    labName, //
                    dateCertified, //
                    reference, //
                    comment);

            myModel.initializeModel(ratios, rhos, null);

            modelInstances.put(makeNameAndVersion(modelName, versionNumber, minorVersionNumber), myModel);
        }

        return myModel;
    }

    /**
     *
     * @return
     */
    public static AbstractRatiosDataModel createNewInstance() {

        AbstractRatiosDataModel myModel = new DetritalUraniumAndThoriumModel(//
                "New Detrital Thorium Uranium Model", //
                1, 0, //
                "No Lab", //
                DateHelpers.defaultEarthTimeDateString(), //
                "No reference", //
                "No comment");

        return myModel;
    }

    /**
     *
     * @return
     */
    public static AbstractRatiosDataModel getNoneInstance() {
        // guarantee final model
        modelInstances.put(noneModel.getNameAndVersion(), noneModel);
        noneModel.setImmutable(true);
        return noneModel;
    }

    /**
     *
     * @return
     */
    public static AbstractRatiosDataModel getSecularEquilibriumDetritalUraniumThoriumInitialModelInstance() {
        // guarantee final model
        modelInstances.put(SecularEquilibriumDetritalUraniumThoriumInitialModel.getNameAndVersion(), SecularEquilibriumDetritalUraniumThoriumInitialModel);
        SecularEquilibriumDetritalUraniumThoriumInitialModel.setImmutable(true);
        return SecularEquilibriumDetritalUraniumThoriumInitialModel;
    }

    /**
     *
     * @return
     */
    @Override
    public AbstractRatiosDataModel cloneModel() {

        AbstractRatiosDataModel myModel = new DetritalUraniumAndThoriumModel(//
                this.modelName, //
                this.versionNumber, this.minorVersionNumber,//
                this.labName, //
                this.dateCertified, //
                this.reference, //
                this.comment);

        myModel.initializeModel(cloneData(), cloneRhosVarUnct(), null);
        ((DetritalUraniumAndThoriumModel) myModel).setInitial(initial);

        return myModel;
    }

    /**
     *
     * @return
     */
    public static ArrayList<AbstractRatiosDataModel> getArrayListOfModels() {

        // guarantee final models
        getNoneInstance();
        getSecularEquilibriumDetritalUraniumThoriumInitialModelInstance();

        //loadModelsFromResources(modelInstances);
        ArrayList<AbstractRatiosDataModel> arrayListOfModels = new ReduxLabDataList<>("Detrital Uranium And Thorium Model");
        Iterator<String> modelsKeyInterator = modelInstances.keySet().iterator();
        while (modelsKeyInterator.hasNext()) {
            arrayListOfModels.add(modelInstances.get(modelsKeyInterator.next()));
        }

        Collections.sort(arrayListOfModels);

        return arrayListOfModels;
    }

    /**
     *
     */
    @Override
    public void removeSelf() {
        modelInstances.remove(this.getReduxLabDataElementName());
    }

    // used for deserialization
    /**
     *
     * @return
     */
    protected Object readResolve() {

        if (!modelInstances.containsKey(makeNameAndVersion(modelName, versionNumber, minorVersionNumber))) {

            this.initializeModel();
            modelInstances.put(makeNameAndVersion(modelName, versionNumber, minorVersionNumber), this);
        }

        return modelInstances.get(makeNameAndVersion(modelName, versionNumber, minorVersionNumber));
    }

    @Override
    protected void customizeXstream(XStream xstream) {
        xstream.registerConverter(new ValueModelXMLConverter());
        xstream.registerConverter(new DetritalUThModelXMLConverter());

        xstream.alias("DetritalUraniumAndThoriumModel", DetritalUraniumAndThoriumModel.class);
        xstream.alias("ValueModel", ValueModel.class);

        setClassXMLSchemaURL("URI_DetritalUraniumAndThoriumModelXMLSchema");
    }

    @Override
    public String getClassNameAliasForXML() {
        return classNameAliasForXML;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        AbstractRatiosDataModel pbBlankModelETs = DetritalUraniumAndThoriumModel.getSecularEquilibriumDetritalUraniumThoriumInitialModelInstance();
        try {
            ETSerializer.SerializeObjectToFile(pbBlankModelETs, "DetritalUraniumAndThoriumModelTEST.ser");
        } catch (ETException eTException) {
        }
        AbstractRatiosDataModel detritalUraniumAndThoriumModel = (AbstractRatiosDataModel) ETSerializer.GetSerializedObjectFromFile("DetritalUraniumAndThoriumModelTEST.ser");

        String testFileName = "DetritalUraniumAndThoriumModelTEST.xml";

        detritalUraniumAndThoriumModel.serializeXMLObject(testFileName);
        try {
            detritalUraniumAndThoriumModel.readXMLObject(testFileName, true);
        } catch (FileNotFoundException fileNotFoundException) {
        } catch (ETException eTException) {
        } catch (BadOrMissingXMLSchemaException badOrMissingXMLSchemaException) {
        }

    }
//    private void readObject(ObjectInputStream stream) throws IOException,
//            ClassNotFoundException {
//        stream.defaultReadObject();
//
//        ObjectStreamClass myObject = ObjectStreamClass.lookup(
//                Class.forName(DetritalUraniumAndThoriumModel.class.getCanonicalName()));
//        long theSUID = myObject.getSerialVersionUID();
//
//        System.out.println("Customized De-serialization of DetritalUraniumAndThoriumModel "
//                + theSUID);
//    }

    /**
     * @return the initial
     */
    public boolean isInitial() {
        return initial;
    }

    /**
     * @param initial the initial to set
     */
    public void setInitial(boolean initial) {
        this.initial = initial;
    }
}


text:
namespace paint_preview {

namespace {

const char kTestFeatureDir[] = "test_feature";

class RejectionPaintPreviewPolicy : public PaintPreviewPolicy {
 public:
  RejectionPaintPreviewPolicy() = default;
  ~RejectionPaintPreviewPolicy() override = default;

  RejectionPaintPreviewPolicy(const RejectionPaintPreviewPolicy&) = delete;
  RejectionPaintPreviewPolicy& operator=(const RejectionPaintPreviewPolicy&) =
      delete;

  bool SupportedForContents(content::WebContents* web_contents) override {
    return false;
  }
};

// Builds a PaintPreviewBaseService associated with |key| which will never
// permit paint previews.
std::unique_ptr<KeyedService> BuildServiceWithRejectionPolicy(
    SimpleFactoryKey* key) {
  return std::make_unique<PaintPreviewBaseService>(
      key->GetPath(), kTestFeatureDir,
      std::make_unique<RejectionPaintPreviewPolicy>(), key->IsOffTheRecord());
}

base::FilePath CreateDir(scoped_refptr<FileManager> manager,
                         const DirectoryKey& key) {
  base::FilePath out;
  base::RunLoop loop;
  manager->GetTaskRunner()->PostTaskAndReplyWithResult(
      FROM_HERE,
      base::BindOnce(&FileManager::CreateOrGetDirectory, manager, key, false),
      base::BindOnce(
          [](base::OnceClosure quit, base::FilePath* out,
             const base::Optional<base::FilePath>& path) {
            EXPECT_TRUE(path.has_value());
            EXPECT_FALSE(path->empty());
            *out = path.value();
            std::move(quit).Run();
          },
          loop.QuitClosure(), &out));
  loop.Run();
  return out;
}

}  // namespace

class MockPaintPreviewRecorder : public mojom::PaintPreviewRecorder {
 public:
  MockPaintPreviewRecorder() = default;
  ~MockPaintPreviewRecorder() override = default;

  void CapturePaintPreview(
      mojom::PaintPreviewCaptureParamsPtr params,
      mojom::PaintPreviewRecorder::CapturePaintPreviewCallback callback)
      override {
    {
      base::ScopedAllowBlockingForTesting scope;
      CheckParams(std::move(params));
      std::move(callback).Run(status_, std::move(response_));
    }
  }

  void SetExpectedParams(mojom::PaintPreviewCaptureParamsPtr params) {
    expected_params_ = std::move(params);
  }

  void SetResponse(mojom::PaintPreviewStatus status,
                   mojom::PaintPreviewCaptureResponsePtr response) {
    status_ = status;
    response_ = std::move(response);
  }

  void BindRequest(mojo::ScopedInterfaceEndpointHandle handle) {
    binding_.Bind(mojo::PendingAssociatedReceiver<mojom::PaintPreviewRecorder>(
        std::move(handle)));
  }

  MockPaintPreviewRecorder(const MockPaintPreviewRecorder&) = delete;
  MockPaintPreviewRecorder& operator=(const MockPaintPreviewRecorder&) = delete;

 private:
  void CheckParams(mojom::PaintPreviewCaptureParamsPtr input_params) {
    // Ignore GUID and File as this is internal information not known by the
    // Keyed Service API.
    EXPECT_EQ(input_params->clip_rect, expected_params_->clip_rect);
    EXPECT_EQ(input_params->is_main_frame, expected_params_->is_main_frame);
  }

  mojom::PaintPreviewCaptureParamsPtr expected_params_;
  mojom::PaintPreviewStatus status_;
  mojom::PaintPreviewCaptureResponsePtr response_;
  mojo::AssociatedReceiver<mojom::PaintPreviewRecorder> binding_{this};
};

class PaintPreviewBaseServiceTest : public content::RenderViewHostTestHarness {
 public:
  PaintPreviewBaseServiceTest() = default;
  ~PaintPreviewBaseServiceTest() override = default;

  PaintPreviewBaseServiceTest(const PaintPreviewBaseService&) = delete;
  PaintPreviewBaseServiceTest& operator=(const PaintPreviewBaseService&) =
      delete;

 protected:
  void SetUp() override {
    content::RenderViewHostTestHarness::SetUp();
    key_ = std::make_unique<SimpleFactoryKey>(
        browser_context()->GetPath(), browser_context()->IsOffTheRecord());
    PaintPreviewBaseServiceTestFactory::GetInstance()->SetTestingFactory(
        key_.get(),
        base::BindRepeating(&PaintPreviewBaseServiceTestFactory::Build));

    rejection_policy_key_ = std::make_unique<SimpleFactoryKey>(
        browser_context()->GetPath(), browser_context()->IsOffTheRecord());
    PaintPreviewBaseServiceTestFactory::GetInstance()->SetTestingFactory(
        rejection_policy_key_.get(),
        base::BindRepeating(&BuildServiceWithRejectionPolicy));
  }

  void OverrideInterface(MockPaintPreviewRecorder* service) {
    blink::AssociatedInterfaceProvider* remote_interfaces =
        main_rfh()->GetRemoteAssociatedInterfaces();
    remote_interfaces->OverrideBinderForTesting(
        mojom::PaintPreviewRecorder::Name_,
        base::BindRepeating(&MockPaintPreviewRecorder::BindRequest,
                            base::Unretained(service)));
  }

  PaintPreviewBaseService* GetService() {
    return PaintPreviewBaseServiceTestFactory::GetForKey(key_.get());
  }

  PaintPreviewBaseService* GetServiceWithRejectionPolicy() {
    return PaintPreviewBaseServiceTestFactory::GetForKey(
        rejection_policy_key_.get());
  }

 private:
  std::unique_ptr<SimpleFactoryKey> key_ = nullptr;
  std::unique_ptr<SimpleFactoryKey> rejection_policy_key_ = nullptr;
};

TEST_F(PaintPreviewBaseServiceTest, CaptureMainFrame) {
  MockPaintPreviewRecorder recorder;
  auto params = mojom::PaintPreviewCaptureParams::New();
  params->clip_rect = gfx::Rect(0, 0, 0, 0);
  params->is_main_frame = true;
  params->max_capture_size = 50;
  recorder.SetExpectedParams(std::move(params));
  auto response = mojom::PaintPreviewCaptureResponse::New();
  response->embedding_token = base::nullopt;
  recorder.SetResponse(mojom::PaintPreviewStatus::kOk, std::move(response));
  OverrideInterface(&recorder);

  auto* service = GetService();
  EXPECT_FALSE(service->IsOffTheRecord());
  auto manager = service->GetFileManager();
  base::FilePath path = CreateDir(
      manager, manager->CreateKey(web_contents()->GetLastCommittedURL()));

  base::RunLoop loop;
  service->CapturePaintPreview(
      web_contents(), path, gfx::Rect(0, 0, 0, 0), 50,
      base::BindOnce(
          [](base::OnceClosure quit_closure,
             PaintPreviewBaseService::CaptureStatus expected_status,
             const base::FilePath& expected_path,
             PaintPreviewBaseService::CaptureStatus status,
             std::unique_ptr<PaintPreviewProto> proto) {
            EXPECT_EQ(status, expected_status);
            EXPECT_TRUE(proto->has_root_frame());
            EXPECT_EQ(proto->subframes_size(), 0);
            EXPECT_TRUE(proto->root_frame().is_main_frame());
            auto token = base::UnguessableToken::Deserialize(
                proto->root_frame().embedding_token_high(),
                proto->root_frame().embedding_token_low());
#if defined(OS_WIN)
            base::FilePath path = base::FilePath(
                base::UTF8ToUTF16(proto->root_frame().file_path()));
            base::FilePath name(
                base::UTF8ToUTF16(base::StrCat({token.ToString(), ".skp"})));
#else
            base::FilePath path =
                base::FilePath(proto->root_frame().file_path());
            base::FilePath name(base::StrCat({token.ToString(), ".skp"}));
#endif
            EXPECT_EQ(path.DirName(), expected_path);
            LOG(ERROR) << expected_path;
            EXPECT_EQ(path.BaseName(), name);
            std::move(quit_closure).Run();
          },
          loop.QuitClosure(), PaintPreviewBaseService::CaptureStatus::kOk,
          path));
  loop.Run();
}

TEST_F(PaintPreviewBaseServiceTest, CaptureFailed) {
  MockPaintPreviewRecorder recorder;
  auto params = mojom::PaintPreviewCaptureParams::New();
  params->clip_rect = gfx::Rect(0, 0, 0, 0);
  params->is_main_frame = true;
  params->max_capture_size = 0;
  recorder.SetExpectedParams(std::move(params));
  auto response = mojom::PaintPreviewCaptureResponse::New();
  response->embedding_token = base::nullopt;
  recorder.SetResponse(mojom::PaintPreviewStatus::kFailed, std::move(response));
  OverrideInterface(&recorder);

  auto* service = GetService();
  EXPECT_FALSE(service->IsOffTheRecord());
  auto manager = service->GetFileManager();
  base::FilePath path = CreateDir(
      manager, manager->CreateKey(web_contents()->GetLastCommittedURL()));

  base::RunLoop loop;
  service->CapturePaintPreview(
      web_contents(), path, gfx::Rect(0, 0, 0, 0), 0,
      base::BindOnce(
          [](base::OnceClosure quit_closure,
             PaintPreviewBaseService::CaptureStatus expected_status,
             PaintPreviewBaseService::CaptureStatus status,
             std::unique_ptr<PaintPreviewProto> proto) {
            EXPECT_EQ(status, expected_status);
            EXPECT_EQ(proto, nullptr);
            std::move(quit_closure).Run();
          },
          loop.QuitClosure(),
          PaintPreviewBaseService::CaptureStatus::kCaptureFailed));
  loop.Run();
}

TEST_F(PaintPreviewBaseServiceTest, CaptureDisallowed) {
  MockPaintPreviewRecorder recorder;
  auto params = mojom::PaintPreviewCaptureParams::New();
  params->clip_rect = gfx::Rect(0, 0, 0, 0);
  params->is_main_frame = true;
  params->max_capture_size = 0;
  recorder.SetExpectedParams(std::move(params));
  auto response = mojom::PaintPreviewCaptureResponse::New();
  response->embedding_token = base::nullopt;
  recorder.SetResponse(mojom::PaintPreviewStatus::kFailed, std::move(response));
  OverrideInterface(&recorder);

  auto* service = GetServiceWithRejectionPolicy();
  EXPECT_FALSE(service->IsOffTheRecord());
  auto manager = service->GetFileManager();
  base::FilePath path = CreateDir(
      manager, manager->CreateKey(web_contents()->GetLastCommittedURL()));

  base::RunLoop loop;
  service->CapturePaintPreview(
      web_contents(), path, gfx::Rect(0, 0, 0, 0), 0,
      base::BindOnce(
          [](base::OnceClosure quit_closure,
             PaintPreviewBaseService::CaptureStatus expected_status,
             PaintPreviewBaseService::CaptureStatus status,
             std::unique_ptr<PaintPreviewProto> proto) {
            EXPECT_EQ(status, expected_status);
            EXPECT_EQ(proto, nullptr);
            std::move(quit_closure).Run();
          },
          loop.QuitClosure(),
          PaintPreviewBaseService::CaptureStatus::kContentUnsupported));
  loop.Run();
}

}  // namespace paint_preview


text:
module.exports = {
  parser: 'babel-eslint',
  extends: ['eslint:recommended'],
  plugins: ['prettier', 'jest'],
  env: {
    node: true,
    es6: true,
    jasmine: true,
    'jest/globals': true
  },
  parserOptions: {
    sourceType: 'module'
  },
  rules: {
    /**
 * Strict mode
 */
    'prettier/prettier': [
      'error',
      {
        singleQuote: true
      }
    ],
    'no-shadow': 2, // http://eslint.org/docs/rules/no-shadow
    'no-shadow-restricted-names': 2, // http://eslint.org/docs/rules/no-shadow-restricted-names
    'no-unused-vars': [
      2,
      {
        // http://eslint.org/docs/rules/no-unused-vars
        vars: 'local',
        args: 'after-used',
        varsIgnorePattern: '_'
      }
    ],
    'no-use-before-define': 2, // http://eslint.org/docs/rules/no-use-before-define
    'comma-dangle': [2, 'never'], // http://eslint.org/docs/rules/comma-dangle
    'no-alert': 2, // http://eslint.org/docs/rules/no-alert
    'no-console': 0, // http://eslint.org/docs/rules/no-console
    'block-scoped-var': 2, // http://eslint.org/docs/rules/block-scoped-var
    'consistent-return': 2, // http://eslint.org/docs/rules/consistent-return
    'default-case': 2, // http://eslint.org/docs/rules/default-case
    'guard-for-in': 2, // http://eslint.org/docs/rules/guard-for-in
    'no-caller': 2, // http://eslint.org/docs/rules/no-caller
    'no-else-return': 2, // http://eslint.org/docs/rules/no-else-return
    'no-eq-null': 2, // http://eslint.org/docs/rules/no-eq-null
    'no-eval': 2, // http://eslint.org/docs/rules/no-eval
    'no-extend-native': 2, // http://eslint.org/docs/rules/no-extend-native
    'no-extra-bind': 2, // http://eslint.org/docs/rules/no-extra-bind
    'no-floating-decimal': 2, // http://eslint.org/docs/rules/no-floating-decimal
    'no-implied-eval': 2, // http://eslint.org/docs/rules/no-implied-eval
    'no-invalid-this': 2, // http://eslint.org/docs/rules/no-invalid-this
    'no-lone-blocks': 2, // http://eslint.org/docs/rules/no-lone-blocks
    'no-loop-func': 2, // http://eslint.org/docs/rules/no-loop-func
    'no-multi-str': 2, // http://eslint.org/docs/rules/no-multi-str
    'no-global-assign': 2, // http://eslint.org/docs/rules/no-native-reassign
    'no-new': 2, // http://eslint.org/docs/rules/no-new
    'no-new-func': 2, // http://eslint.org/docs/rules/no-new-func
    'no-new-wrappers': 2, // http://eslint.org/docs/rules/no-new-wrappers
    'no-octal-escape': 2, // http://eslint.org/docs/rules/no-octal-escape
    'no-param-reassign': 2, // http://eslint.org/docs/rules/no-param-reassign
    'no-proto': 2, // http://eslint.org/docs/rules/no-proto
    'no-return-assign': 2, // http://eslint.org/docs/rules/no-return-assign
    'no-script-url': 2, // http://eslint.org/docs/rules/no-script-url
    'no-self-compare': 2, // http://eslint.org/docs/rules/no-self-compare
    'no-sequences': 2, // http://eslint.org/docs/rules/no-sequences
    'no-throw-literal': 2, // http://eslint.org/docs/rules/no-throw-literal
    'no-with': 2, // http://eslint.org/docs/rules/no-with
    radix: 2, // http://eslint.org/docs/rules/radix
    'vars-on-top': 2, // http://eslint.org/docs/rules/vars-on-top
    'wrap-iife': [2, 'any'], // http://eslint.org/docs/rules/wrap-iife
    yoda: 2, // http://eslint.org/docs/rules/yoda

    /**
 * Style
 */
    indent: 'off', // http://eslint.org/docs/rules/
    'brace-style': [
      2, // http://eslint.org/docs/rules/brace-style
      '1tbs',
      {
        allowSingleLine: false
      }
    ],
    quotes: [
      2,
      'single',
      'avoid-escape' // http://eslint.org/docs/rules/quotes
    ],
    camelcase: [
      2,
      {
        // http://eslint.org/docs/rules/camelcase
        properties: 'never'
      }
    ],
    'comma-spacing': [
      2,
      {
        // http://eslint.org/docs/rules/comma-spacing
        before: false,
        after: true
      }
    ],
    'comma-style': [2, 'last'], // http://eslint.org/docs/rules/comma-style
    'func-names': 2, // http://eslint.org/docs/rules/func-names
    'key-spacing': [
      2,
      {
        // http://eslint.org/docs/rules/key-spacing
        beforeColon: false,
        afterColon: true
      }
    ],
    'no-multiple-empty-lines': [
      2,
      {
        // http://eslint.org/docs/rules/no-multiple-empty-lines
        max: 2
      }
    ],
    'no-nested-ternary': 2, // http://eslint.org/docs/rules/no-nested-ternary
    'no-new-object': 2, // http://eslint.org/docs/rules/no-new-object
    'func-call-spacing': 2, // http://eslint.org/docs/rules/func-call-spacing
    'no-trailing-spaces': 2, // http://eslint.org/docs/rules/no-trailing-spaces
    'one-var': [2, 'never'], // http://eslint.org/docs/rules/one-var
    'padded-blocks': [2, 'never'], // http://eslint.org/docs/rules/padded-blocks
    semi: [2, 'always'], // http://eslint.org/docs/rules/semi
    'semi-spacing': [
      2,
      {
        // http://eslint.org/docs/rules/semi-spacing
        before: false,
        after: true
      }
    ],
    'keyword-spacing': 2, // http://eslint.org/docs/rules/keyword-spacing
    'space-before-function-paren': [2, 'never'], // http://eslint.org/docs/rules/space-before-function-paren
    'space-infix-ops': 2, // http://eslint.org/docs/rules/space-infix-ops,
    'no-underscore-dangle': 2 //https://eslint.org/docs/rules/no-underscore-dangle
  }
};


text:
<!DOCTYPE html>

    <title>Video.js | HTML5 Video Player</title>

    <link href="video-js.css" rel="stylesheet" type="text/css">

<video id="example_video_1" class="video-js vjs-default-skin" controls preload="none" width="640" height="264"
       poster="http://video-js.zencoder.com/oceans-clip.png"
       data-setup="{}">
    <source src="http://video-js.zencoder.com/oceans-clip.mp4" type='video/mp4'/>
    <source src="http://video-js.zencoder.com/oceans-clip.webm" type='video/webm'/>
    <source src="http://video-js.zencoder.com/oceans-clip.ogv" type='video/ogg'/>
    <track kind="captions" src="demo.captions.vtt" srclang="en" label="English"></track>

    <track kind="subtitles" src="demo.captions.vtt" srclang="en" label="English"></track>

To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video

</video>


text:
package org.apache.flink.graph.drivers.parameter;

import org.apache.flink.api.java.utils.ParameterTool;

/**
 * A {@link Parameter} storing a {@link Long} within <tt>min</tt> and
 * <tt>max</tt> bounds (inclusive).
 *
 *
Note that the default value may be outside of these bounds.
 */
public class LongParameter
extends SimpleParameter<Long> {

	private boolean hasMinimumValue = false;
	private long minimumValue;

	private boolean hasMaximumValue = false;
	private long maximumValue;

	/**
	 * Set the parameter name and add this parameter to the list of parameters
	 * stored by owner.
	 *
	 * @param owner the {@link Parameterized} using this {@link Parameter}
	 * @param name the parameter name
	 */
	public LongParameter(ParameterizedBase owner, String name) {
		super(owner, name);
	}

	/**
	 * Set the default value.
	 *
	 *
The default may set to any value and is not restricted by setting the
	 * minimum or maximum values.
	 *
	 * @param defaultValue the default value.
	 * @return this
	 */
	public LongParameter setDefaultValue(long defaultValue) {
		super.setDefaultValue(defaultValue);

		return this;
	}

	/**
	 * Set the minimum value.
	 *
	 *
If a maximum value has been set then the minimum value must not be
	 * greater than the maximum value.
	 *
	 * @param minimumValue the minimum value
	 * @return this
	 */
	public LongParameter setMinimumValue(long minimumValue) {
		if (hasMaximumValue) {
			Util.checkParameter(minimumValue <= maximumValue,
				"Minimum value (" + minimumValue + ") must be less than or equal to maximum (" + maximumValue + ")");
		}

		this.hasMinimumValue = true;
		this.minimumValue = minimumValue;

		return this;
	}

	/**
	 * Set the maximum value.
	 *
	 *
If a minimum value has been set then the maximum value must not be
	 * less than the minimum value.
	 *
	 * @param maximumValue the maximum value
	 * @return this
	 */
	public LongParameter setMaximumValue(long maximumValue) {
		if (hasMinimumValue) {
			Util.checkParameter(maximumValue >= minimumValue,
				"Maximum value (" + maximumValue + ") must be greater than or equal to minimum (" + minimumValue + ")");
		}

		this.hasMaximumValue = true;
		this.maximumValue = maximumValue;

		return this;
	}

	@Override
	public void configure(ParameterTool parameterTool) {
		if (hasDefaultValue && !parameterTool.has(name)) {
			// skip checks for min and max when using default value
			value = defaultValue;
		} else {
			value = parameterTool.getLong(name);

			if (hasMinimumValue) {
				Util.checkParameter(value >= minimumValue,
					name + " must be greater than or equal to " + minimumValue);
			}

			if (hasMaximumValue) {
				Util.checkParameter(value <= maximumValue,
					name + " must be less than or equal to " + maximumValue);
			}
		}
	}

	@Override
	public String toString() {
		return Long.toString(value);
	}
}


text:
var workerHashrateData;
var workerHashrateChart;
var workerHistoryMax = 160;

var statData;
var totalHash;
var totalImmature;
var totalBal;
var totalPaid;
var totalShares;

function getReadableHashRateString(hashrate){
	hashrate = (hashrate * 2);
	if (hashrate < 1000000) {
		return (Math.round(hashrate / 1000) / 1000 ).toFixed(2)+' Sol/s';
	}
	var byteUnits = [ ' Sol/s', ' KSol/s', ' MSol/s', ' GSol/s', ' TSol/s', ' PSol/s' ];
	var i = Math.floor((Math.log(hashrate/1000) / Math.log(1000)) - 1);
	hashrate = (hashrate/1000) / Math.pow(1000, i + 1);
	return hashrate.toFixed(2) + byteUnits[i];
}

function timeOfDayFormat(timestamp){
    var dStr = d3.time.format('%I:%M %p')(new Date(timestamp));
    if (dStr.indexOf('0') === 0) dStr = dStr.slice(1);
    return dStr;
}

function getWorkerNameFromAddress(w) {
	var worker = w;
	if (w.split(".").length > 1) {
		worker = w.split(".")[1];
		if (worker == null || worker.length < 1) {
			worker = "noname";
		}
	} else {
		worker = "noname";
	}
	return worker;
}

function buildChartData(){
    var workers = {};
	for (var w in statData.history) {
		var worker = getWorkerNameFromAddress(w);
		var a = workers[worker] = (workers[worker] || {
			hashrate: []
		});
		for (var wh in statData.history[w]) {
			a.hashrate.push([statData.history[w][wh].time * 1000, statData.history[w][wh].hashrate]);
		}
		if (a.hashrate.length > workerHistoryMax) {
			workerHistoryMax = a.hashrate.length;
		}
	}

	var i=0;
    workerHashrateData = [];
    for (var worker in workers){
        workerHashrateData.push({
            key: worker,
			disabled: (i > Math.min((_workerCount-1), 3)),
            values: workers[worker].hashrate
        });
		i++;
    }
}

function updateChartData(){
    var workers = {};
	for (var w in statData.history) {
		var worker = getWorkerNameFromAddress(w);
		// get a reference to lastest workerhistory
		for (var wh in statData.history[w]) { }
		//var wh = statData.history[w][statData.history[w].length - 1];
		var foundWorker = false;
		for (var i = 0; i < workerHashrateData.length; i++) {
			if (workerHashrateData[i].key === worker) {
				foundWorker = true;
				if (workerHashrateData[i].values.length >= workerHistoryMax) {
					workerHashrateData[i].values.shift();
				}
				workerHashrateData[i].values.push([statData.history[w][wh].time * 1000, statData.history[w][wh].hashrate]);
				break;
			}
		}
		if (!foundWorker) {
			var hashrate = [];
			hashrate.push([statData.history[w][wh].time * 1000, statData.history[w][wh].hashrate]);
			workerHashrateData.push({
				key: worker,
				values: hashrate
			});
			rebuildWorkerDisplay();
			return true;
		}
	}
	triggerChartUpdates();
	return false;
}

function calculateAverageHashrate(worker) {
	var count = 0;
	var total = 1;
	var avg = 0;
	for (var i = 0; i < workerHashrateData.length; i++) {
		count = 0;
		for (var ii = 0; ii < workerHashrateData[i].values.length; ii++) {
			if (worker == null || workerHashrateData[i].key === worker) {
				count++;
				avg += parseFloat(workerHashrateData[i].values[ii][1]);
			}
		}
		if (count > total)
			total = count;
	}
	avg = avg / total;
	return avg;
}

function triggerChartUpdates(){
    workerHashrateChart.update();
}

function displayCharts() {
    nv.addGraph(function() {
        workerHashrateChart = nv.models.lineChart()
            .margin({left: 80, right: 30})
            .x(function(d){ return d[0] })
            .y(function(d){ return d[1] })
            .useInteractiveGuideline(true);

        workerHashrateChart.xAxis.tickFormat(timeOfDayFormat);

        workerHashrateChart.yAxis.tickFormat(function(d){
            return getReadableHashRateString(d);
        });
        d3.select('#workerHashrate').datum(workerHashrateData).call(workerHashrateChart);
        return workerHashrateChart;
    });
}

function updateStats() {
	totalHash = statData.totalHash;
	totalPaid = statData.paid;
	totalBal = statData.balance;
	totalImmature = statData.immature;
	totalShares = statData.totalShares;
	// do some calculations
	var _blocktime = 250;
	var _networkHashRate = parseFloat(statData.networkSols) * 1.2;
	var _myHashRate = (totalHash / 1000000) * 2;
	var luckDays =  ((_networkHashRate / _myHashRate * _blocktime) / (24 * 60 * 60)).toFixed(3);
	// update miner stats
	$("#statsHashrate").text(getReadableHashRateString(totalHash));
	$("#statsHashrateAvg").text(getReadableHashRateString(calculateAverageHashrate(null)));
	$("#statsLuckDays").text(luckDays);
	$("#statsTotalImmature").text(totalImmature);
	$("#statsTotalBal").text(totalBal);
	$("#statsTotalPaid").text(totalPaid);
	$("#statsTotalShares").text(totalShares.toFixed(2));
}
function updateWorkerStats() {
	// update worker stats
	var i=0;
	for (var w in statData.workers) { i++;
		var htmlSafeWorkerName = w.split('.').join('_').replace(/[^\w\s]/gi, '');
		var saneWorkerName = getWorkerNameFromAddress(w);
		$("#statsHashrate"+htmlSafeWorkerName).text(getReadableHashRateString(statData.workers[w].hashrate));
		$("#statsHashrateAvg"+htmlSafeWorkerName).text(getReadableHashRateString(calculateAverageHashrate(saneWorkerName)));
		$("#statsLuckDays"+htmlSafeWorkerName).text(statData.workers[w].luckDays);
		$("#statsPaid"+htmlSafeWorkerName).text(statData.workers[w].paid);
		$("#statsBalance"+htmlSafeWorkerName).text(statData.workers[w].balance);
		$("#statsShares"+htmlSafeWorkerName).text(Math.round(statData.workers[w].currRoundShares * 100) / 100);
		$("#statsDiff"+htmlSafeWorkerName).text(statData.workers[w].diff);
	}
}
function addWorkerToDisplay(name, htmlSafeName, workerObj) {
	var htmlToAdd = "";
	htmlToAdd = '

';
	if (htmlSafeName.indexOf("_") >= 0) {
		htmlToAdd+= '
'+htmlSafeName.substr(htmlSafeName.indexOf("_")+1,htmlSafeName.length)+'
';
	} else {
		htmlToAdd+= '
noname
';
	}
	htmlToAdd+='
 '+getReadableHashRateString(workerObj.hashrate)+' (Now)
';
	htmlToAdd+='
 '+getReadableHashRateString(calculateAverageHashrate(name))+' (Avg)
';
	htmlToAdd+='
 Diff: '+workerObj.diff+'
';
	htmlToAdd+='
 Shares: '+(Math.round(workerObj.currRoundShares * 100) / 100)+'
';
	htmlToAdd+='
 Luck '+workerObj.luckDays+' Days
';
	htmlToAdd+='
 Bal: '+workerObj.balance+'
';
	htmlToAdd+='
 Paid: '+workerObj.paid+'
';
	htmlToAdd+='

';
	$("#boxesWorkers").html($("#boxesWorkers").html()+htmlToAdd);
}

function rebuildWorkerDisplay() {
	$("#boxesWorkers").html("");
	var i=0;
	for (var w in statData.workers) { i++;
		var htmlSafeWorkerName = w.split('.').join('_').replace(/[^\w\s]/gi, '');
		var saneWorkerName = getWorkerNameFromAddress(w);
		addWorkerToDisplay(saneWorkerName, htmlSafeWorkerName, statData.workers[w]);
	}
}

// resize chart on window resize
nv.utils.windowResize(triggerChartUpdates);

// grab initial stats
$.getJSON('/api/worker_stats?'+_miner, function(data){
    statData = data;
	for (var w in statData.workers) { _workerCount++; }
	buildChartData();
	displayCharts();
	rebuildWorkerDisplay();
    updateStats();
});

// live stat updates
statsSource.addEventListener('message', function(e){
	// TODO, create miner_live_stats...
	// miner_live_stats will return the same josn except without the worker history
	// FOR NOW, use this to grab updated stats
	$.getJSON('/api/worker_stats?'+_miner, function(data){
		statData = data;
		// check for missing workers
		var wc = 0;
		var rebuilt = false;
		// update worker stats
		for (var w in statData.workers) { wc++; }
		// TODO, this isn't 100% fool proof!
		if (_workerCount != wc) {
			if (_workerCount > wc) {
				rebuildWorkerDisplay();
				rebuilt = true;
			}
			_workerCount = wc;
		}
		rebuilt = (rebuilt || updateChartData());
		updateStats();
		if (!rebuilt) {
			updateWorkerStats();
		}
	});
});


text:
namespace Gallio.Common.Messaging.MessageSinks.Tcp
{
	/// <summary>
	/// Socket error codes - http://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx
	/// </summary>
	public static class SocketErrorCodes
	{
		/// <summary>
		/// Connection refused.
		/// </summary>
		public const int WSAECONNREFUSED = 10061;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<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>

	<groupId>jpabook</groupId>
	<artifactId>ch00-model0</artifactId>
	<version>1.0-SNAPSHOT</version>

	<properties>

		<!-- 기본 설정 -->
		<java.version>1.6</java.version>
		<!-- 프로젝트 코드 인코딩 설정 -->
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

		<!-- JPA, 하이버네이트 버전 -->
		<hibernate.version>4.3.10.Final</hibernate.version>
		<!-- 데이터베이스 버전 -->
		<h2db.version>2.1.210</h2db.version>

	</properties>

	<dependencies>
		<!-- JPA, 하이버네이트 -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<!-- H2 데이터베이스 -->
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>${h2db.version}</version>
		</dependency>
		<!-- Logger -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.12</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.27</version>
		</dependency>
		<!-- StringUtils -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.0</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


text:
package io.quarkus.resteasy.reactive.server.test.resource.basic;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.function.Supplier;

import javax.ws.rs.GET;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.resteasy.reactive.server.test.simple.PortProviderUtil;
import io.quarkus.test.QuarkusUnitTest;

@DisplayName("Media Type Negotiation Server Quality Test")
public class MediaTypeNegotiationServerQualityTest {

    @Produces({ "application/*;qs=0.7", "text/*;qs=0.9" })
    @DisplayName("Custom Message Body Writer")
    @Provider
    public static class CustomMessageBodyWriter implements MessageBodyWriter<Object> {

        @Override
        public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
            return true;
        }

        @Override
        public long getSize(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
            return -1;
        }

        @Override
        public void writeTo(Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
                MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
                throws IOException, WebApplicationException {
        }
    }

    @DisplayName("Not Found Exception Mapper")
    @Provider
    public static class NotFoundExceptionMapper implements ExceptionMapper<NotFoundException> {

        @Override
        public Response toResponse(NotFoundException notFoundException) {
            return Response.status(Status.NOT_FOUND).entity(new Object()).build();
        }
    }

    @Path("/foo")
    public static class FakeResource {
        @GET
        @Path("/fake")
        public String fake() {
            return "";
        }
    }

    private static Client client;

    @RegisterExtension
    static QuarkusUnitTest testExtension = new QuarkusUnitTest()
            .setArchiveProducer(new Supplier<>() {
                @Override
                public JavaArchive get() {
                    JavaArchive war = ShrinkWrap.create(JavaArchive.class);
                    war.addClasses(PortProviderUtil.class, CustomMessageBodyWriter.class, FakeResource.class,
                            NotFoundExceptionMapper.class);
                    return war;
                }
            });

    @BeforeAll
    public static void setup() {
        client = ClientBuilder.newClient();
    }

    @AfterAll
    public static void cleanup() {
        client.close();
    }

    private String generateURL() {
        return PortProviderUtil.generateBaseUrl();
    }

    @Test
    @DisplayName("Test Server Quality")
    public void testServerQuality() throws Exception {
        Invocation.Builder request = client.target(generateURL()).path("foo/echo").request("application/x;", "text/y");
        Response response = request.get();
        try {
            Assertions.assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
            MediaType mediaType = response.getMediaType();
            Assertions.assertEquals("text", mediaType.getType());
            Assertions.assertEquals("y", mediaType.getSubtype());
        } finally {
            response.close();
        }
    }
}


text:
<?php

namespace Taskio\Controller;

use Taskio\Entity\UserGroup;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

class UserGroupController extends AbstractController
{
}


text:
<?php
/**
 * The base configurations of the WordPress.
 *
 * This file has the following configurations: MySQL settings, Table Prefix,
 * Secret Keys, WordPress Language, and ABSPATH. You can find more information
 * by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing
 * wp-config.php} Codex page. You can get the MySQL settings from your web host.
 *
 * This file is used by the wp-config.php creation script during the
 * installation. You don't have to use the web site, you can just copy this file
 * to "wp-config.php" and fill in the values.
 *
 * @package WordPress
 */

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'database_name_here');

/** MySQL database username */
define('DB_USER', 'username_here');

/** MySQL database password */
define('DB_PASSWORD', 'password_here');

/** MySQL hostname */
define('DB_HOST', 'localhost');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

/**#@+
 * Authentication Unique Keys and Salts.
 *
 * Change these to different unique phrases!
 * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
 * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         'put your unique phrase here');
define('SECURE_AUTH_KEY',  'put your unique phrase here');
define('LOGGED_IN_KEY',    'put your unique phrase here');
define('NONCE_KEY',        'put your unique phrase here');
define('AUTH_SALT',        'put your unique phrase here');
define('SECURE_AUTH_SALT', 'put your unique phrase here');
define('LOGGED_IN_SALT',   'put your unique phrase here');
define('NONCE_SALT',       'put your unique phrase here');

/**#@-*/

/**
 * WordPress Database Table prefix.
 *
 * You can have multiple installations in one database if you give each a unique
 * prefix. Only numbers, letters, and underscores please!
 */
$table_prefix  = 'wp_';

/**
 * WordPress Localized Language, defaults to English.
 *
 * Change this to localize WordPress. A corresponding MO file for the chosen
 * language must be installed to wp-content/languages. For example, install
 * de_DE.mo to wp-content/languages and set WPLANG to 'de_DE' to enable German
 * language support.
 */
define('WPLANG', '');

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 */
define('WP_DEBUG', false);

/* Set theme to Vrijplaats */
define('WP_DEFAULT_THEME', 'vrijplaats');

/**
 * Multisite configuration
 *
 * See: http://codex.wordpress.org/Create_A_Network
 */
define('WP_ALLOW_MULTISITE', true);
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
$base = '/';
define('DOMAIN_CURRENT_SITE', 'localhost');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);

/* That's all, stop editing! Happy blogging. */

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
	define('ABSPATH', dirname(__FILE__) . '/wp');

/** Sets up WordPress vars and included files. */
define( 'WP_CONTENT_DIR', dirname(__FILE__) . '/wp-content' );
require_once(ABSPATH . 'wp-settings.php');
$plugins = get_option( 'active_plugins' );
if ( count( $plugins ) === 0 ) {
  require_once(ABSPATH .'/wp-admin/includes/plugin.php');
  $pluginsToActivate = array( 'nginx-helper/nginx-helper.php' );
  foreach ( $pluginsToActivate as $plugin ) {
    if ( !in_array( $plugin, $plugins ) ) {
      activate_plugin( '/usr/share/nginx/www/wp-content/plugins/' . $plugin );
    }
  }
}


text:
<!doctype html>
<title>CSS Test Reference</title>
<meta charset="utf-8">
<link rel="author" title="Emilio Cobos Álvarez" href="mailto:emilio@crisal.io">


text:
package org.sakaiproject.metaobj.shared.mgt;

import org.sakaiproject.metaobj.utils.mvc.intf.FieldValueWrapper;

/**
 * Created by IntelliJ IDEA.
 * User: John Ellis
 * Date: Jul 5, 2005
 * Time: 2:28:58 PM
 * To change this template use File | Settings | File Templates.
 */
public interface FieldValueWrapperFactory {
   boolean checkWrapper(Class clazz);

   FieldValueWrapper wrapInstance(Class clazz);

   FieldValueWrapper wrapInstance(Object obj);
}


text:
<?php
namespace Payum\Core\Request;

use Payum\Core\Exception\LogicException;

abstract class BaseModelInteractiveRequest  extends LogicException implements InteractiveRequestInterface, ModelRequestInterface
{
    /**
     * @var mixed
     */
    protected $model;

    /**
     * @param mixed $model
     */
    public function __construct($model)
    {
        $this->setModel($model);
    }

    /**
     * @return mixed
     */
    public function getModel()
    {
        return $this->model;
    }

    /**
     * @param mixed $model
     */
    public function setModel($model)
    {
        if (is_array($model)) {
            $model = new \ArrayObject($model);
        }

        $this->model = $model;
    }
}


text:
//*******************************************************************
// OSSIM
//
// License:  See top level LICENSE.txt file.
//
//*******************************************************************
//  $Id: ossimSlopeFilter.h 23451 2015-07-27 15:42:17Z okramer $
#ifndef ossimSlopeFilter_HEADER
#define ossimSlopeFilter_HEADER

#include <ossim/imaging/ossimImageSourceFilter.h>
#include <ossim/imaging/ossimImageToPlaneNormalFilter.h>

/**
 * Filter class for computing the slope image of the input image connection. The slope
 * dP/dR is defined as the maximum change in pixel value for a differential change in ground
 * position. This filter would typically be applied to elevation data (represented as an image),
 * where dP is the change in height when walking some distance dR either straight uphill or
 * downhill. Numerically , this quantity is computed from the dot product of the normal vector with
 * the local vertical.
 *
 * The output is a floating point single-band image. The input should be a single-band, floating
 * point image. The slope quantity can be represented as an angle from local vertical, i.e., the
 * arccos(dP/dR) (in radians, degrees, or normalized) or as the simple ratio dP/dR.
 */
class OSSIMDLLEXPORT ossimSlopeFilter : public ossimImageSourceFilter
{
public:
   /** Specifies how the slope quantity is represented */
   enum SlopeType
   {
      RADIANS,   // Angle from local vertical in radians
      DEGREES,   // Angle from local vertical in degrees (default)
      RATIO,     // dH/dR ratio of change in height to change in horizontal ground distance
      NORMALIZED // Angle from local vertical normalized so that 0.0 = 0 deg, 1.0 = 90 deg)
   };

   ossimSlopeFilter();
   ossimSlopeFilter(ossimImageSource* inputSource);

   virtual void initialize();

   virtual ossimString getLongName()  const;
   virtual ossimString getShortName() const;

   virtual ossimRefPtr<ossimImageData> getTile(const ossimIrect& tile_rect, ossim_uint32 rLevel=0);

   /**
    *  Returns the output pixel type of the tile source.  This override the
    *  base class since it simply returns it's input scalar type which is
    *  not correct with this object.
    */
   virtual ossimScalarType getOutputScalarType() const { return OSSIM_FLOAT32; }

   /**
    *  Method to save the state of an object to a keyword list.
    *  Return true if ok or false on error.
    */
   virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=NULL)const;

   /**
    * Method to the load (recreate) the state of an object from a keyword
    * list.  Return true if ok or false on error.
    */
   virtual bool loadState(const ossimKeywordlist& kwl,
                          const char* prefix=NULL);

   virtual void setProperty(ossimRefPtr<ossimProperty> property);
   virtual ossimRefPtr<ossimProperty> getProperty(const ossimString& name)const;
   virtual void getPropertyNames(std::vector<ossimString>& propertyNames)const;

   void setSlopeType(SlopeType t) { m_slopeType = t; }

protected:
   virtual ~ossimSlopeFilter();
   static ossimString getSlopeTypeString(SlopeType t);

   ossimRefPtr<ossimImageToPlaneNormalFilter> m_normals;
   SlopeType m_slopeType;

   TYPE_DATA
};

#endif /* #ifndef ossimSlopeFilter_HEADER */