text:
<!doctype html>

    <meta charset="utf-8"/>
    <title>TIFF Metadata Format Specification and Usage Notes</title>

TIFF Metadata Format Specification and Usage Notes

Reading Images

Color Conversion

Color Spaces

ICC Profiles

Metadata Issues

Native to Standard Metadata Mapping

Reading Exif Images

Reading Uncompressed Exif Images

Reading Compressed Exif Images

Writing Images

Compression

Color Conversion

ICC Profiles

Metadata Issues

Standard to Native Metadata Mapping

Writing Exif Images

Writing Uncompressed Exif Images

Writing Compressed Exif Images

Native Stream Metadata Format

Native Image Metadata Format

Reading Images

TIFF images are read by an {@link javax.imageio.ImageReader ImageReader}
which may be controlled by its public interface as well as via a supplied
{@link javax.imageio.plugins.tiff.TIFFImageReadParam TIFFImageReadParam}.

Color Conversion

If the source image data
have photometric type CIE L*a*b* or YCbCr, and the destination color space
type is RGB, then the source image data will be automatically converted to
RGB using an internal color converter.

Color Spaces

The raw color space assigned by default, i.e., in the absence of a
user-supplied {@link javax.imageio.ImageTypeSpecifier ImageTypeSpecifier},
will be the first among the following which applies:

A color space created from the ICC Profile
metadata field if it is present and compatible with the image data
layout.

sRGB if the image is monochrome/bilevel
(a two-level color map is created internally).

sRGB if the image is palette-color.

Linear RGB if the image has three samples per pixel, has photometric type
CIE L*a*b*, or has photometric type YCbCr and is not
JPEG-compressed.

A default CMYK color space if the image has
photometric type CMYK and four samples per pixel.

Grayscale if the image has one or two samples per pixel and uniformly
1, 2, 4, 8, 16, or 32 bits per sample or is floating point.

sRGB if the image has three or four samples per pixel and uniformly
1, 2, 4, 8, 16, or 32 bits per sample or is floating point.

A fabricated, generic color space if the image
has more than four samples per pixel and the number of bits per sample for
all bands is the same and is a multiple of 8.

Grayscale if the image has one or two samples per pixel regardless of
the number of bits per sample.

sRGB if the image has three or four samples per pixel regardless of
the number of bits per sample.

A fabricated, generic color space if the image
has more than four samples per pixel regardless of the number of bits per
sample.

The normalized color coordinate transformations
used for the default CMYK color space are defined as follows:

CMYK to linear RGB

R = (1 - K)*(1 - C)
G = (1 - K)*(1 - M)
B = (1 - K)*(1 - Y)

Linear RGB to CMYK

K = min{1 - R, 1 - G, 1 - B}
if(K != 1) {
    C = (1 - R - K)/(1 - K)
    M = (1 - G - K)/(1 - K)
    Y = (1 - B - K)/(1 - K)
} else {
    C = M = Y = 0
}

The generic color space used when no other color space
can be inferred is provided merely to enable the data to be loaded. It is not
intended to provide accurate conversions of any kind.

If the data are known to be in a color space not correctly handled by the
foregoing, then an ImageTypeSpecifier should be
supplied to the reader and should be derived from a color space which is correct
for the data in question.

ICC Profiles

If an ICC profile is contained in the image metadata
({@link javax.imageio.plugins.tiff.BaselineTIFFTagSet BaselineTIFFTagSet}.
TAG_ICC_PROFILE, tag number 34675),
an attempt will be made to use it to create the color space
of the loaded image. It will be used if the data layout is of component type
and the number of samples per pixel equals or is one greater than the number
of components described by the ICC profile. If the ICC profile is not used
then the color space will be inferred in one of the subsequent steps described
above.

If for some reason the embedded ICC profile is not used automatically, then
it may be used manually by following this procedure:

Obtain the image metadata from
ImageReader.getImageMetadata

Extract the ICC profile field and its value.

Create an {@link java.awt.color.ICC_ColorSpace ICC_ColorSpace} from an
{@link java.awt.color.ICC_Profile ICC_Profile} created from the ICC profile field data
using ICC_Profile.getInstance(byte[]).

Create an ImageTypeSpecifier from the new color
space using one of its factory methods which accepts an
ICC_ColorSpace.

Create a compatible {@link javax.imageio.ImageReadParam ImageReadParam}
and set the ImageTypeSpecifier using
ImageReadParam.setDestinationType.

Pass the parameter object to the appropriate read method.

If the inferred color space not based on the ICC Profile field is compatible
with the ICC profile-based color space, then a second
ImageTypeSpecifier derived from this inferred color
space will be included in the
{@link java.util.Iterator Iterator} returned by
ImageReader.getImageTypes. If the iterator contains
more than one type, the first one will be based on the ICC profile and the
second on the inferred color space.

Metadata Issues

By default all recognized fields in the TIFF image file directory (IFD) are
loaded into the native image metadata object. Which fields are loaded may be
controlled by setting which TIFF tags the reader is allowed to recognize,
whether to read fields with unrecognized tags, and whether to ignore all
metadata. The reader is informed to disregard all metadata as usual via the
ignoreMetadata parameter of
ImageReader.setInput(Object,boolean,boolean). It is
informed of which {@link javax.imageio.plugins.tiff.TIFFTag TIFFTag}s to
recognize or not to recognize via
TIFFImageReadParam.addAllowedTagSet(TIFFTagSet) and
TIFFImageReadParam.removeAllowedTagSet(TIFFTagSet).
If ignoreMetadata is true, then only metadata
essential to reading the image will be loaded into the native image metadata
object. If ignoreMetadata is false, then the reader
will by default load into the native image metadata object only those fields
which are either essential to reading the image or have a TIFFTag
contained in the one of the allowed TIFFTagSets. Reading of
fields with tags not in the allowed TIFFTagSets may be forced
by passing in a TIFFImageReadParam on which
TIFFImageReadParam.setReadUnknownTags(boolean) has been
invoked with parameter true.

Use of a {@link javax.imageio.plugins.tiff.TIFFDirectory TIFFDirectory}
object may simplify gaining access to metadata values. An instance of
TIFFDirectory may be created from the IIOMetadata
object returned by the TIFF reader using the
TIFFDirectory.createFromMetadata method.

Mapping of TIFF Native Image Metadata to the Standard Metadata Format

The derivation of standard metadata format
javax_imageio_1.0
elements from TIFF native image metadata is given
in the following table.

Index
Standard Metadata Element
Derivation from TIFF Fields

1
/Chroma/ColorSpaceType@name
PhotometricInterpretation: WhiteIsZero, BlackIsZero, TransparencyMask =
"GRAY"; RGB, PaletteColor => "RGB"; CMYK => "CMYK";
YCbCr => "YCbCr";
CIELab, ICCLab => "Lab".

2
/Chroma/NumChannels@value
SamplesPerPixel

3
/Chroma/BlackIsZero@value
"TRUE" <=> PhotometricInterpretation => WhiteIsZero

4
/Chroma/Palette
ColorMap

5
/Compression/CompressionTypeName@value
Compression: Uncompressed => "none"; CCITT 1D => "CCITT
RLE";
Group 3 Fax => "CCITT T.4"; Group 4 Fax => "CCITT T.6";
LZW => "LZW";
JPEG => "Old JPEG"; New JPEG => "JPEG"; Zlib =>> "ZLib"; PackBits =>
"PackBits";
Deflate => "Deflate"; Exif JPEG => "JPEG".

6
/Compression/Lossless@value
Compression: JPEG or New JPEG => "FALSE"; otherwise "TRUE".

7
/Data/PlanarConfiguration@value
Chunky => "PixelInterleaved"; Planar => "PlaneInterleaved".

8
/Data/SampleFormat@value
PhotometricInterpretation PaletteColor => "Index";
SampleFormat unsigned integer data => "UnsignedIntegral";
SampleFormat two's complement signed integer data => "SignedIntegral";
SampleFormat IEEE floating point data => "Real";
otherwise element not emitted.

9
/Data/BitsPerSample@value
BitsPerSample as a space-separated list.

10
/Data/SampleMSB@value
FillOrder: left-to-right => space-separated list of BitsPerSample-1;
right-to-left => space-separated list of 0s.

11
/Dimension/PixelAspectRatio@value
(1/XResolution)/(1/YResolution)

12
/Dimension/ImageOrientation@value
Orientation

13
/Dimension/HorizontalPixelSize@value
1/XResolution in millimeters if ResolutionUnit is not None.

14
/Dimension/VerticalPixelSize@value
1/YResolution in millimeters if ResolutionUnit is not None.

15
/Dimension/HorizontalPosition@value
XPosition in millimeters if ResolutionUnit is not None.

16
/Dimension/VerticalPosition@value
YPosition in millimeters if ResolutionUnit is not None.

17
/Document/FormatVersion@value
6.0

18
/Document/SubimageInterpretation@value
NewSubFileType: transparency => "TransparencyMask";
reduced-resolution => "ReducedResolution";
single page => "SinglePage".

19
/Document/ImageCreationTime@value
DateTime

20
/Text/TextEntry
DocumentName, ImageDescription, Make, Model, PageName, Software,
Artist, HostComputer, InkNames, Copyright:
/Text/TextEntry@keyword = field name,
/Text/TextEntry@value = field value.

Example: TIFF Software field => /Text/TextEntry@keyword = "Software",
/Text/TextEntry@value = Name and version number of the software package(s)
used to create the image.

21
/Transparency/Alpha@value
ExtraSamples: associated alpha => "premultiplied";
unassociated alpha => "nonpremultiplied".

Reading Exif Images

The TIFF reader may be used to read an uncompressed Exif image or the
contents of the APP1 marker segment of a compressed Exif image.

Reading Uncompressed Exif Images

An uncompressed Exif image is a one- or two-page uncompressed TIFF image
with a specific ordering of its IFD and image data content. Each pixel
has three 8-bit samples with photometric interpretation RGB or YCbCr.
The image stream must contain a single primary image and may contain a
single thumbnail which if present must also be uncompressed. The usual
ImageReader methods may be used to read the image
data and metadata:

    ImageInputStream input;
    ImageReader tiffReader;
    ImageReadParam tiffReadParam;

    tiffReader.setInput(input);

    // Read primary image and IFD.
    BufferedImage image = tiffReader.read(0, tiffReadParam);
    IIOMetadata primaryIFD = tiffReader.getImageMetadata(0);

    // Read thumbnail if present.
    BufferedImage thumbnail = null;
    if (tiffReader.getNumImages(true) > 1) {
        thumbnail = tiffReader.read(1, tiffReadParam);
    }

Note that the Exif thumbnail is treated as a separate page in the TIFF
stream and not as a thumbnail, i.e.,
tiffReader.hasThumbnails(0) will return false.

Reading Compressed Exif Images

A compressed Exif image is a 3-band ISO/IEC 10918-1 baseline DCT JPEG stream
with an inserted APP1 marker segment. The parameters of the marker
segment after the length are the 6-byte sequence
{'E', 'x', 'i', 'f', 0x00, 0x00}
followed by a complete TIFF stream. The embedded TIFF stream contains a primary
IFD describing the JPEG image optionally followed by a thumbnail IFD and
compressed or uncompressed thumbnail image data. Note that the embedded TIFF
stream does not contain any image data associated with the primary IFD
nor any descriptive fields which duplicate information found in the JPEG
stream itself.

The parameter content of the APP1 marker segment may be obtained
from the user object of the associated Node in a
javax_imageio_jpeg_image_1.0 native image metadata tree extracted
from the image metadata object returned by the JPEG reader. This APP1 Exif
node will be a child of the node named "markerSequence" and will
have name unknown and an attribute named MarkerTag with
integral value 0xE1 (String value
"225"). The user object of this node will be a byte array
which starts with the six bytes {'E', 'x', 'i', 'f', '0', '0'}.
The primary IFD and the thumbnail IFD and image may be
read from the user object by the usual ImageReader
methods:

    ImageReader jpegReader;
    ImageReader tiffReader;

    // Obtain the APP1 Exif marker data from the JPEG image metadata.
    IIOMetadata jpegImageMetadata = jpegReader.getImageMetadata(0);
    String nativeFormat = jpegImageMetadata.getNativeMetadataFormatName();
    Node jpegImageMetadataTree = jpegImageMetadata.getAsTree(nativeFormat);

    // getExifMarkerData() returns the byte array which is the user object
    // of the APP1 Exif marker node.
    byte[] app1Params = getExifMarkerData(jpegImageMetadataTree);
    if (app1Params == null) {
        throw new IIOException("APP1 Exif marker not found.");
    }

    // Set up input, skipping Exif ID 6-byte sequence.
    MemoryCacheImageInputStream app1ExifInput
        = new MemoryCacheImageInputStream
            (new ByteArrayInputStream(app1Params, 6, app1Params.length - 6));
    tiffReader.setInput(app1ExifInput);

    // Read primary IFD.
    IIOMetadata primaryIFD = tiffReader.getImageMetadata(0);

    // Read thumbnail if present.
    BufferedImage thumbnail = null;
    if (tiffReader.getNumImages(true) > 1) {
        thumbnail = tiffReader.read(1, tiffReadParam);
    }

    // Read the primary image.
    BufferedImage image = jpegReader.read(0);

Note that tiffReader.getNumImages(true) returns the number of
IFDs in the embedded TIFF stream including those corresponding to empty
images. Calling tiffReader.read(0, readParam) will throw
an exception as the primary image in the embedded TIFF stream is always
empty; the primary image should be obtained using the JPEG reader itself.

Writing Images

TIFF images are written by a {@link javax.imageio.ImageWriter ImageWriter} which may be
controlled by its public interface as well as via a supplied
{@link javax.imageio.ImageWriteParam ImageWriteParam}.  For an ImageWriteParam returned
by the getDefaultWriteParam() method of the TIFF ImageWriter,
the canWriteTiles() and canWriteCompressed() methods
will return true; the canOffsetTiles() and
canWriteProgressive() methods will return false.

The TIFF writer supports many optional capabilities including writing tiled
images, inserting images, writing or inserting empty images, and replacing image
data. Pixels may be replaced in either empty or non-empty images but if and
only if the data are not compressed.

 If tiles are being written, then each of their dimensions will be
rounded to the nearest multiple of 16 per the TIFF specification. If
JPEG-in-TIFF compression is being used, and tiles are being written
each tile dimension will be rounded to the nearest multiple of 8 times
the JPEG minimum coded unit (MCU) in that dimension. If JPEG-in-TIFF
compression is being used and strips are being written, the number of
rows per strip is rounded to a multiple of 8 times the maximum MCU over
both dimensions.

Compression

The compression type may be set via the setCompressionType() method of
the ImageWriteParam after setting the compression mode to
MODE_EXPLICIT. The set of innately
supported compression types is listed in the following table:

Supported Compression Types

  Index
  Compression Type
  Description
  Reference

1
CCITT RLE
Modified Huffman compression
TIFF 6.0 Specification, Section 10

2
CCITT T.4
CCITT T.4 bilevel encoding/Group 3 facsimile compression
TIFF 6.0 Specification, Section 11

3
CCITT T.6
CCITT T.6 bilevel encoding/Group 4 facsimile compression
TIFF 6.0 Specification, Section 11

4
LZW
LZW compression
TIFF 6.0 Specification, Section 13

5
JPEG
"New" JPEG-in-TIFF compression
TIFF Technical Note #2

6
ZLib
"Deflate/Inflate" compression (see note following this table)
Adobe Photoshop® TIFF Technical Notes

7
PackBits
Byte-oriented, run length compression
TIFF 6.0 Specification, Section 9

8
Deflate
"Zip-in-TIFF" compression (see note following this table)

ZLIB Compressed Data Format Specification,

DEFLATE Compressed Data Format Specification

9
Exif JPEG
Exif-specific JPEG compression (see note following this table)
Exif 2.2 Specification
(PDF), section 4.5.5, "Basic Structure of Thumbnail Data"

Old-style JPEG compression as described in section 22 of the TIFF 6.0
Specification is not supported.

 The CCITT compression types are applicable to bilevel (1-bit)
images only.  The JPEG compression type is applicable to byte
grayscale (1-band) and RGB (3-band) images only.

ZLib and Deflate compression are identical except for the value of the
TIFF Compression field: for ZLib the Compression field has value 8
whereas for Deflate it has value 32946 (0x80b2). In both cases each
image segment (strip or tile) is written as a single complete zlib data
stream.

"Exif JPEG" is a compression type used when writing the contents of an
APP1 Exif marker segment for inclusion in a JPEG native image metadata
tree. The contents appended to the output when this compression type is
used are a function of whether an empty or non-empty image is written.
If the image is empty, then a TIFF IFD adhering to the specification of
a compressed Exif primary IFD is appended. If the image is non-empty,
then a complete IFD and image adhering to the specification of a
compressed Exif thumbnail IFD and image are appended. Note that the
data of the empty image may not later be appended using the pixel
replacement capability of the TIFF writer.

 If ZLib/Deflate or JPEG compression is used, the compression quality
may be set. For ZLib/Deflate the supplied floating point quality value is
rescaled to the range [1, 9] and truncated to an integer
to derive the Deflate compression level. For JPEG the floating point
quality value is passed directly to the JPEG writer plug-in which
interprets it in the usual way.

Color Conversion

If the source image data
color space type is RGB, and the destination photometric type is CIE L*a*b* or
YCbCr, then the source image data will be automatically converted from
RGB using an internal color converter.

ICC Profiles

An ICC Profile field will be written if either:

one is present in the native image metadata
{@link javax.imageio.metadata.IIOMetadata IIOMetadata} instance supplied to the writer,
or

the {@link java.awt.color.ColorSpace ColorSpace}
of the destination ImageTypeSpecifier is an instance of
ICC_ColorSpace which is not one of the standard
color spaces defined by the CS_* constants in the
ColorSpace class. The destination type is set via
ImageWriteParam.setDestinationType(ImageTypeSpecifier) and defaults
to the ImageTypeSpecifier of the image being written.

Metadata Issues

Some behavior of the writer is affected by or may affect the contents of
the image metadata which may be supplied by the user.

For bilevel images, the FillOrder, and T4Options
fields affect the output data. The data will be filled right-to-left if
FillOrder is present with a value of 2
(BaselineTIFFTagSet.FILL_ORDER_RIGHT_TO_LEFT)
and will be filled left-to-right otherwise. The value of T4Options
specifies whether the data should be 1D- or 2D-encoded and whether EOL
padding should be used.

For all images the value of the RowsPerStrip field is used
to the set the number of rows per strip if the image is not tiled. The
default number of rows per strip is either 8 or the number of rows which
would fill no more than 8 kilobytes, whichever is larger.

For all images the tile dimensions may be set using the TileWidth
and TileLength field values if the tiling mode is
ImageWriteParam.MODE_COPY_FROM_METADATA. If this mode
is set but the fields are not, their respective default values are the image
width and height.

When using JPEG-in-TIFF compression, a JPEGTables field will be
written to the IFD and abbreviated JPEG streams to each strip or tile if and
only if a JPEGTables field is contained in the metadata object
provided to the writer. If the contents of the JPEGTables field is
a valid tables-only JPEG stream, then it will be used; otherwise the contents
of the field will be replaced with default visually lossless tables. If no
such JPEGTables field is present in the metadata, then no
JPEGTables field will be written to the output and each strip or
tile will be written as a separate, self-contained JPEG stream.

When using Deflate/ZLib or LZW compression, if the image has 8 bits per
sample, a horizontal differencing predictor will be used if the
Predictor field is present with a value of 2
(BaselineTIFFTagSet.PREDICTOR_HORIZONTAL_DIFFERENCING).
If prediction is so requested but the image does not have
8 bits per sample the field will be reset to have the value 1
(BaselineTIFFTagSet.PREDICTOR_NONE).

Some fields may be added or modified:

PhotometricInterpretation if not present.

PlanarConfiguration if this field is present with value
Planar is is reset to Chunky.

Compression always.

BitsPerSample if the image is not bilevel.

SamplesPerPixel always.

ExtraSamples if an alpha channel is present.

SampleFormat if not present and the data are 16- or 32-bit
integers or floating point.

ColorMap if the PhotometricInterpretation is
RGBPalette.

ImageWidth and ImageLength always.

TileWidth, TileLength, TileOffsets, and
TileByteCounts if a tiled image is being written.

RowsPerStrip, StripOffsets, and StripByteCounts
if a tiled image is not being written.

XResolution, YResolution, and ResolutionUnit
if none of these is present.

YCbCrSubsampling and YCbCrPositioning if the
photometric interpretation is YCbCr and the compression type is not JPEG
(only [1, 1] subsampling and cosited positioning are supported for
non-JPEG YCbCr output).

YCbCrSubsampling, YCbCrPositioning, and
ReferenceBlackWhite: if the compression type is JPEG and the color
space is RGB these will be reset to [2, 2] centered subsampling with no
headroom/footroom (0:255,128:255,128:255).

Some fields may be removed:

BitsPerSample if the image is bilevel.

ExtraSamples if the image does not have an alpha channel.

ColorMap if the photometric interpretation is not
RGBPalette.

TileWidth, TileLength, TileOffsets, and
TileByteCounts if tiling is not being used.

RowsPerStrip, StripOffsets, and StripByteCounts
if tiling is being used.

YCbCrSubsampling, YCbCrPositioning, and
ReferenceBlackWhite if the compression type is JPEG and the
color space is grayscale.

JPEGProc, JPEGInterchangeFormat,
JPEGInterchangeFormatLength, JPEGRestartInterval,
JPEGLosslessPredictors, JPEGPointTransforms,
JPEGQTables, JPEGDCTables, and
JPEGACTables if the compression type is JPEG.

Other fields present in the supplied metadata are uninterpreted and will
be written as supplied.

If an Exif image is being written, the set of fields present and their
values will be modified such that the result is in accord with the Exif 2.2
specification.

Setting up the image metadata to write to a TIFF stream may be simplified
by using the TIFFDirectory class
which represents a TIFF IFD. A field in a TIFF IFD is represented by an
instance of {@link javax.imageio.plugins.tiff.TIFFField TIFFField}. For each
field to be written a TIFFField may be added to the
TIFFDirectory and the latter converted to an
IIOMetadata object by invoking
TIFFDirectory.getAsMetadata. The
IIOMetadata object so obtained may then be passed to the TIFF
writer.

Mapping of the Standard Metadata Format to TIFF Native Image Metadata

The derivation of TIFF native image metadata
elements from the standard metadata format
javax_imageio_1.0 is
given in the following table.

Index
TIFF Field
Derivation from Standard Metadata Elements

1

PhotometricInterpretation

/Chroma/ColorSpaceType@name: "GRAY" and /Chroma/BlackIsZero@value = "FALSE"
=> WhiteIsZero; "GRAY" and /Document/SubimageInterpretation@value =
"TransparencyMask" => TransparencyMask; "RGB" and /Chroma/Palette present =>
PaletteColor; "GRAY" => BlackIsZero; "RGB" => RGB; "YCbCr" => YCbCr;
"CMYK" => CMYK; "Lab" => CIELab.

2
SamplesPerPixel
/Chroma/NumChannels@value

3
ColorMap
/Chroma/Palette

4
Compression
/Compression/CompressionTypeName@value: "none" => Uncompressed;
"CCITT RLE" => CCITT 1D; "CCITT T.4" => Group 3 Fax; "CCITT T.6" => Group 4
Fax; "LZW" => LZW; "Old JPEG" => JPEG; "JPEG" => New JPEG; "ZLib" => ZLib;
"PackBits" => PackBits; "Deflate" => Deflate.

5
PlanarConfiguration
/Data/PlanarConfiguration@value: "PixelInterleaved" => Chunky;
"PlaneInterleaved" => Planar.

6
SampleFormat
/Data/SampleFormat@value: "SignedIntegral" => two's complement signed
integer data; "UnsignedIntegral" => unsigned integer data; "Real" =>
IEEE floating point data; "Index" => unsigned integer data.

7
BitsPerSample
/Data/BitsPerSample@value: space-separated list parsed to char array.

8
FillOrder
/Data/SampleMSB@value: if all values in space-separated list are 0s =>
right-to-left; otherwise => left-to-right.

9
XResolution
(10 / /Dimension/HorizontalPixelSize@value) or
(10 / (/Dimension/VerticalPixelSize@value *
/Dimension/PixelAspectRatio@value))

10
YResolution
(10 / /Dimension/VerticalPixelSize@value) or
(10 / (/Dimension/HorizontalPixelSize@value /
/Dimension/PixelAspectRatio@value))

11
ResolutionUnit
Centimeter if XResolution or YResolution set; otherwise None.

12
Orientation
/Dimension/ImageOrientation@value

13
XPosition
/Dimension/HorizontalPosition@value / 10

14
YPosition
/Dimension/VerticalPosition@value / 10

15
NewSubFileType
/Document/SubimageInterpretation@value: "TransparencyMask" =>
transparency mask; "ReducedResolution" => reduced-resolution;
"SinglePage" => single page.

16
DateTime
/Document/ImageCreationTime@value

17
DocumentName, ImageDescription, Make, Model, PageName, Software,
Artist, HostComputer, InkNames, Copyright
/Text/TextEntry: if /Text/TextEntry@keyword is the name of any of the
TIFF Fields, e.g., "Software", then the field is added with content
/Text/TextEntry@value and count 1.

18
ExtraSamples
/Transparency/Alpha@value: "premultiplied" => associated alpha, count 1;
"nonpremultiplied" => unassociated alpha, count 1.

Writing Exif Images

The TIFF writer may be used to write an uncompressed Exif image or the
contents of the APP1 marker segment of a compressed Exif image.

Writing Uncompressed Exif Images

When writing a sequence of images each image is normally recorded as
{IFD, IFD Value, Image Data}. The Exif specification requires
that an uncompressed Exif image be structured as follows:

Image File Header

Primary IFD

Primary IFD Value

Thumbnail IFD

Thumbnail IFD Value

Thumbnail Image Data

Primary Image Data

To meet the requirement of the primary image data being recorded last, the
primary image must be written initially as an empty image and have its data
added via pixel replacement after the thumbnail IFD and image data have been
written:

    ImageWriter tiffWriter;
    ImageWriteParam tiffWriteParam;
    IIOMetadata tiffStreamMetadata;
    IIOMetadata primaryIFD;
    BufferedImage image;
    BufferedImage thumbnail;

    // Specify uncompressed output.
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_DISABLED);

    if (thumbnail != null) {
        // Write the TIFF header.
        tiffWriter.prepareWriteSequence(tiffStreamMetadata);

        // Append the primary IFD.
        tiffWriter.prepareInsertEmpty(-1, // append
                new ImageTypeSpecifier(image),
                image.getWidth(),
                image.getHeight(),
                primaryIFD,
                null, // thumbnails
                tiffWriteParam);
        tiffWriter.endInsertEmpty();

        // Append the thumbnail image data.
        tiffWriter.writeToSequence(new IIOImage(thumbnail, null, null),
                tiffWriteParam);

        // Insert the primary image data.
        tiffWriter.prepareReplacePixels(0, new Rectangle(image.getWidth(),
                image.getHeight()));
        tiffWriter.replacePixels(image, tiffWriteParam);
        tiffWriter.endReplacePixels();

        // End writing.
        tiffWriter.endWriteSequence();
    } else {
        // Write only the primary IFD and image data.
        tiffWriter.write(tiffStreamMetadata,
                new IIOImage(image, null, primaryIFD),
                tiffWriteParam);
    }

Writing Compressed Exif Images

The structure of the embedded TIFF stream in the APP1 segment of a
compressed Exif image is identical to the
uncompressed Exif image structure except that there are no primary
image data, i.e., the primary IFD does not refer to any image data.

    ImageWriter tiffWriter;
    ImageWriteParam tiffWriteParam;
    IIOMetadata tiffStreamMetadata;
    BufferedImage image;
    BufferedImage thumbnail;
    IIOMetadata primaryIFD;
    ImageOutputStream output;

    // Set up an output to contain the APP1 Exif TIFF stream.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    MemoryCacheImageOutputStream app1ExifOutput =
        new MemoryCacheImageOutputStream(baos);
    tiffWriter.setOutput(app1ExifOutput);

    // Set compression for the thumbnail.
    tiffWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    tiffWriteParam.setCompressionType("Exif JPEG");

    // Write the APP1 Exif TIFF stream.
    if (thumbnail != null) {
        // Write the TIFF header.
        tiffWriter.prepareWriteSequence(tiffStreamMetadata);

        // Append the primary IFD.
        tiffWriter.prepareInsertEmpty(-1, // append
                new ImageTypeSpecifier(image),
                image.getWidth(),
                image.getHeight(),
                primaryIFD,
                null, // thumbnails
                tiffWriteParam);
        tiffWriter.endInsertEmpty();

        // Append the thumbnail IFD and image data.
        tiffWriter.writeToSequence(new IIOImage(thumbnail, null,
                null), tiffWriteParam);

        // End writing.
        tiffWriter.endWriteSequence();
    } else {
        // Write only the primary IFD.
        tiffWriter.prepareWriteEmpty(tiffStreamMetadata,
                new ImageTypeSpecifier(image),
                image.getWidth(),
                image.getHeight(),
                primaryIFD,
                null, // thumbnails
                tiffWriteParam);
        tiffWriter.endWriteEmpty();
    }

    // Flush data into byte stream.
    app1ExifOutput.flush();

    // Create APP1 parameter array.
    byte[] app1Parameters = new byte[6 + baos.size()];

    // Add APP1 Exif ID bytes.
    app1Parameters[0] = (byte) 'E';
    app1Parameters[1] = (byte) 'x';
    app1Parameters[2] = (byte) 'i';
    app1Parameters[3] = (byte) 'f';
    app1Parameters[4] = app1Parameters[5] = (byte) 0;

    // Append TIFF stream to APP1 parameters.
    System.arraycopy(baos.toByteArray(), 0, app1Parameters, 6, baos.size());

    // Create the APP1 Exif node to be added to native JPEG image metadata.
    IIOMetadataNode app1Node = new IIOMetadataNode("unknown");
    app1Node.setAttribute("MarkerTag", String.valueOf(0xE1));
    app1Node.setUserObject(app1Parameters);

    // Append the APP1 Exif marker to the "markerSequence" node.
    IIOMetadata jpegImageMetadata =
        jpegWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image),
            jpegWriteParam);
    String nativeFormat = jpegImageMetadata.getNativeMetadataFormatName();
    Node tree = jpegImageMetadata.getAsTree(nativeFormat);
    NodeList children = tree.getChildNodes();
    int numChildren = children.getLength();
    for (int i = 0; i < numChildren; i++) {
        Node child = children.item(i);
        if (child.getNodeName().equals("markerSequence")) {
            child.appendChild(app1Node);
            break;
        }
    }
    jpegImageMetadata.setFromTree(nativeFormat, tree);

    // Write the JPEG image data including the APP1 Exif marker.
    jpegWriter.setOutput(output);
    jpegWriter.write(new IIOImage(image, null, jpegImageMetadata));

The "unknown" node created above would be appended to the
"markerSequence" node of the native JPEG image metadata
and written to the JPEG stream when the primary image is written using
the JPEG writer.

Stream Metadata

The DTD for the TIFF native stream metadata format is as follows:

<!DOCTYPE "javax_imageio_tiff_stream_1.0" [

  <!ELEMENT "javax_imageio_tiff_stream_1.0" (ByteOrder)>

    <!ELEMENT "ByteOrder" EMPTY>
      <!-- The stream byte order -->
      <!ATTLIST "ByteOrder" "value" #CDATA #REQUIRED>
        <!-- One of "BIG_ENDIAN" or "LITTLE_ENDIAN" -->
        <!-- Data type: String -->
]>

Image Metadata

The DTD for the TIFF native image metadata format is as follows:

<!DOCTYPE "javax_imageio_tiff_image_1.0" [

  <!ELEMENT "javax_imageio_tiff_image_1.0" (TIFFIFD)*>

    <!ELEMENT "TIFFIFD" (TIFFField | TIFFIFD)*>
      <!-- An IFD (directory) containing fields -->
      <!ATTLIST "TIFFIFD" "tagSets" #CDATA #REQUIRED>
        <!-- Data type: String -->
      <!ATTLIST "TIFFIFD" "parentTagNumber" #CDATA #IMPLIED>
        <!-- The tag number of the field pointing to this IFD -->
        <!-- Data type: Integer -->
      <!ATTLIST "TIFFIFD" "parentTagName" #CDATA #IMPLIED>
        <!-- A mnemonic name for the field pointing to this IFD, if known
             -->
        <!-- Data type: String -->

      <!ELEMENT "TIFFField" (TIFFBytes | TIFFAsciis |
        TIFFShorts | TIFFSShorts | TIFFLongs | TIFFSLongs |
        TIFFRationals | TIFFSRationals |
        TIFFFloats | TIFFDoubles | TIFFUndefined)>
        <!-- A field containing data -->
        <!ATTLIST "TIFFField" "number" #CDATA #REQUIRED>
          <!-- The tag number asociated with the field -->
          <!-- Data type: String -->
        <!ATTLIST "TIFFField" "name" #CDATA #IMPLIED>
          <!-- A mnemonic name associated with the field, if known -->
          <!-- Data type: String -->

        <!ELEMENT "TIFFBytes" (TIFFByte)*>
          <!-- A sequence of TIFFByte nodes -->

          <!ELEMENT "TIFFByte" EMPTY>
            <!-- An integral value between 0 and 255 -->
            <!ATTLIST "TIFFByte" "value" #CDATA #IMPLIED>
              <!-- The value -->
              <!-- Data type: String -->
            <!ATTLIST "TIFFByte" "description" #CDATA #IMPLIED>
              <!-- A description, if available -->
              <!-- Data type: String -->

        <!ELEMENT "TIFFAsciis" (TIFFAscii)*>
          <!-- A sequence of TIFFAscii nodes -->

          <!ELEMENT "TIFFAscii" EMPTY>
            <!-- A String value -->
            <!ATTLIST "TIFFAscii" "value" #CDATA #IMPLIED>
              <!-- The value -->
              <!-- Data type: String -->

        <!ELEMENT "TIFFShorts" (TIFFShort)*>
          <!-- A sequence of TIFFShort nodes -->

          <!ELEMENT "TIFFShort" EMPTY>
            <!-- An integral value between 0 and 65535 -->
            <!ATTLIST "TIFFShort" "value" #CDATA #IMPLIED>
              <!-- The value -->
              <!-- Data type: String -->
            <!ATTLIST "TIFFShort" "description" #CDATA #IMPLIED>
              <!-- A description, if available -->
              <!-- Data type: String -->

        <!ELEMENT "TIFFSShorts" (TIFFSShort)*>
          <!-- A sequence of TIFFSShort nodes -->

          <!ELEMENT "TIFFSShort" EMPTY>
            <!-- An integral value between -32768 and 32767 -->
            <!ATTLIST "TIFFSShort" "value" #CDATA #IMPLIED>
              <!-- The value -->
              <!-- Data type: String -->
            <!ATTLIST "TIFFSShort" "description" #CDATA #IMPLIED>
              <!-- A description, if available -->
              <!-- Data type: String -->

        <!ELEMENT "TIFFLongs" (TIFFLong)*>
          <!-- A sequence of TIFFLong nodes -->

          <!ELEMENT "TIFFLong" EMPTY>
            <!-- An integral value between 0 and 4294967295 -->
            <!ATTLIST "TIFFLong" "value" #CDATA #IMPLIED>
              <!-- The value -->
              <!-- Data type: String -->
            <!ATTLIST "TIFFLong" "description" #CDATA #IMPLIED>
              <!-- A description, if available -->
              <!-- Data type: String -->

        <!ELEMENT "TIFFSLongs" (TIFFSLong)*>
          <!-- A sequence of TIFFSLong nodes -->

          <!ELEMENT "TIFFSLong" EMPTY>
            <!-- An integral value between -2147483648 and 2147482647 -->
            <!ATTLIST "TIFFSLong" "value" #CDATA #IMPLIED>
              <!-- The value -->
              <!-- Data type: String -->
            <!ATTLIST "TIFFSLong" "description" #CDATA #IMPLIED>
              <!-- A description, if available -->
              <!-- Data type: String -->

        <!ELEMENT "TIFFRationals" (TIFFRational)*>
          <!-- A sequence of TIFFRational nodes -->

          <!ELEMENT "TIFFRational" EMPTY>
            <!-- A rational value consisting of an unsigned numerator and
                 denominator -->
            <!ATTLIST "TIFFRational" "value" #CDATA #IMPLIED>
              <!-- The numerator and denominator, separated by a slash -->
              <!-- Data type: String -->

        <!ELEMENT "TIFFSRationals" (TIFFSRational)*>
          <!-- A sequence of TIFFSRational nodes -->

          <!ELEMENT "TIFFSRational" EMPTY>
            <!-- A rational value consisting of a signed numerator and
                 denominator -->
            <!ATTLIST "TIFFSRational" "value" #CDATA #IMPLIED>
              <!-- The numerator and denominator, separated by a slash -->
              <!-- Data type: String -->

        <!ELEMENT "TIFFFloats" (TIFFFloat)*>
          <!-- A sequence of TIFFFloat nodes -->

          <!ELEMENT "TIFFFloat" EMPTY>
            <!-- A single-precision floating-point value -->
            <!ATTLIST "TIFFFloat" "value" #CDATA #IMPLIED>
              <!-- The value -->
              <!-- Data type: String -->

        <!ELEMENT "TIFFDoubles" (TIFFDouble)*>
          <!-- A sequence of TIFFDouble nodes -->

          <!ELEMENT "TIFFDouble" EMPTY>
            <!-- A double-precision floating-point value -->
            <!ATTLIST "TIFFDouble" "value" #CDATA #IMPLIED>
              <!-- The value -->
              <!-- Data type: String -->

        <!ELEMENT "TIFFUndefined" EMPTY>
          <!-- Uninterpreted byte data -->
          <!ATTLIST "TIFFUndefined" "value" #CDATA #IMPLIED>
            <!-- A list of comma-separated byte values -->
            <!-- Data type: String -->
]>

@since 9


text:
cask "epichrome" do
  version "2.3.21"
  sha256 "ab279ff9dd9865dd8598b0919bfe558aa97fba3b2b1ad3a07767ea1e09b3b55f"

  url "https://github.com/dmarmor/epichrome/releases/download/v#{version}/epichrome-#{version}.pkg"
  appcast "https://github.com/dmarmor/epichrome/releases.atom"
  name "Epichrome"
  desc "Tool to create web-based applications that work like standalone apps"
  homepage "https://github.com/dmarmor/epichrome"

  pkg "epichrome-#{version}.pkg"

  uninstall pkgutil: "org.epichrome.Epichrome"
end

redpajama_set_name: RedPajamaGithub


text:
<template>
	Detail.
</template>


text:
package org.jkiss.dbeaver.ui.navigator.database;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.TreeEditor;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.progress.WorkbenchJob;
import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.DBeaverPreferences;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.core.DBeaverUI;
import org.jkiss.dbeaver.model.navigator.*;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.runtime.DBRRunnableWithResult;
import org.jkiss.dbeaver.ui.AbstractUIJob;
import org.jkiss.dbeaver.ui.ActionUtils;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.actions.navigator.NavigatorHandlerObjectRename;
import org.jkiss.dbeaver.ui.navigator.NavigatorUtils;
import org.jkiss.utils.ArrayUtils;
import org.jkiss.utils.CommonUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

public class DatabaseNavigatorTree extends Composite implements INavigatorListener
{
    private static final Log log = Log.getLog(DatabaseNavigatorTree.class);

    private TreeViewer treeViewer;
    private DBNModel model;
    private TreeEditor treeEditor;
    private boolean checkEnabled;
    private ISelection defaultSelection;
    private IFilter navigatorFilter;

    public DatabaseNavigatorTree(Composite parent, DBNNode rootNode, int style)
    {
        this(parent, rootNode, style, false);
    }

    public DatabaseNavigatorTree(Composite parent, DBNNode rootNode, int style, boolean showRoot) {
        this(parent, rootNode, style, showRoot, null);
    }

    public DatabaseNavigatorTree(Composite parent, DBNNode rootNode, int style, boolean showRoot, IFilter navigatorFilter)
    {
        super(parent, SWT.NONE);
        this.setLayout(new FillLayout());
        this.navigatorFilter = navigatorFilter;
        this.defaultSelection = new StructuredSelection(rootNode);
        this.model = DBeaverCore.getInstance().getNavigatorModel();
        this.model.addListener(this);
        addDisposeListener(new DisposeListener() {
            @Override
            public void widgetDisposed(DisposeEvent e)
            {
                if (model != null) {
                    model.removeListener(DatabaseNavigatorTree.this);
                    model = null;
                }
            }
        });

        treeViewer = doCreateTreeViewer(this, style);

        treeViewer.getTree().setCursor(getDisplay().getSystemCursor(SWT.CURSOR_ARROW));
        treeViewer.setUseHashlookup(true);
        if (rootNode.getParentNode() == null) {
            //this.treeViewer.setAutoExpandLevel(2);
        }
        treeViewer.setLabelProvider(new DatabaseNavigatorLabelProvider(treeViewer));
        treeViewer.setContentProvider(new DatabaseNavigatorContentProvider(this, showRoot));

        treeViewer.setInput(new DatabaseNavigatorContent(rootNode));

        ColumnViewerToolTipSupport.enableFor(treeViewer);

        initEditor();
    }

    private TreeViewer doCreateTreeViewer(Composite parent, int style) {
        checkEnabled = (style & SWT.CHECK) != 0;

        // Create tree
        int treeStyle = SWT.H_SCROLL | SWT.V_SCROLL | style;
        if (checkEnabled) {
            return new CheckboxTreeViewer(parent, treeStyle);
        } else {
            if (navigatorFilter != null) {
                CustomFilteredTree filteredTree = new CustomFilteredTree(this, treeStyle);
                return filteredTree.getViewer();
            } else {
                return doCreateNavigatorTreeViewer(parent, style);
            }
        }
    }

    private TreeViewer doCreateNavigatorTreeViewer(Composite parent, int style) {
        return new TreeViewer(parent, style) {
            @Override
            public ISelection getSelection() {
                ISelection selection = super.getSelection();
                return selection.isEmpty() && defaultSelection != null ? defaultSelection : selection;
            }
            protected void handleTreeExpand(TreeEvent event) {
                // Disable redraw during expand (its blinking)
                getTree().setRedraw(false);
                try {
                    super.handleTreeExpand(event);
                } finally {
                    getTree().setRedraw(true);
                }
            }
            protected void handleTreeCollapse(TreeEvent event) {
                getTree().setRedraw(false);
                try {
                    super.handleTreeCollapse(event);
                } finally {
                    getTree().setRedraw(true);
                }
            }
        };
    }

    public DBNNode getModel()
    {
        DatabaseNavigatorContent content = (DatabaseNavigatorContent) this.treeViewer.getInput();
        return content.getRootNode();
    }

    private void initEditor()
    {
        Tree treeControl = this.treeViewer.getTree();

        treeEditor = new TreeEditor(treeControl);
        treeEditor.horizontalAlignment = SWT.LEFT;
        treeEditor.verticalAlignment = SWT.TOP;
        treeEditor.grabHorizontal = false;
        treeEditor.minimumWidth = 50;

        //treeControl.addSelectionListener(new TreeSelectionAdapter());
        if (!checkEnabled) {
            // Add rename listener only for non CHECK trees
            treeControl.addMouseListener(new TreeSelectionAdapter());
        }
    }

    @NotNull
    public TreeViewer getViewer()
    {
        return treeViewer;
    }

    @Override
    public void nodeChanged(final DBNEvent event)
    {
        switch (event.getAction()) {
            case ADD:
            case REMOVE: {
                final DBNNode node = event.getNode();
                final DBNNode parentNode = node.getParentNode();
                if (parentNode != null) {
                    DBeaverUI.syncExec(new Runnable() {
                        @Override
                        public void run() {
                            if (!treeViewer.getControl().isDisposed()) {
                                if (!parentNode.isDisposed()) {
                                    treeViewer.refresh(getViewerObject(parentNode));
                                    if (event.getNodeChange() == DBNEvent.NodeChange.SELECT) {
                                        treeViewer.reveal(node);
                                        treeViewer.setSelection(new StructuredSelection(node));
                                    }
                                }
                            }
                        }
                    });
                }
                break;
            }
            case UPDATE:
                DBeaverUI.syncExec(new NodeUpdater(event));
                break;
            default:
                break;
        }
    }

    private void expandNodeOnLoad(final DBNNode node)
    {
        if (node instanceof DBNDataSource && DBeaverCore.getGlobalPreferenceStore().getBoolean(DBeaverPreferences.NAVIGATOR_EXPAND_ON_CONNECT)) {
            try {
                DBRRunnableWithResult<DBNNode> runnable = new DBRRunnableWithResult<DBNNode>() {
                    @Override
                    public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException
                    {
                        try {
                            result = findActiveNode(monitor, node);
                        } catch (DBException e) {
                            throw new InvocationTargetException(e);
                        }
                    }
                };
                DBeaverUI.runInProgressService(runnable);
                if (runnable.getResult() != null) {
                    showNode(runnable.getResult());
                    treeViewer.expandToLevel(runnable.getResult(), 1);
                }
            } catch (InvocationTargetException e) {
                log.error("Can't expand node", e.getTargetException());
            } catch (InterruptedException e) {
                // skip it
            }
        }
    }

    private DBNNode findActiveNode(DBRProgressMonitor monitor, DBNNode node) throws DBException
    {
        DBNNode[] children = node.getChildren(monitor);
        if (!ArrayUtils.isEmpty(children)) {
            if (children[0] instanceof DBNContainer) {
                // Use only first folder to search
                return findActiveNode(monitor, children[0]);
            }
            for (DBNNode child : children) {
                if (NavigatorUtils.isDefaultElement(child)) {
                    return child;
                }
            }
        }

        return node;
    }

    Object getViewerObject(DBNNode node)
    {
        if (((DatabaseNavigatorContent) treeViewer.getInput()).getRootNode() == node) {
            return treeViewer.getInput();
        } else {
            return node;
        }
    }

    public void showNode(DBNNode node) {
        treeViewer.reveal(node);
        treeViewer.setSelection(new StructuredSelection(node));
    }

    public void reloadTree(final DBNNode rootNode)
    {
        DatabaseNavigatorTree.this.treeViewer.setInput(new DatabaseNavigatorContent(rootNode));
    }

    private class TreeSelectionAdapter implements MouseListener {

        private volatile TreeItem curSelection;
        private volatile RenameJob renameJob = new RenameJob();

        private volatile boolean doubleClick = false;

        @Override
        public synchronized void mouseDoubleClick(MouseEvent e)
        {
            curSelection = null;
            renameJob.canceled = true;
        }

        @Override
        public void mouseDown(MouseEvent e)
        {
        }

        @Override
        public void mouseUp(MouseEvent e)
        {
            if ((e.stateMask & SWT.BUTTON1) == 0) {
                curSelection = null;
                return;
            }
            changeSelection(e);
        }

        public void changeSelection(MouseEvent e) {
            disposeOldEditor();
            final TreeItem newSelection = treeViewer.getTree().getItem(new Point(e.x, e.y));
            if (newSelection == null) {
                return;
            }

            if (!(newSelection.getData() instanceof DBNNode) ||
                !(ActionUtils.isCommandEnabled(IWorkbenchCommandConstants.FILE_RENAME, DBeaverUI.getActiveWorkbenchWindow().getActivePage().getActivePart().getSite()))) {
                curSelection = null;
                return;
            }
            if (curSelection != null && curSelection == newSelection && renameJob.selection == null) {
                renameJob.selection = curSelection;
                renameJob.schedule(1000);
            }
            curSelection = newSelection;
        }

        private class RenameJob extends AbstractUIJob {
            private volatile boolean canceled = false;
            public TreeItem selection;

            public RenameJob()
            {
                super("Rename ");
            }

            @Override
            protected IStatus runInUIThread(DBRProgressMonitor monitor)
            {
                try {
                    if (!treeViewer.getTree().isDisposed() && treeViewer.getTree().isFocusControl() && curSelection == selection && !canceled) {
                        final TreeItem itemToRename = selection;
                        DBeaverUI.asyncExec(new Runnable() {
                            @Override
                            public void run() {
                                renameItem(itemToRename);
                            }
                        });
                    }
                } finally {
                    canceled = false;
                    selection = null;
                }
                return Status.OK_STATUS;
            }

        }
    }

    private void renameItem(final TreeItem item)
    {
        // Clean up any previous editor control
        disposeOldEditor();
        if (item.isDisposed()) {
            return;
        }
        final DBNNode node = (DBNNode) item.getData();

        Text text = new Text(treeViewer.getTree(), SWT.BORDER);
        text.setText(node.getNodeName());
        text.selectAll();
        text.setFocus();
        text.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e)
            {
                disposeOldEditor();
            }
        });
        text.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e)
            {
                if (e.keyCode == SWT.CR) {
                    Text text = (Text) treeEditor.getEditor();
                    final String newName = text.getText();
                    disposeOldEditor();
                    treeViewer.getTree().setFocus();
                    if (!CommonUtils.isEmpty(newName) && !newName.equals(node.getNodeName())) {
                        NavigatorHandlerObjectRename.renameNode(DBeaverUI.getActiveWorkbenchWindow(), node, newName);
                    }
                } else if (e.keyCode == SWT.ESC) {
                    disposeOldEditor();
                    treeViewer.getTree().setFocus();
                }
            }
        });
        final Rectangle itemBounds = item.getBounds(0);
        final Rectangle treeBounds = treeViewer.getTree().getBounds();
        treeEditor.minimumWidth = Math.max(itemBounds.width, 50);
        treeEditor.minimumWidth = Math.min(treeEditor.minimumWidth, treeBounds.width - (itemBounds.x - treeBounds.x) - item.getImageBounds(0).width - 4);

        treeEditor.setEditor(text, item, 0);
    }

    private void disposeOldEditor()
    {
        Control oldEditor = treeEditor.getEditor();
        if (oldEditor != null) oldEditor.dispose();
    }

    ////////////////////////////////////////////////////////////////////////////
    // Filtered tree

    private static class TreeFilter extends PatternFilter {
        private final IFilter filter;
        TreeFilter(IFilter filter) {
            setIncludeLeadingWildcard(true);
            this.filter = filter;
        }

        public Object[] filter(Viewer viewer, Object parent, Object[] elements) {
            int size = elements.length;
            ArrayList<Object> out = new ArrayList<>(size);
            for (int i = 0; i < size; ++i) {
                Object element = elements[i];
                if (select(viewer, parent, element)) {
                    out.add(element);
                }
            }
            return out.toArray();
        }

        public boolean isElementVisible(Viewer viewer, Object element){
            if (filter.select(element)) {
                return true;
            }
            return super.isLeafMatch(viewer, element);
        }

    }

    private static class CustomFilteredTree extends FilteredTree {
        CustomFilteredTree(DatabaseNavigatorTree navigatorTree, int treeStyle) {
            super(navigatorTree, treeStyle, new TreeFilter(navigatorTree.navigatorFilter), true);
            setInitialText("Type table/view name to filter");
            ((GridLayout)getLayout()).verticalSpacing = 0;

            UIUtils.addDefaultEditActionsSupport(DBeaverUI.getActiveWorkbenchWindow(), getFilterControl());
        }

        @Override
        protected TreeViewer doCreateTreeViewer(Composite parent, int style) {
            return ((DatabaseNavigatorTree)getParent()).doCreateNavigatorTreeViewer(parent, style);
        }

        protected WorkbenchJob doCreateRefreshJob() {
            return new WorkbenchJob("Refresh Filter") {//$NON-NLS-1$
                @Override
                public IStatus runInUIThread(IProgressMonitor monitor) {
                    if (treeViewer.getControl().isDisposed()) {
                        return Status.CANCEL_STATUS;
                    }

                    String text = getFilterString();
                    if (text == null) {
                        return Status.OK_STATUS;
                    }
                    boolean initial = initialText != null && initialText.equals(text);
                    if (initial) {
                        getPatternFilter().setPattern(null);
                    } else {
                        getPatternFilter().setPattern(text);
                    }

                    final Control redrawFalseControl = treeComposite != null ? treeComposite
                            : treeViewer.getControl();
                    try {
                        // don't want the user to see updates that will be made to
                        // the tree
                        // we are setting redraw(false) on the composite to avoid
                        // dancing scrollbar
                        redrawFalseControl.setRedraw(false);
                        treeViewer.refresh(true);

                        if (text.length() > 0 && !initial) {
                            // enabled toolbar - there is text to clear
                            // and the list is currently being filtered
                            updateToolbar(true);
                        } else {
                            // disabled toolbar - there is no text to clear
                            // and the list is currently not filtered
                            updateToolbar(false);
                        }
                    } finally {
                        // done updating the tree - set redraw back to true
                        redrawFalseControl.setRedraw(true);
                    }

                    return Status.OK_STATUS;
                }
            };
        }
    }

    private class NodeUpdater implements Runnable {
        private final DBNEvent event;
        NodeUpdater(DBNEvent event) {
            this.event = event;
        }
        @Override
        public void run() {
            if (!treeViewer.getControl().isDisposed() && !treeViewer.isBusy()) {
                if (event.getNode() != null) {
                    switch (event.getNodeChange()) {
                        case LOAD:
                            treeViewer.refresh(getViewerObject(event.getNode()));
                            expandNodeOnLoad(event.getNode());
                            break;
                        case UNLOAD:
                            treeViewer.collapseToLevel(event.getNode(), -1);
                            treeViewer.refresh(getViewerObject(event.getNode()));
                            break;
                        case REFRESH:
                            treeViewer.refresh(getViewerObject(event.getNode()), true);
                            break;
                        case LOCK:
                        case UNLOCK:
                        case STRUCT_REFRESH:
                            treeViewer.refresh(getViewerObject(event.getNode()));
                            break;
                    }
                } else {
                    log.warn("Null node object");
                }
            }
        }
    }
}


text:
require 'simplecov'

SimpleCov.start

$LOAD_PATH.unshift File.expand_path('../lib', __dir__)
require 'front_matter_parser'
require 'pry-byebug'
Dir["#{File.expand_path('support', __dir__)}/*.rb"].each do |file|
  require file
end


text:
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { InfoPessoalMedicoPage } from './info-pessoal-medico';

@NgModule({
  declarations: [
    InfoPessoalMedicoPage,
  ],
  imports: [
    IonicPageModule.forChild(InfoPessoalMedicoPage),
  ],
})
export class InfoPessoalMedicoPageModule {}


text:
//this page defines the schema for RentalPoint  db model
var mongoose = require('mongoose');
var rental_point_schema = new mongoose.Schema({
  lat:{ type:Number, max: 85, min:-85} ,
  lng:{ type:Number, max:180, min:-180},
  beds: {type:Number, min:0, max:20},
  baths:{type:Number, min:0, max:20},
  price_single: {type:Number, min:0},
  price_total : {type:Number, min:0},
  cat:{type:Number, min:1,max:4}, // 1 : sublease, 2:want to lease, 3: find roommate(includes finding colease)
  post_date: Date,
  isexpired:Boolean,
  community:String,
  source:String,
  memo:String,
  addr:String
}, { collection: 'rentalpoint' }
);

/* validation area begin */
/*
rental_point_schema.path('community').validate( function(value){
  return value.length <= 120;
},"too many chars in community attr");
*/
/* validation area end*/

rental_point_schema.static({
  list: function(callback) {
    this.find({} , null, {sort:{_id:-1}}, callback);
  }
});

module.exports = mongoose.model('RentalPoint',rental_point_schema);
/*
for RentalPoint
----
_id:number
lat: number
lng: number
----
beds:number
baths:number
----
price_single_room:number
price_total:number
----
cat:number // 1 : sublease, 2:want to lease, 3: find roommate(includes finding colease)
post_date: date
isexpired:  boolean
---
community: string
source: url_string
memo: string  // content at original post
addr:string
*/


text:
<?php

class Qrz_Indexer_Block_Adminhtml_Indexer_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

    /**  @var string */
    protected $_massactionBlockName = 'qrz_indexer/adminhtml_indexer_grid_massaction';

    /**
     * @author Cristian Quiroz <cris@qrz.io>
     */
    public function __construct()
    {
        parent::__construct();
        $this->setId('qdev_indexer_processes_grid');
        $this->_filterVisibility = false;
        $this->_pagerVisibility = false;
    }

    /**
     * @return Qrz_Indexer_Block_Adminhtml_Indexer_Grid
     * @author Cristian Quiroz <cris@qrz.io>
     */
    protected function _prepareCollection()
    {
        $collection = $this->getQrzIndexerModel()->getIndexProcessCollection();
        $this->getQrzIndexerModel()->joinMViewMetadataToIndexProcessCollection($collection);
        $this->setCollection($collection);

        return parent::_prepareCollection();
    }

    /**
     * Add name and description to collection elements
     * @return Qrz_Indexer_Block_Adminhtml_Indexer_Grid
     * @author Cristian Quiroz <cris@qrz.io>
     */
    protected function _afterLoadCollection()
    {
        /** @var $item Mage_Index_Model_Process */
        foreach ($this->_collection as $key => $item) {
            if (!$item->getIndexer()->isVisible()) {
                $this->_collection->removeItemByKey($key);
                continue;
            }
            $item->setName($item->getIndexer()->getName());
            $item->setDescription($item->getIndexer()->getDescription());
            $item->setId($item->getIndexerCode());
        }

        $this->getQrzIndexerModel()->addLatestVersionIdToIndexProcessCollection($this->_collection);

        return parent::_afterLoadCollection();
    }

    /**
     * Prepare grid columns
     * @return Qrz_Indexer_Block_Adminhtml_Indexer_Grid
     * @author Cristian Quiroz <cris@qrz.io>
     */
    protected function _prepareColumns()
    {
        $this->addColumn(
            'indexer_code',
            array(
                'header'   => Mage::helper('index')->__('Index'),
                'width'    => '180',
                'align'    => 'left',
                'index'    => 'name',
                'sortable' => false,
            )
        );

        $this->addColumn(
            'description',
            array(
                'header'   => Mage::helper('index')->__('Description'),
                'align'    => 'left',
                'index'    => 'description',
                'sortable' => false,
            )
        );

        $this->addColumn(
            'max_version_id',
            array(
                'header'   => Mage::helper('index')->__('Newest version ID'),
                'align'    => 'left',
                'index'    => 'max_version_id',
                'sortable' => false,
            )
        );

        $this->addColumn(
            'version_id',
            array(
                'header'   => Mage::helper('index')->__('Last processed version ID'),
                'align'    => 'left',
                'index'    => 'version_id',
                'sortable' => false,
            )
        );

        $this->addColumn('action',
            array(
                'header'    => Mage::helper('index')->__('Action'),
                'width'     => '100',
                'type'      => 'action',
                'getter'    => 'getIndexerCode',
                'actions'   => array(
                    array(
                        'caption' => Mage::helper('index')->__('Reindex Now'),
                        'url'     => array('base' => '*/*/reindex'),
                        'field'   => 'indexer_code'
                    ),
                ),
                'filter'    => false,
                'sortable'  => false,
                'is_system' => true,
            )
        );

        return parent::_prepareColumns();
    }

    /**
     * @param mixed $row
     * @return null
     * @author Cristian Quiroz <cris@qrz.io>
     */
    public function getRowUrl($row)
    {
        return null;
    }

    /**
     * Add mass actions to grid
     * @return Qrz_Indexer_Block_Adminhtml_Indexer_Grid
     * @author Cristian Quiroz <cris@qrz.io>
     */
    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('qdev_indexer_id');
        $this->getMassactionBlock()->setFormFieldName('indexer_code');

        $this->getMassactionBlock()->addItem(
            'reindex',
            array(
                'label'    => Mage::helper('index')->__('Reindex Now'),
                'url'      => $this->getUrl('*/*/reindex'),
                'selected' => true,
            )
        );

        return $this;
    }

    /**
     * @return Qrz_Indexer_Model_Indexer
     * @author Cristian Quiroz <cris@qrz.io>
     */
    protected function getQrzIndexerModel()
    {
        return Mage::getSingleton('qrz_indexer/indexer');
    }
}


text:
class AddReadingGroupingSnapshot < ActiveRecord::Migration[5.2]
  def change
    create_table :reading_grouping_snapshots do |t|
      t.text :grouping_workspace_id, null: false
      t.integer :school_id, null: false
      t.text :grade, null: false
      t.integer :benchmark_school_year, null: false
      t.text :benchmark_period_key, null: false
      t.json :snapshot_json, null: false
      t.integer :educator_id, null: false
      t.timestamps
    end
    add_foreign_key :reading_grouping_snapshots, :schools
    add_foreign_key :reading_grouping_snapshots, :educators
  end
end


text:
const fs = require('fs');
const path = require('path');

let hasError = false;

processAll('pc-components');
processAll('common/components');
processAll('common/directive');

if (hasError) {
    console.error('Node env has no HTMLElement declaration, and the compiler will complain that if someone like awade ' +
        'uses Jigsaw in a Node env.');
    process.exit(1);
} else {
    console.error(`Everything's fine!`);
}

function processAll(folder) {
    const cmpHome = path.resolve(`${__dirname}/../../src/jigsaw/${folder}`);
    const cmpFolders = fs.readdirSync(cmpHome);
    cmpFolders.forEach(cmpFolder => {
        const pathname = path.join(cmpHome, cmpFolder);
        const stat = fs.lstatSync(pathname);
        if (stat.isDirectory()) {
            processSourceFiles(pathname);
        }
    });
}

function processSourceFiles(sourceFolder) {
    const files = fs.readdirSync(sourceFolder);
    files.forEach(file => {
        const pathname = path.join(sourceFolder, file);
        const stat = fs.lstatSync(pathname);
        if (stat.isDirectory()) {
            processSourceFiles(pathname)
        } else {
            checkInputProperty(pathname);
        }
    });
}

function checkInputProperty(srcPath) {
    if (!srcPath.match(/.+\.ts$/i)) {
        return;
    }

    const source = fs.readFileSync(srcPath).toString();
    source.replace(/@Input\s*\(\s*\)\s*(public)?\s*(\w+)\s*:\s*HTMLElement/g, (found, _, prop) => {
        error(`Input property ${prop}'s type can NOT be "HTMLElement"! Use type "any" instead!`);
    });
}

function error(msg) {
    console.error(msg);
    hasError = true;
}


text:
'use strict';

import nls = require('vs/nls');

import pfs = require('vs/base/node/pfs');

import URI from 'vs/base/common/uri';
import {TPromise} from 'vs/base/common/winjs.base';
import paths = require('vs/base/common/paths');
import {IExtensionService, IExtensionDescription} from 'vs/platform/extensions/common/extensions';
import {ExtensionsRegistry} from 'vs/platform/extensions/common/extensionsRegistry';
import {ExtHostAPIImplementation} from 'vs/workbench/api/node/extHost.api.impl';
import {IMainProcessExtHostIPC} from 'vs/platform/extensions/common/ipcRemoteCom';
import {ExtHostModelService} from 'vs/workbench/api/node/extHostDocuments';
import {IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import InstantiationService = require('vs/platform/instantiation/common/instantiationService');
import {ExtHostExtensionService} from 'vs/platform/extensions/common/nativeExtensionService';
import {ExtHostThreadService} from 'vs/platform/thread/common/extHostThreadService';
import {ExtHostTelemetryService} from 'vs/workbench/api/node/extHostTelemetry';
import {BaseRequestService} from 'vs/platform/request/common/baseRequestService';
import {BaseWorkspaceContextService} from 'vs/platform/workspace/common/baseWorkspaceContextService';
import {ModeServiceImpl} from 'vs/editor/common/services/modeServiceImpl';
import {ExtensionScanner, MessagesCollector} from 'vs/workbench/node/extensionPoints';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { Client } from 'vs/base/node/service.net';
import { IExtensionsService } from 'vs/workbench/parts/extensions/common/extensions';
import { ExtensionsService } from 'vs/workbench/parts/extensions/node/extensionsService';

const DIRNAME = URI.parse(require.toUrl('./')).fsPath;
const BASE_PATH = paths.normalize(paths.join(DIRNAME, '../../../..'));
const BUILTIN_EXTENSIONS_PATH = paths.join(BASE_PATH, 'extensions');

export interface IInitData {
	threadService: any;
	contextService: {
		workspace: any;
		configuration: any;
		options: any;
	};
}

const nativeExit = process.exit.bind(process);
process.exit = function() {
	const err = new Error('An extension called process.exit() and this was prevented.');
	console.warn((<any>err).stack);
};
export function exit(code?: number) {
	nativeExit(code);
}

export function createServices(remoteCom: IMainProcessExtHostIPC, initData: IInitData, sharedProcessClient: Client): IInstantiationService {

	let contextService = new BaseWorkspaceContextService(initData.contextService.workspace, initData.contextService.configuration, initData.contextService.options);
	let threadService = new ExtHostThreadService(remoteCom);
	threadService.setInstantiationService(InstantiationService.createInstantiationService({ threadService: threadService }));
	let telemetryService = new ExtHostTelemetryService(threadService);
	let requestService = new BaseRequestService(contextService, telemetryService);
	let modelService = threadService.getRemotable(ExtHostModelService);

	let extensionService = new ExtHostExtensionService(threadService, telemetryService);
	let modeService = new ModeServiceImpl(threadService, extensionService);
	let _services: any = {
		contextService: contextService,
		requestService: requestService,
		modelService: modelService,
		threadService: threadService,
		modeService: modeService,
		extensionService: extensionService,
		telemetryService: telemetryService
	};
	let instantiationService = InstantiationService.createInstantiationService(_services);
	threadService.setInstantiationService(instantiationService);

	// Create the monaco API
	instantiationService.createInstance(ExtHostAPIImplementation);

	// Connect to shared process services
	instantiationService.addSingleton(IExtensionsService, sharedProcessClient.getService<IExtensionsService>('ExtensionService', ExtensionsService));

	return instantiationService;
}

interface ITestRunner {
	run(testsRoot: string, clb: (error: Error, failures?: number) => void): void;
}

export class ExtensionHostMain {

	private _isTerminating: boolean;
	private _contextService: IWorkspaceContextService;
	private _extensionService: ExtHostExtensionService;

	constructor(
		@IWorkspaceContextService contextService: IWorkspaceContextService,
		@IExtensionService extensionService: IExtensionService
	) {
		this._isTerminating = false;
		this._contextService = contextService;
		this._extensionService = <ExtHostExtensionService>extensionService;
	}

	public start(): TPromise<void> {
		return this.readExtensions();
	}

	public terminate(): void {
		if (this._isTerminating) {
			// we are already shutting down...
			return;
		}
		this._isTerminating = true;

		try {
			let allExtensions = ExtensionsRegistry.getAllExtensionDescriptions();
			let allExtensionsIds = allExtensions.map(ext => ext.id);
			let activatedExtensions = allExtensionsIds.filter(id => this._extensionService.isActivated(id));

			activatedExtensions.forEach((extensionId) => {
				this._extensionService.deactivate(extensionId);
			});
		} catch (err) {
			// TODO: write to log once we have one
		}

		// Give extensions 1 second to wrap up any async dispose, then exit
		setTimeout(() => {
			exit();
		}, 1000);
	}

	private readExtensions(): TPromise<void> {
		let collector = new MessagesCollector();
		let env = this._contextService.getConfiguration().env;

		return ExtensionHostMain.scanExtensions(collector, BUILTIN_EXTENSIONS_PATH, !env.disableExtensions ? env.userExtensionsHome : void 0, !env.disableExtensions ? env.extensionDevelopmentPath : void 0, env.version)
			.then(null, err => {
				collector.error('', err);
				return [];
			})
			.then(extensions => {
				// Register & Signal done
				ExtensionsRegistry.registerExtensions(extensions);
				this._extensionService.registrationDone(collector.getMessages());
			})
			.then(() => this.handleEagerExtensions())
			.then(() => this.handleExtensionTests());
	}

	private static scanExtensions(collector: MessagesCollector, builtinExtensionsPath: string, userInstallPath: string, extensionDevelopmentPath: string, version: string): TPromise<IExtensionDescription[]> {
		const builtinExtensions = ExtensionScanner.scanExtensions(version, collector, builtinExtensionsPath, true);
		const userExtensions = !userInstallPath ? TPromise.as([]) : ExtensionScanner.scanExtensions(version, collector, userInstallPath, false);
		const developedExtensions = !extensionDevelopmentPath ? TPromise.as([]) : ExtensionScanner.scanOneOrMultipleExtensions(version, collector, extensionDevelopmentPath, false);

		return TPromise.join([builtinExtensions, userExtensions, developedExtensions]).then((_: IExtensionDescription[][]) => {
			let builtinExtensions = _[0];
			let userExtensions = _[1];
			let developedExtensions = _[2];

			let result: { [extensionId: string]: IExtensionDescription; } = {};
			builtinExtensions.forEach((builtinExtension) => {
				result[builtinExtension.id] = builtinExtension;
			});
			userExtensions.forEach((userExtension) => {
				if (result.hasOwnProperty(userExtension.id)) {
					collector.warn(userExtension.extensionFolderPath, nls.localize('overwritingExtension', "Overwriting extesion {0} with {1}.", result[userExtension.id].extensionFolderPath, userExtension.extensionFolderPath));
				}
				result[userExtension.id] = userExtension;
			});
			developedExtensions.forEach(developedExtension => {
				collector.info('', nls.localize('extensionUnderDevelopment', "Loading development extension at {0}", developedExtension.extensionFolderPath));
				if (result.hasOwnProperty(developedExtension.id)) {
					collector.warn(developedExtension.extensionFolderPath, nls.localize('overwritingExtension', "Overwriting extesion {0} with {1}.", result[developedExtension.id].extensionFolderPath, developedExtension.extensionFolderPath));
				}
				result[developedExtension.id] = developedExtension;
			});

			return Object.keys(result).map(name => result[name]);
		});
	}

	// Handle "eager" activation extensions
	private handleEagerExtensions(): TPromise<void> {
		this._extensionService.activateByEvent('*').then(null, (err) => {
			console.error(err);
		});
		return this.handleWorkspaceContainsEagerExtensions();
	}

	private handleWorkspaceContainsEagerExtensions(): TPromise<void> {
		let workspace = this._contextService.getWorkspace();
		if (!workspace || !workspace.resource) {
			return TPromise.as(null);
		}

		let folderPath = workspace.resource.fsPath;

		let desiredFilesMap: {
			[filename: string]: boolean;
		} = {};

		ExtensionsRegistry.getAllExtensionDescriptions().forEach((desc) => {
			let activationEvents = desc.activationEvents;
			if (!activationEvents) {
				return;
			}

			for (let i = 0; i < activationEvents.length; i++) {
				if (/^workspaceContains:/.test(activationEvents[i])) {
					let fileName = activationEvents[i].substr('workspaceContains:'.length);
					desiredFilesMap[fileName] = true;
				}
			}
		});

		return TPromise.join(
			Object.keys(desiredFilesMap).map(
				(fileName) => pfs.fileExistsWithResult(paths.join(folderPath, fileName), fileName)
			)
		).then((fileNames: string[]) => {
			fileNames.forEach((existingFileName) => {
				if (!existingFileName) {
					return;
				}

				let activationEvent = 'workspaceContains:' + existingFileName;
				this._extensionService.activateByEvent(activationEvent).then(null, (err) => {
					console.error(err);
				});
			});
		});
	}

	private handleExtensionTests(): TPromise<void> {
		let env = this._contextService.getConfiguration().env;
		if (!env.extensionTestsPath || !env.extensionDevelopmentPath) {
			return TPromise.as(null);
		}

		// Require the test runner via node require from the provided path
		let testRunner: ITestRunner;
		let requireError: Error;
		try {
			testRunner = <any>require.__$__nodeRequire(env.extensionTestsPath);
		} catch (error) {
			requireError = error;
		}

		// Execute the runner if it follows our spec
		if (testRunner && typeof testRunner.run === 'function') {
			return new TPromise<void>((c, e) => {
				testRunner.run(env.extensionTestsPath, (error, failures) => {
					if (error) {
						e(error.toString());
					} else {
						c(null);
					}

					// after tests have run, we shutdown the host
					this.gracefulExit(failures && failures > 0 ? 1 /* ERROR */ : 0 /* OK */);
				});
			});
		}

		// Otherwise make sure to shutdown anyway even in case of an error
		else {
			this.gracefulExit(1 /* ERROR */);
		}

		return TPromise.wrapError<void>(requireError ? requireError.toString() : nls.localize('extensionTestError', "Path {0} does not point to a valid extension test runner.", env.extensionTestsPath));
	}

	private gracefulExit(code: number): void {
		// to give the PH process a chance to flush any outstanding console
		// messages to the main process, we delay the exit() by some time
		setTimeout(() => exit(code), 500);
	}
}


text:
var gulp = require('gulp');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer-core');
var nano = require('gulp-cssnano');
var precss = require('precss');

gulp.task('default', ['browser-sync', 'watch']);


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.commsen.em.contractors</groupId>
		<artifactId>contractors</artifactId>
		<version>0.3.0-SNAPSHOT</version>
	</parent>

	<artifactId>em.contractors.pax-web-tomcat</artifactId>
	<version>6.0.7</version>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<!-- THIS -->
				<groupId>${project.groupId}</groupId>
				<artifactId>${project.artifactId}</artifactId>
				<version>${project.version}</version>
				<scope>runtime</scope>
			</dependency>
			<dependency>
				<groupId>org.ops4j.pax.web</groupId>
				<artifactId>pax-web-extender-whiteboard</artifactId>
				<version>6.0.7</version>
				<scope>runtime</scope>
			</dependency>
			<dependency>
				<groupId>org.apache.xbean</groupId>
				<artifactId>xbean-finder</artifactId>
				<version>4.1</version>
				<scope>runtime</scope>
			</dependency>
			<dependency>
				<groupId>org.ops4j.pax.web</groupId>
				<artifactId>pax-web-tomcat</artifactId>
				<version>6.0.7</version>
				<scope>runtime</scope>
			</dependency>
			<dependency>
				<groupId>org.ops4j.pax.web</groupId>
				<artifactId>pax-web-runtime</artifactId>
				<version>6.0.7</version>
				<scope>runtime</scope>
			</dependency>
			<dependency>
				<groupId>javax.el</groupId>
				<artifactId>javax.el-api</artifactId>
				<version>3.0.0</version>
				<scope>runtime</scope>
			</dependency>
			<dependency>
				<groupId>javax.transaction</groupId>
				<artifactId>javax.transaction-api</artifactId>
				<version>1.2</version>
				<scope>runtime</scope>
			</dependency>
			<dependency>
				<groupId>javax.interceptor</groupId>
				<artifactId>javax.interceptor-api</artifactId>
				<version>1.2.1</version>
				<scope>runtime</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

</project>


text:
<Type Name="AlignmentAttribute" FullName="MonoTouch.Dialog.AlignmentAttribute">
  <TypeSignature Language="C#" Value="public class AlignmentAttribute : Attribute" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit AlignmentAttribute extends System.Attribute" />
  <AssemblyInfo>
    <AssemblyName>MonoTouch.Dialog-1</AssemblyName>
    <AssemblyVersion>0.0.0.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>System.Attribute</BaseTypeName>
  </Base>
  <Interfaces />
  <Attributes>
    <Attribute>
      <AttributeName>System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Field | System.AttributeTargets.All, Inherited=false)</AttributeName>
    </Attribute>
  </Attributes>
  <Docs>
    <summary>Apply this attribute to properties and fields to instruct the BindingContext how it should align the text on the row.</summary>
    <remarks>
    </remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public AlignmentAttribute (MonoTouch.UIKit.UITextAlignment alignment);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(valuetype MonoTouch.UIKit.UITextAlignment alignment) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters>
        <Parameter Name="alignment" Type="MonoTouch.UIKit.UITextAlignment" />
      </Parameters>
      <Docs>
        <param name="alignment">The desired alignment.</param>
        <summary>
        </summary>
        <remarks>
        </remarks>
      </Docs>
    </Member>
    <Member MemberName="Alignment">
      <MemberSignature Language="C#" Value="public MonoTouch.UIKit.UITextAlignment Alignment;" />
      <MemberSignature Language="ILAsm" Value=".field public valuetype MonoTouch.UIKit.UITextAlignment Alignment" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>0.0.0.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>MonoTouch.UIKit.UITextAlignment</ReturnType>
      </ReturnValue>
      <Docs>
        <summary>
        </summary>
        <remarks>
        </remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
ccArray::Array getEmptyArray() {
    ccArray::Array ret;
    return ret;
}

ccArray::Array setArrayKeyValue(ccArray::Array array, std::string key, std::string value) {
    array[key] = value;
    return array;
}

TEST(ArraySimpleTests, ValueAssign) {
    ccArray::Array test;
    ASSERT_EQ(std::string("NULL"), test.toString()) << "Empty array to string NULL";

    test["testKey"] = "testValue";
    test["nested"]["nestedKey"] = "nestedValue";
    ASSERT_EQ(std::string("testValue"), (std::string)test["testKey"]) << "Get simple value from array";
    ASSERT_EQ(std::string("nestedValue"), (std::string)test["nested"]["nestedKey"]) << "Get nested value";
}

TEST(ArraySimpleTests, basicFunctions) {
    ccArray::Array test;
    test["testKey"] = "testValue";

    ASSERT_EQ(std::string("testValue"), test["testKey"].getValue()) << "Get simple value from array by getValue";
    ASSERT_EQ(std::string("testKey"), test["testKey"].getName()) << "Get simple value from array by getValue";
    ASSERT_FALSE(test["testKey"].hasChildrens());
    ASSERT_TRUE(test.hasChildrens());
    ASSERT_EQ(1, test.getChildrens().size());

    ASSERT_TRUE(test["not_exists"] == nullptr);
}

TEST(ArraySimpleTests, ArrayType) {
    ccArray::Array test;
    test["Hello"] = "World";

    test["array"]["nestedKey"] = "nestedValue";

    test["list"][""] = "value1";
    test["list"][""] = "value2";

    test["array2"][""] = "value1";
    test["array2"][""] = "value2";
    test["array2"]["asoc"] = "valueAsoc";

    ASSERT_EQ(ccArray::Array::TYPE_VALUE, test["Hello"].getType()) << "Test hello is value";
    ASSERT_EQ(ccArray::Array::TYPE_VALUE, test["array"]["nestedKey"].getType()) << "Test test[array][nestedKey] is value";

    ASSERT_EQ(ccArray::Array::TYPE_ARRAY, test["array"].getType()) << "Test test[array] is array";
    ASSERT_EQ(ccArray::Array::TYPE_ARRAY, test["array2"].getType()) << "Test test[array] is array";
    ASSERT_EQ(ccArray::Array::TYPE_LIST, test["list"].getType()) << "Test test[list] is list";;
}

TEST(ArraySimpleTests, EqualTest) {
    ccArray::Array test1;
    ccArray::Array test2;

    ASSERT_TRUE(test1 == test2);

    test1["key"] = "value";
    test2["key"] = "value";
    test1["assoc"]["test"] = "1";
    test2["assoc"]["test"] = "1";
    test1["list"][""] = "1";
    test2["list"][""] = "1";
    ASSERT_TRUE(test1 == test2);

    test2["list"][""] = "2";
    ASSERT_TRUE(test1 != test2);

    test2["list"]["asoc"] = "2";
    ASSERT_TRUE(test1 != test2);

    test2.unset("list");
    test2["list"][""] = "1";
    ASSERT_TRUE(test1 == test2);
}

TEST(ArraySimpleTests, ArrayToString) {
    ccArray::Array test;
    ASSERT_EQ("NULL", test.toString());
    test["Value"] = "value";
    ASSERT_EQ("value", test["Value"].toString());

    test["assoc"]["key"] = "value";
    ASSERT_EQ("Array", test["assoc"].toString());

    test["list"][""] = "value";
    ASSERT_EQ("Array", test["list"].toString());

}

TEST(ArraySimpleTests, functionTest) {
    ccArray::Array test;
    test = setArrayKeyValue(test, "key", "value");

    ASSERT_EQ(std::string("value"), (std::string)test["key"]) << "Get simple value from array";
}

    int main(int argc, char **argv) {
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
require 'spec_helper'

describe Annotation do
  describe :full_name do
    context "when parent_symbol given" do
      let(:annotation) {
        create(:annotation, :parent_symbol => 'CoP1', :symbol => '#1')
      }
      specify { annotation.full_symbol == 'CoP1#1' }
    end
    context "when event given" do
      let(:event) { create_cites_cop(:name => 'CoP1') }
      let(:annotation) {
        create(:annotation, :event_id => event.id, :symbol => '#1')
      }
      specify { annotation.full_symbol == 'CoP1#1' }
    end
  end
  describe :destroy do
    let(:annotation) { create(:annotation) }
    context "when no dependent objects attached" do
      specify { annotation.destroy.should be_truthy }
    end
    context "when dependent objects attached" do
      context "when listing changes" do
        let!(:listing_change) { create_cites_I_addition(:annotation_id => annotation.id) }
        specify { annotation.destroy.should be_falsey }
      end
      context "when hashed listing changes" do
        let!(:listing_change) { create_cites_I_addition(:hash_annotation_id => annotation.id) }
        specify { annotation.destroy.should be_falsey }
      end
    end
  end
end


text:
detection.py
============

.. automodule:: detection
    :members:
    :undoc-members:
    :show-inheritance:


text:
'use strict';
var vscode = require('vscode');
var cp = require('child_process');
var goPath_1 = require('./goPath');
var util_1 = require('./util');
function listPackages() {
    return new Promise(function (resolve, reject) {
        cp.execFile(goPath_1.getBinPath('gopkgs'), [], function (err, stdout, stderr) {
            if (err && err.code === 'ENOENT') {
                vscode.window.showInformationMessage('The "gopkgs" command is not available.  Use "go get github.com/tpng/gopkgs" to install.');
                return reject();
            }
            var lines = stdout.toString().split('\n');
            var sortedlines = lines.sort().slice(1); // Drop the empty entry from the final '\n'
            return resolve(sortedlines);
        });
    });
}
exports.listPackages = listPackages;
function askUserForImport() {
    return listPackages().then(function (packages) {
        return vscode.window.showQuickPick(packages);
    });
}
function addImport(arg) {
    var p = arg ? Promise.resolve(arg) : askUserForImport();
    p.then(function (imp) {
        // Import name wasn't provided
        if (imp === undefined) {
            return null;
        }
        var _a = util_1.parseFilePrelude(vscode.window.activeTextEditor.document.getText()), imports = _a.imports, pkg = _a.pkg;
        var multis = imports.filter(function (x) { return x.kind === 'multi'; });
        if (multis.length > 0) {
            // There is a multiple import declaration, add to the last one
            var closeParenLine_1 = multis[multis.length - 1].end;
            return vscode.window.activeTextEditor.edit(function (editBuilder) {
                editBuilder.insert(new vscode.Position(closeParenLine_1, 0), '\t"' + imp + '"\n');
            });
        }
        else if (imports.length > 0) {
            // There are only single import declarations, add after the last one
            var lastSingleImport_1 = imports[imports.length - 1].end;
            return vscode.window.activeTextEditor.edit(function (editBuilder) {
                editBuilder.insert(new vscode.Position(lastSingleImport_1 + 1, 0), 'import "' + imp + '"\n');
            });
        }
        else if (pkg && pkg.start >= 0) {
            // There are no import declarations, but there is a package declaration
            return vscode.window.activeTextEditor.edit(function (editBuilder) {
                editBuilder.insert(new vscode.Position(pkg.start + 1, 0), '\nimport (\n\t"' + imp + '"\n)\n');
            });
        }
        else {
            // There are no imports and no package declaration - give up
            return null;
        }
    });
}
exports.addImport = addImport;
//# sourceMappingURL=goImport.js.map


text:
<?xml version="1.0" encoding="utf-8"?>
<AssetDeclaration xmlns="uri:ea.com:eala:asset" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<Tags></Tags>
	<Includes>
		<Include
			type="all"
			source="ART:DCPStrSign02.w3x" />
	</Includes>
	<GameObject
		id="DCPStrSign02"
		SelectPortrait="SABarracks_L"
		ButtonImage="SABarracks"
		Side="Civilian"
		EditorSorting="MISC_MAN_MADE"
		TransportSlotCount="1"
		BuildCost="1"
		BuildTime="10.0"
		CommandSet="EmptyCommandSet"
		KindOf="STRUCTURE UNATTACKABLE NOT_AUTOACQUIRABLE IMMOBILE CLEARED_BY_BUILD NO_COLLIDE"
		RadarPriority="STRUCTURE"
		EditorName="DCPStrSign02"
		Browser="REGION Washington_DC_DC MISC_MAN_MADE">
		<DisplayName>Sign</DisplayName>
		<ArmorSet
			Armor="StructureArmor" />
		<Draws>
			<ScriptedModelDraw
				id="ModuleTag_Draw"
				OkToChangeModelColor="true">
				<ModelConditionState
					ParseCondStateType="PARSE_DEFAULT">
					<Model
						Name="DCPStrSign02" />
				</ModelConditionState>
			</ScriptedModelDraw>
		</Draws>
		<Behaviors></Behaviors>
		<Body>
			<ActiveBody
				id="ModuleTag_Body"
				MaxHealth="6000.0"
				InitialHealth="6000.0" />
		</Body>
		<Geometry
			IsSmall="false">
			<Shape
				Type="BOX"
				MajorRadius="2.10143"
				MinorRadius="2.92373"
				Height="49.7034">
				<Offset
					x="-0.471649"
					y="-1.05124"
					z="0.0" />
			</Shape>
		</Geometry>
		<ShadowInfo
			Type="VOLUME" />
		<VisionInfo
			VisionRange="100"
			ShroudClearingRange="200" />
	</GameObject>
</AssetDeclaration>


text:
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// "liveMedia"
// Copyright (c) 1996-2017 Live Networks, Inc.  All rights reserved.
// A generic RTP sink for video codecs (abstract base class)
// Implementation

#include "VideoRTPSink.hh"

VideoRTPSink::VideoRTPSink(UsageEnvironment& env,
			   Groupsock* rtpgs, unsigned char rtpPayloadType,
			   unsigned rtpTimestampFrequency,
			   char const* rtpPayloadFormatName)
  : MultiFramedRTPSink(env, rtpgs, rtpPayloadType, rtpTimestampFrequency,
		       rtpPayloadFormatName) {
}

VideoRTPSink::~VideoRTPSink() {
}

char const* VideoRTPSink::sdpMediaType() const {
  return "video";
}


text:
/*
FPF - Frame Processing Framework
See the file COPYING for copying permission.
*/
/*
CNode_ZTS -  node to append Zodiac timestamps to the TF

*/

#ifndef CNODE_ZTS_H
#define CNODE_ZTS_H

#include "fpf.h"

#define  FACTORY_CNODE_ZTS(c) FACTORY_ADD_NODE(c,CNode_ZTS)

struct PACKED_GCC ZTS { //Zodiac style timestamp, 16 bytes
    uint32_t  seconds;
    uint32_t  mkseconds;
    uint32_t    w1; //not yet known fields
    uint32_t    w2;
};

class CNode_ZTS : public INode
{
    public:
        CNode_ZTS();
        virtual ~CNode_ZTS();
        //INode
        bool init(t_ini& ini, string& name, CChain* chain);
        void start(void);
        void stop(void);
        void close(void);
        void take_frame(CFrame* pf);
    protected:
    private:
        unsigned long c_counter;
        CFrame new_frame; ///new frame structure to keep new output frame (is size extention takes place)
        CFrame* p_output_frame; /// pointer to output frame (either input one or new one)
        uint8_t *pframe_data;
        string str_base_time;
        time_t base_t;
        time_t base_utime;
        int base_mksec;
        int frame_period; ///microseconds per frame
        bool set_timestamp ; /// set new timestamp values, otherwise this is just the ts dump utility
        int dump_every;
        int base_year;
        size_t zts_offset;
        bool f_update_actime;
        //
        void do_frame_processing(CFrame* pf);

};
#endif // CNODE_ZTS_H


text:
<?php namespace Tarsana\Syntax;

use Tarsana\Syntax\Exceptions\DumpException;
use Tarsana\Syntax\Exceptions\ParseException;

/**
 * Represents a string.
 */
class StringSyntax extends Syntax {

    const ERROR = 'Not a string value';
    const NO_EMPTY = 'String should not be empty';

    protected static $instance = null;

    /**
     * Returns the StringSyntax instance.
     *
     * @return Tarsana\Syntax\StringSyntax
     */
    public static function instance() : StringSyntax
    {
        if (self::$instance === null)
            self::$instance = new StringSyntax;
        return self::$instance;
    }

    private function __construct() {}

    /**
     * Returns the given string.
     *
     * @param  string $text
     * @return string
     */
    public function parse(string $text) : string
    {
        if ($text === '')
            throw new ParseException($this, $text, 0, self::NO_EMPTY);
        return $text;
    }

    /**
     * Returns the given string.
     *
     * @param  string $value
     * @return string
     *
     * @throws Tarsana\Syntax\Exceptions\DumpException
     */
    public function dump($value) : string
    {
        if (! is_string($value))
            throw new DumpException($this, $value, self::ERROR);
        return $value;
    }

    /**
     * Returns the string representation of the syntax.
     *
     * @return string
     */
    public function __toString() : string
    {
        return 'String';
    }
}