text:
import { CharCode } from 'vs/base/common/charCode';
import * as strings from 'vs/base/common/strings';
import { IViewLineTokens } from 'vs/editor/common/core/lineTokens';
import { IStringBuilder, createStringBuilder } from 'vs/editor/common/core/stringBuilder';
import { LineDecoration, LineDecorationsNormalizer } from 'vs/editor/common/viewLayout/lineDecorations';
import { InlineDecorationType } from 'vs/editor/common/viewModel/viewModel';

export const enum RenderWhitespace {
	None = 0,
	Boundary = 1,
	Selection = 2,
	All = 3
}

export const enum LinePartMetadata {
	IS_WHITESPACE = 1,
	PSEUDO_BEFORE = 2,
	PSEUDO_AFTER = 4,

	IS_WHITESPACE_MASK = 0b001,
	PSEUDO_BEFORE_MASK = 0b010,
	PSEUDO_AFTER_MASK = 0b100,
}

class LinePart {
	_linePartBrand: void;

	/**
	 * last char index of this token (not inclusive).
	 */
	public readonly endIndex: number;
	public readonly type: string;
	public readonly metadata: number;

	constructor(endIndex: number, type: string, metadata: number) {
		this.endIndex = endIndex;
		this.type = type;
		this.metadata = metadata;
	}

	public isWhitespace(): boolean {
		return (this.metadata & LinePartMetadata.IS_WHITESPACE_MASK ? true : false);
	}
}

export class LineRange {
	/**
	 * Zero-based offset on which the range starts, inclusive.
	 */
	public readonly startOffset: number;

	/**
	 * Zero-based offset on which the range ends, inclusive.
	 */
	public readonly endOffset: number;

	constructor(startIndex: number, endIndex: number) {
		this.startOffset = startIndex;
		this.endOffset = endIndex;
	}

	public equals(otherLineRange: LineRange) {
		return this.startOffset === otherLineRange.startOffset
			&& this.endOffset === otherLineRange.endOffset;
	}
}

export class RenderLineInput {

	public readonly useMonospaceOptimizations: boolean;
	public readonly canUseHalfwidthRightwardsArrow: boolean;
	public readonly lineContent: string;
	public readonly continuesWithWrappedLine: boolean;
	public readonly isBasicASCII: boolean;
	public readonly containsRTL: boolean;
	public readonly fauxIndentLength: number;
	public readonly lineTokens: IViewLineTokens;
	public readonly lineDecorations: LineDecoration[];
	public readonly tabSize: number;
	public readonly startVisibleColumn: number;
	public readonly spaceWidth: number;
	public readonly renderSpaceWidth: number;
	public readonly renderSpaceCharCode: number;
	public readonly stopRenderingLineAfter: number;
	public readonly renderWhitespace: RenderWhitespace;
	public readonly renderControlCharacters: boolean;
	public readonly fontLigatures: boolean;

	/**
	 * Defined only when renderWhitespace is 'selection'. Selections are non-overlapping,
	 * and ordered by position within the line.
	 */
	public readonly selectionsOnLine: LineRange[] | null;

	constructor(
		useMonospaceOptimizations: boolean,
		canUseHalfwidthRightwardsArrow: boolean,
		lineContent: string,
		continuesWithWrappedLine: boolean,
		isBasicASCII: boolean,
		containsRTL: boolean,
		fauxIndentLength: number,
		lineTokens: IViewLineTokens,
		lineDecorations: LineDecoration[],
		tabSize: number,
		startVisibleColumn: number,
		spaceWidth: number,
		middotWidth: number,
		wsmiddotWidth: number,
		stopRenderingLineAfter: number,
		renderWhitespace: 'none' | 'boundary' | 'selection' | 'all',
		renderControlCharacters: boolean,
		fontLigatures: boolean,
		selectionsOnLine: LineRange[] | null
	) {
		this.useMonospaceOptimizations = useMonospaceOptimizations;
		this.canUseHalfwidthRightwardsArrow = canUseHalfwidthRightwardsArrow;
		this.lineContent = lineContent;
		this.continuesWithWrappedLine = continuesWithWrappedLine;
		this.isBasicASCII = isBasicASCII;
		this.containsRTL = containsRTL;
		this.fauxIndentLength = fauxIndentLength;
		this.lineTokens = lineTokens;
		this.lineDecorations = lineDecorations;
		this.tabSize = tabSize;
		this.startVisibleColumn = startVisibleColumn;
		this.spaceWidth = spaceWidth;
		this.stopRenderingLineAfter = stopRenderingLineAfter;
		this.renderWhitespace = (
			renderWhitespace === 'all'
				? RenderWhitespace.All
				: renderWhitespace === 'boundary'
					? RenderWhitespace.Boundary
					: renderWhitespace === 'selection'
						? RenderWhitespace.Selection
						: RenderWhitespace.None
		);
		this.renderControlCharacters = renderControlCharacters;
		this.fontLigatures = fontLigatures;
		this.selectionsOnLine = selectionsOnLine && selectionsOnLine.sort((a, b) => a.startOffset < b.startOffset ? -1 : 1);

		const wsmiddotDiff = Math.abs(wsmiddotWidth - spaceWidth);
		const middotDiff = Math.abs(middotWidth - spaceWidth);
		if (wsmiddotDiff < middotDiff) {
			this.renderSpaceWidth = wsmiddotWidth;
			this.renderSpaceCharCode = 0x2E31; // U+2E31 - WORD SEPARATOR MIDDLE DOT
		} else {
			this.renderSpaceWidth = middotWidth;
			this.renderSpaceCharCode = 0xB7; // U+00B7 - MIDDLE DOT
		}
	}

	private sameSelection(otherSelections: LineRange[] | null): boolean {
		if (this.selectionsOnLine === null) {
			return otherSelections === null;
		}

		if (otherSelections === null) {
			return false;
		}

		if (otherSelections.length !== this.selectionsOnLine.length) {
			return false;
		}

		for (let i = 0; i < this.selectionsOnLine.length; i++) {
			if (!this.selectionsOnLine[i].equals(otherSelections[i])) {
				return false;
			}
		}

		return true;
	}

	public equals(other: RenderLineInput): boolean {
		return (
			this.useMonospaceOptimizations === other.useMonospaceOptimizations
			&& this.canUseHalfwidthRightwardsArrow === other.canUseHalfwidthRightwardsArrow
			&& this.lineContent === other.lineContent
			&& this.continuesWithWrappedLine === other.continuesWithWrappedLine
			&& this.isBasicASCII === other.isBasicASCII
			&& this.containsRTL === other.containsRTL
			&& this.fauxIndentLength === other.fauxIndentLength
			&& this.tabSize === other.tabSize
			&& this.startVisibleColumn === other.startVisibleColumn
			&& this.spaceWidth === other.spaceWidth
			&& this.renderSpaceWidth === other.renderSpaceWidth
			&& this.renderSpaceCharCode === other.renderSpaceCharCode
			&& this.stopRenderingLineAfter === other.stopRenderingLineAfter
			&& this.renderWhitespace === other.renderWhitespace
			&& this.renderControlCharacters === other.renderControlCharacters
			&& this.fontLigatures === other.fontLigatures
			&& LineDecoration.equalsArr(this.lineDecorations, other.lineDecorations)
			&& this.lineTokens.equals(other.lineTokens)
			&& this.sameSelection(other.selectionsOnLine)
		);
	}
}

export const enum CharacterMappingConstants {
	PART_INDEX_MASK = 0b11111111111111110000000000000000,
	CHAR_INDEX_MASK = 0b00000000000000001111111111111111,

	CHAR_INDEX_OFFSET = 0,
	PART_INDEX_OFFSET = 16
}

/**
 * Provides a both direction mapping between a line's character and its rendered position.
 */
export class CharacterMapping {

	public static getPartIndex(partData: number): number {
		return (partData & CharacterMappingConstants.PART_INDEX_MASK) >>> CharacterMappingConstants.PART_INDEX_OFFSET;
	}

	public static getCharIndex(partData: number): number {
		return (partData & CharacterMappingConstants.CHAR_INDEX_MASK) >>> CharacterMappingConstants.CHAR_INDEX_OFFSET;
	}

	public readonly length: number;
	private readonly _data: Uint32Array;
	private readonly _absoluteOffsets: Uint32Array;

	constructor(length: number, partCount: number) {
		this.length = length;
		this._data = new Uint32Array(this.length);
		this._absoluteOffsets = new Uint32Array(this.length);
	}

	public setPartData(charOffset: number, partIndex: number, charIndex: number, partAbsoluteOffset: number): void {
		let partData = (
			(partIndex << CharacterMappingConstants.PART_INDEX_OFFSET)
			| (charIndex << CharacterMappingConstants.CHAR_INDEX_OFFSET)
		) >>> 0;
		this._data[charOffset] = partData;
		this._absoluteOffsets[charOffset] = partAbsoluteOffset + charIndex;
	}

	public getAbsoluteOffsets(): Uint32Array {
		return this._absoluteOffsets;
	}

	public charOffsetToPartData(charOffset: number): number {
		if (this.length === 0) {
			return 0;
		}
		if (charOffset < 0) {
			return this._data[0];
		}
		if (charOffset >= this.length) {
			return this._data[this.length - 1];
		}
		return this._data[charOffset];
	}

	public partDataToCharOffset(partIndex: number, partLength: number, charIndex: number): number {
		if (this.length === 0) {
			return 0;
		}

		let searchEntry = (
			(partIndex << CharacterMappingConstants.PART_INDEX_OFFSET)
			| (charIndex << CharacterMappingConstants.CHAR_INDEX_OFFSET)
		) >>> 0;

		let min = 0;
		let max = this.length - 1;
		while (min + 1 < max) {
			let mid = ((min + max) >>> 1);
			let midEntry = this._data[mid];
			if (midEntry === searchEntry) {
				return mid;
			} else if (midEntry > searchEntry) {
				max = mid;
			} else {
				min = mid;
			}
		}

		if (min === max) {
			return min;
		}

		let minEntry = this._data[min];
		let maxEntry = this._data[max];

		if (minEntry === searchEntry) {
			return min;
		}
		if (maxEntry === searchEntry) {
			return max;
		}

		let minPartIndex = CharacterMapping.getPartIndex(minEntry);
		let minCharIndex = CharacterMapping.getCharIndex(minEntry);

		let maxPartIndex = CharacterMapping.getPartIndex(maxEntry);
		let maxCharIndex: number;

		if (minPartIndex !== maxPartIndex) {
			// sitting between parts
			maxCharIndex = partLength;
		} else {
			maxCharIndex = CharacterMapping.getCharIndex(maxEntry);
		}

		let minEntryDistance = charIndex - minCharIndex;
		let maxEntryDistance = maxCharIndex - charIndex;

		if (minEntryDistance <= maxEntryDistance) {
			return min;
		}
		return max;
	}
}

export const enum ForeignElementType {
	None = 0,
	Before = 1,
	After = 2
}

export class RenderLineOutput {
	_renderLineOutputBrand: void;

	readonly characterMapping: CharacterMapping;
	readonly containsRTL: boolean;
	readonly containsForeignElements: ForeignElementType;

	constructor(characterMapping: CharacterMapping, containsRTL: boolean, containsForeignElements: ForeignElementType) {
		this.characterMapping = characterMapping;
		this.containsRTL = containsRTL;
		this.containsForeignElements = containsForeignElements;
	}
}

export function renderViewLine(input: RenderLineInput, sb: IStringBuilder): RenderLineOutput {
	if (input.lineContent.length === 0) {

		let containsForeignElements = ForeignElementType.None;

		// This is basically for IE's hit test to work
		let content: string = '\u00a0';

		if (input.lineDecorations.length > 0) {
			// This line is empty, but it contains inline decorations
			const beforeClassNames: string[] = [];
			const afterClassNames: string[] = [];
			for (let i = 0, len = input.lineDecorations.length; i < len; i++) {
				const lineDecoration = input.lineDecorations[i];
				if (lineDecoration.type === InlineDecorationType.Before) {
					beforeClassNames.push(input.lineDecorations[i].className);
					containsForeignElements |= ForeignElementType.Before;
				}
				if (lineDecoration.type === InlineDecorationType.After) {
					afterClassNames.push(input.lineDecorations[i].className);
					containsForeignElements |= ForeignElementType.After;
				}
			}

			if (containsForeignElements !== ForeignElementType.None) {
				const beforeSpan = (beforeClassNames.length > 0 ? `<span class="${beforeClassNames.join(' ')}"></span>` : ``);
				const afterSpan = (afterClassNames.length > 0 ? `<span class="${afterClassNames.join(' ')}"></span>` : ``);
				content = `<span>${beforeSpan}${afterSpan}</span>`;
			}
		}

		sb.appendASCIIString(content);
		return new RenderLineOutput(
			new CharacterMapping(0, 0),
			false,
			containsForeignElements
		);
	}

	return _renderLine(resolveRenderLineInput(input), sb);
}

export class RenderLineOutput2 {
	constructor(
		public readonly characterMapping: CharacterMapping,
		public readonly html: string,
		public readonly containsRTL: boolean,
		public readonly containsForeignElements: ForeignElementType
	) {
	}
}

export function renderViewLine2(input: RenderLineInput): RenderLineOutput2 {
	let sb = createStringBuilder(10000);
	let out = renderViewLine(input, sb);
	return new RenderLineOutput2(out.characterMapping, sb.build(), out.containsRTL, out.containsForeignElements);
}

class ResolvedRenderLineInput {
	constructor(
		public readonly fontIsMonospace: boolean,
		public readonly canUseHalfwidthRightwardsArrow: boolean,
		public readonly lineContent: string,
		public readonly len: number,
		public readonly isOverflowing: boolean,
		public readonly parts: LinePart[],
		public readonly containsForeignElements: ForeignElementType,
		public readonly fauxIndentLength: number,
		public readonly tabSize: number,
		public readonly startVisibleColumn: number,
		public readonly containsRTL: boolean,
		public readonly spaceWidth: number,
		public readonly renderSpaceCharCode: number,
		public readonly renderWhitespace: RenderWhitespace,
		public readonly renderControlCharacters: boolean,
	) {
		//
	}
}

function resolveRenderLineInput(input: RenderLineInput): ResolvedRenderLineInput {
	const lineContent = input.lineContent;

	let isOverflowing: boolean;
	let len: number;

	if (input.stopRenderingLineAfter !== -1 && input.stopRenderingLineAfter < lineContent.length) {
		isOverflowing = true;
		len = input.stopRenderingLineAfter;
	} else {
		isOverflowing = false;
		len = lineContent.length;
	}

	let tokens = transformAndRemoveOverflowing(input.lineTokens, input.fauxIndentLength, len);
	if (input.renderWhitespace === RenderWhitespace.All || input.renderWhitespace === RenderWhitespace.Boundary || (input.renderWhitespace === RenderWhitespace.Selection && !!input.selectionsOnLine)) {
		tokens = _applyRenderWhitespace(input, lineContent, len, tokens);
	}
	let containsForeignElements = ForeignElementType.None;
	if (input.lineDecorations.length > 0) {
		for (let i = 0, len = input.lineDecorations.length; i < len; i++) {
			const lineDecoration = input.lineDecorations[i];
			if (lineDecoration.type === InlineDecorationType.RegularAffectingLetterSpacing) {
				// Pretend there are foreign elements... although not 100% accurate.
				containsForeignElements |= ForeignElementType.Before;
			} else if (lineDecoration.type === InlineDecorationType.Before) {
				containsForeignElements |= ForeignElementType.Before;
			} else if (lineDecoration.type === InlineDecorationType.After) {
				containsForeignElements |= ForeignElementType.After;
			}
		}
		tokens = _applyInlineDecorations(lineContent, len, tokens, input.lineDecorations);
	}
	if (!input.containsRTL) {
		// We can never split RTL text, as it ruins the rendering
		tokens = splitLargeTokens(lineContent, tokens, !input.isBasicASCII || input.fontLigatures);
	}

	return new ResolvedRenderLineInput(
		input.useMonospaceOptimizations,
		input.canUseHalfwidthRightwardsArrow,
		lineContent,
		len,
		isOverflowing,
		tokens,
		containsForeignElements,
		input.fauxIndentLength,
		input.tabSize,
		input.startVisibleColumn,
		input.containsRTL,
		input.spaceWidth,
		input.renderSpaceCharCode,
		input.renderWhitespace,
		input.renderControlCharacters
	);
}

/**
 * In the rendering phase, characters are always looped until token.endIndex.
 * Ensure that all tokens end before `len` and the last one ends precisely at `len`.
 */
function transformAndRemoveOverflowing(tokens: IViewLineTokens, fauxIndentLength: number, len: number): LinePart[] {
	let result: LinePart[] = [], resultLen = 0;

	// The faux indent part of the line should have no token type
	if (fauxIndentLength > 0) {
		result[resultLen++] = new LinePart(fauxIndentLength, '', 0);
	}

	for (let tokenIndex = 0, tokensLen = tokens.getCount(); tokenIndex < tokensLen; tokenIndex++) {
		const endIndex = tokens.getEndOffset(tokenIndex);
		if (endIndex <= fauxIndentLength) {
			// The faux indent part of the line should have no token type
			continue;
		}
		const type = tokens.getClassName(tokenIndex);
		if (endIndex >= len) {
			result[resultLen++] = new LinePart(len, type, 0);
			break;
		}
		result[resultLen++] = new LinePart(endIndex, type, 0);
	}

	return result;
}

/**
 * written as a const enum to get value inlining.
 */
const enum Constants {
	LongToken = 50
}

/**
 * See https://github.com/Microsoft/vscode/issues/6885.
 * It appears that having very large spans causes very slow reading of character positions.
 * So here we try to avoid that.
 */
function splitLargeTokens(lineContent: string, tokens: LinePart[], onlyAtSpaces: boolean): LinePart[] {
	let lastTokenEndIndex = 0;
	let result: LinePart[] = [], resultLen = 0;

	if (onlyAtSpaces) {
		// Split only at spaces => we need to walk each character
		for (let i = 0, len = tokens.length; i < len; i++) {
			const token = tokens[i];
			const tokenEndIndex = token.endIndex;
			if (lastTokenEndIndex + Constants.LongToken < tokenEndIndex) {
				const tokenType = token.type;
				const tokenMetadata = token.metadata;

				let lastSpaceOffset = -1;
				let currTokenStart = lastTokenEndIndex;
				for (let j = lastTokenEndIndex; j < tokenEndIndex; j++) {
					if (lineContent.charCodeAt(j) === CharCode.Space) {
						lastSpaceOffset = j;
					}
					if (lastSpaceOffset !== -1 && j - currTokenStart >= Constants.LongToken) {
						// Split at `lastSpaceOffset` + 1
						result[resultLen++] = new LinePart(lastSpaceOffset + 1, tokenType, tokenMetadata);
						currTokenStart = lastSpaceOffset + 1;
						lastSpaceOffset = -1;
					}
				}
				if (currTokenStart !== tokenEndIndex) {
					result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata);
				}
			} else {
				result[resultLen++] = token;
			}

			lastTokenEndIndex = tokenEndIndex;
		}
	} else {
		// Split anywhere => we don't need to walk each character
		for (let i = 0, len = tokens.length; i < len; i++) {
			const token = tokens[i];
			const tokenEndIndex = token.endIndex;
			let diff = (tokenEndIndex - lastTokenEndIndex);
			if (diff > Constants.LongToken) {
				const tokenType = token.type;
				const tokenMetadata = token.metadata;
				const piecesCount = Math.ceil(diff / Constants.LongToken);
				for (let j = 1; j < piecesCount; j++) {
					let pieceEndIndex = lastTokenEndIndex + (j * Constants.LongToken);
					result[resultLen++] = new LinePart(pieceEndIndex, tokenType, tokenMetadata);
				}
				result[resultLen++] = new LinePart(tokenEndIndex, tokenType, tokenMetadata);
			} else {
				result[resultLen++] = token;
			}
			lastTokenEndIndex = tokenEndIndex;
		}
	}

	return result;
}

/**
 * Whitespace is rendered by "replacing" tokens with a special-purpose `mtkw` type that is later recognized in the rendering phase.
 * Moreover, a token is created for every visual indent because on some fonts the glyphs used for rendering whitespace (→ or ·) do not have the same width as  .
 * The rendering phase will generate `style="width:..."` for these tokens.
 */
function _applyRenderWhitespace(input: RenderLineInput, lineContent: string, len: number, tokens: LinePart[]): LinePart[] {

	const continuesWithWrappedLine = input.continuesWithWrappedLine;
	const fauxIndentLength = input.fauxIndentLength;
	const tabSize = input.tabSize;
	const startVisibleColumn = input.startVisibleColumn;
	const useMonospaceOptimizations = input.useMonospaceOptimizations;
	const selections = input.selectionsOnLine;
	const onlyBoundary = (input.renderWhitespace === RenderWhitespace.Boundary);
	const generateLinePartForEachWhitespace = (input.renderSpaceWidth !== input.spaceWidth);

	let result: LinePart[] = [], resultLen = 0;
	let tokenIndex = 0;
	let tokenType = tokens[tokenIndex].type;
	let tokenEndIndex = tokens[tokenIndex].endIndex;
	const tokensLength = tokens.length;

	let firstNonWhitespaceIndex = strings.firstNonWhitespaceIndex(lineContent);
	let lastNonWhitespaceIndex: number;
	if (firstNonWhitespaceIndex === -1) {
		// The entire line is whitespace
		firstNonWhitespaceIndex = len;
		lastNonWhitespaceIndex = len;
	} else {
		lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent);
	}

	let wasInWhitespace = false;
	let currentSelectionIndex = 0;
	let currentSelection = selections && selections[currentSelectionIndex];
	let tmpIndent = startVisibleColumn % tabSize;
	for (let charIndex = fauxIndentLength; charIndex < len; charIndex++) {
		const chCode = lineContent.charCodeAt(charIndex);

		if (currentSelection && charIndex >= currentSelection.endOffset) {
			currentSelectionIndex++;
			currentSelection = selections && selections[currentSelectionIndex];
		}

		let isInWhitespace: boolean;
		if (charIndex < firstNonWhitespaceIndex || charIndex > lastNonWhitespaceIndex) {
			// in leading or trailing whitespace
			isInWhitespace = true;
		} else if (chCode === CharCode.Tab) {
			// a tab character is rendered both in all and boundary cases
			isInWhitespace = true;
		} else if (chCode === CharCode.Space) {
			// hit a space character
			if (onlyBoundary) {
				// rendering only boundary whitespace
				if (wasInWhitespace) {
					isInWhitespace = true;
				} else {
					const nextChCode = (charIndex + 1 < len ? lineContent.charCodeAt(charIndex + 1) : CharCode.Null);
					isInWhitespace = (nextChCode === CharCode.Space || nextChCode === CharCode.Tab);
				}
			} else {
				isInWhitespace = true;
			}
		} else {
			isInWhitespace = false;
		}

		// If rendering whitespace on selection, check that the charIndex falls within a selection
		if (isInWhitespace && selections) {
			isInWhitespace = !!currentSelection && currentSelection.startOffset <= charIndex && currentSelection.endOffset > charIndex;
		}

		if (wasInWhitespace) {
			// was in whitespace token
			if (!isInWhitespace || (!useMonospaceOptimizations && tmpIndent >= tabSize)) {
				// leaving whitespace token or entering a new indent
				if (generateLinePartForEachWhitespace) {
					const lastEndIndex = (resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength);
					for (let i = lastEndIndex + 1; i <= charIndex; i++) {
						result[resultLen++] = new LinePart(i, 'mtkw', LinePartMetadata.IS_WHITESPACE);
					}
				} else {
					result[resultLen++] = new LinePart(charIndex, 'mtkw', LinePartMetadata.IS_WHITESPACE);
				}
				tmpIndent = tmpIndent % tabSize;
			}
		} else {
			// was in regular token
			if (charIndex === tokenEndIndex || (isInWhitespace && charIndex > fauxIndentLength)) {
				result[resultLen++] = new LinePart(charIndex, tokenType, 0);
				tmpIndent = tmpIndent % tabSize;
			}
		}

		if (chCode === CharCode.Tab) {
			tmpIndent = tabSize;
		} else if (strings.isFullWidthCharacter(chCode)) {
			tmpIndent += 2;
		} else {
			tmpIndent++;
		}

		wasInWhitespace = isInWhitespace;

		while (charIndex === tokenEndIndex) {
			tokenIndex++;
			if (tokenIndex < tokensLength) {
				tokenType = tokens[tokenIndex].type;
				tokenEndIndex = tokens[tokenIndex].endIndex;
			}
		}
	}

	let generateWhitespace = false;
	if (wasInWhitespace) {
		// was in whitespace token
		if (continuesWithWrappedLine && onlyBoundary) {
			let lastCharCode = (len > 0 ? lineContent.charCodeAt(len - 1) : CharCode.Null);
			let prevCharCode = (len > 1 ? lineContent.charCodeAt(len - 2) : CharCode.Null);
			let isSingleTrailingSpace = (lastCharCode === CharCode.Space && (prevCharCode !== CharCode.Space && prevCharCode !== CharCode.Tab));
			if (!isSingleTrailingSpace) {
				generateWhitespace = true;
			}
		} else {
			generateWhitespace = true;
		}
	}

	if (generateWhitespace) {
		if (generateLinePartForEachWhitespace) {
			const lastEndIndex = (resultLen > 0 ? result[resultLen - 1].endIndex : fauxIndentLength);
			for (let i = lastEndIndex + 1; i <= len; i++) {
				result[resultLen++] = new LinePart(i, 'mtkw', LinePartMetadata.IS_WHITESPACE);
			}
		} else {
			result[resultLen++] = new LinePart(len, 'mtkw', LinePartMetadata.IS_WHITESPACE);
		}
	} else {
		result[resultLen++] = new LinePart(len, tokenType, 0);
	}

	return result;
}

/**
 * Inline decorations are "merged" on top of tokens.
 * Special care must be taken when multiple inline decorations are at play and they overlap.
 */
function _applyInlineDecorations(lineContent: string, len: number, tokens: LinePart[], _lineDecorations: LineDecoration[]): LinePart[] {
	_lineDecorations.sort(LineDecoration.compare);
	const lineDecorations = LineDecorationsNormalizer.normalize(lineContent, _lineDecorations);
	const lineDecorationsLen = lineDecorations.length;

	let lineDecorationIndex = 0;
	let result: LinePart[] = [], resultLen = 0, lastResultEndIndex = 0;
	for (let tokenIndex = 0, len = tokens.length; tokenIndex < len; tokenIndex++) {
		const token = tokens[tokenIndex];
		const tokenEndIndex = token.endIndex;
		const tokenType = token.type;
		const tokenMetadata = token.metadata;

		while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset < tokenEndIndex) {
			const lineDecoration = lineDecorations[lineDecorationIndex];

			if (lineDecoration.startOffset > lastResultEndIndex) {
				lastResultEndIndex = lineDecoration.startOffset;
				result[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata);
			}

			if (lineDecoration.endOffset + 1 <= tokenEndIndex) {
				// This line decoration ends before this token ends
				lastResultEndIndex = lineDecoration.endOffset + 1;
				result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className, tokenMetadata | lineDecoration.metadata);
				lineDecorationIndex++;
			} else {
				// This line decoration continues on to the next token
				lastResultEndIndex = tokenEndIndex;
				result[resultLen++] = new LinePart(lastResultEndIndex, tokenType + ' ' + lineDecoration.className, tokenMetadata | lineDecoration.metadata);
				break;
			}
		}

		if (tokenEndIndex > lastResultEndIndex) {
			lastResultEndIndex = tokenEndIndex;
			result[resultLen++] = new LinePart(lastResultEndIndex, tokenType, tokenMetadata);
		}
	}

	const lastTokenEndIndex = tokens[tokens.length - 1].endIndex;
	if (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
		let classNames: string[] = [];
		let metadata = 0;
		while (lineDecorationIndex < lineDecorationsLen && lineDecorations[lineDecorationIndex].startOffset === lastTokenEndIndex) {
			classNames.push(lineDecorations[lineDecorationIndex].className);
			metadata |= lineDecorations[lineDecorationIndex].metadata;
			lineDecorationIndex++;
		}
		result[resultLen++] = new LinePart(lastResultEndIndex, classNames.join(' '), metadata);
	}

	return result;
}

/**
 * This function is on purpose not split up into multiple functions to allow runtime type inference (i.e. performance reasons).
 * Notice how all the needed data is fully resolved and passed in (i.e. no other calls).
 */
function _renderLine(input: ResolvedRenderLineInput, sb: IStringBuilder): RenderLineOutput {
	const fontIsMonospace = input.fontIsMonospace;
	const canUseHalfwidthRightwardsArrow = input.canUseHalfwidthRightwardsArrow;
	const containsForeignElements = input.containsForeignElements;
	const lineContent = input.lineContent;
	const len = input.len;
	const isOverflowing = input.isOverflowing;
	const parts = input.parts;
	const fauxIndentLength = input.fauxIndentLength;
	const tabSize = input.tabSize;
	const startVisibleColumn = input.startVisibleColumn;
	const containsRTL = input.containsRTL;
	const spaceWidth = input.spaceWidth;
	const renderSpaceCharCode = input.renderSpaceCharCode;
	const renderWhitespace = input.renderWhitespace;
	const renderControlCharacters = input.renderControlCharacters;

	const characterMapping = new CharacterMapping(len + 1, parts.length);

	let charIndex = 0;
	let visibleColumn = startVisibleColumn;
	let charOffsetInPart = 0;

	let partDisplacement = 0;
	let prevPartContentCnt = 0;
	let partAbsoluteOffset = 0;

	if (containsRTL) {
		sb.appendASCIIString('');
	} else {
		sb.appendASCIIString('');
	}

	for (let partIndex = 0, tokensLen = parts.length; partIndex < tokensLen; partIndex++) {
		partAbsoluteOffset += prevPartContentCnt;

		const part = parts[partIndex];
		const partEndIndex = part.endIndex;
		const partType = part.type;
		const partRendersWhitespace = (renderWhitespace !== RenderWhitespace.None && part.isWhitespace());
		const partRendersWhitespaceWithWidth = partRendersWhitespace && !fontIsMonospace && (partType === 'mtkw'/*only whitespace*/ || !containsForeignElements);
		const partIsEmptyAndHasPseudoAfter = (charIndex === partEndIndex && part.metadata === LinePartMetadata.PSEUDO_AFTER);
		charOffsetInPart = 0;

		sb.appendASCIIString('<span class="');
		sb.appendASCIIString(partRendersWhitespaceWithWidth ? 'mtkz' : partType);
		sb.appendASCII(CharCode.DoubleQuote);

		if (partRendersWhitespace) {

			let partContentCnt = 0;
			{
				let _charIndex = charIndex;
				let _visibleColumn = visibleColumn;

				for (; _charIndex < partEndIndex; _charIndex++) {
					const charCode = lineContent.charCodeAt(_charIndex);
					const charWidth = (charCode === CharCode.Tab ? (tabSize - (_visibleColumn % tabSize)) : 1) | 0;
					partContentCnt += charWidth;
					if (_charIndex >= fauxIndentLength) {
						_visibleColumn += charWidth;
					}
				}
			}

			if (partRendersWhitespaceWithWidth) {
				sb.appendASCIIString(' style="width:');
				sb.appendASCIIString(String(spaceWidth * partContentCnt));
				sb.appendASCIIString('px"');
			}
			sb.appendASCII(CharCode.GreaterThan);

			for (; charIndex < partEndIndex; charIndex++) {
				characterMapping.setPartData(charIndex, partIndex - partDisplacement, charOffsetInPart, partAbsoluteOffset);
				partDisplacement = 0;
				const charCode = lineContent.charCodeAt(charIndex);
				let charWidth: number;

				if (charCode === CharCode.Tab) {
					charWidth = (tabSize - (visibleColumn % tabSize)) | 0;

					if (!canUseHalfwidthRightwardsArrow || charWidth > 1) {
						sb.write1(0x2192); // RIGHTWARDS ARROW
					} else {
						sb.write1(0xFFEB); // HALFWIDTH RIGHTWARDS ARROW
					}
					for (let space = 2; space <= charWidth; space++) {
						sb.write1(0xA0); //
					}

				} else { // must be CharCode.Space
					charWidth = 1;

					sb.write1(renderSpaceCharCode); // · or word separator middle dot
				}

				charOffsetInPart += charWidth;
				if (charIndex >= fauxIndentLength) {
					visibleColumn += charWidth;
				}
			}

			prevPartContentCnt = partContentCnt;

		} else {

			let partContentCnt = 0;

			sb.appendASCII(CharCode.GreaterThan);

			for (; charIndex < partEndIndex; charIndex++) {
				characterMapping.setPartData(charIndex, partIndex - partDisplacement, charOffsetInPart, partAbsoluteOffset);
				partDisplacement = 0;
				const charCode = lineContent.charCodeAt(charIndex);

				let producedCharacters = 1;
				let charWidth = 1;

				switch (charCode) {
					case CharCode.Tab:
						producedCharacters = (tabSize - (visibleColumn % tabSize));
						charWidth = producedCharacters;
						for (let space = 1; space <= producedCharacters; space++) {
							sb.write1(0xA0); //
						}
						break;

					case CharCode.Space:
						sb.write1(0xA0); //
						break;

					case CharCode.LessThan:
						sb.appendASCIIString('<');
						break;

					case CharCode.GreaterThan:
						sb.appendASCIIString('>');
						break;

					case CharCode.Ampersand:
						sb.appendASCIIString('&');
						break;

					case CharCode.Null:
						sb.appendASCIIString('�');
						break;

					case CharCode.UTF8_BOM:
					case CharCode.LINE_SEPARATOR:
					case CharCode.PARAGRAPH_SEPARATOR:
					case CharCode.NEXT_LINE:
						sb.write1(0xFFFD);
						break;

					default:
						if (strings.isFullWidthCharacter(charCode)) {
							charWidth++;
						}
						if (renderControlCharacters && charCode < 32) {
							sb.write1(9216 + charCode);
						} else {
							sb.write1(charCode);
						}
				}

				charOffsetInPart += producedCharacters;
				partContentCnt += producedCharacters;
				if (charIndex >= fauxIndentLength) {
					visibleColumn += charWidth;
				}
			}

			prevPartContentCnt = partContentCnt;
		}

		if (partIsEmptyAndHasPseudoAfter) {
			partDisplacement++;
		} else {
			partDisplacement = 0;
		}

		sb.appendASCIIString('');

	}

	// When getting client rects for the last character, we will position the
	// text range at the end of the span, insteaf of at the beginning of next span
	characterMapping.setPartData(len, parts.length - 1, charOffsetInPart, partAbsoluteOffset);

	if (isOverflowing) {
		sb.appendASCIIString('…');
	}

	sb.appendASCIIString('');

	return new RenderLineOutput(characterMapping, containsRTL, containsForeignElements);
}


text:
<TITLE>Review for Gone with the Wind (1939)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Gone with the Wind (1939)

reviewed by
Brian Koller

Gone with the Wind (1939)

Grade: 93

"Gone with the Wind" is perhaps the most successful film
of all time.  It was the top grossing film until at least
"The Sound of Music", some thirty years of inflation later.
The story, and the characters, have become a part of
American cultural heritage.

The story begins in Georgia, just prior to the Civil War.
Beautiful and spoiled Scarlett O'Hara (Vivien Leigh) schemes
to win the love of the honorable Ashley Wilkes (Leslie Howard),
who is engaged to his saintly cousin Melanie (Olivia De Havilland).
Scarlett fails in this effort, but wins the admiration of
dashing scoundrel Rhett Butler (Clark Gable).

Ashley marries Melanie, then goes off to fight the Civil War.
Scarlett moves to Atlanta to be with Melanie and wait for
Ashley's return.  Eventually, Union troops siege and capture
Atlanta, forcing Scarlett, Melanie, and her newborn baby
to flee to Scarlett's home at Tara, which has been impoverished
by looting Federal troops.

After much humiliation and unethical behavior, Scarlett rebuilds
Tara and becomes a wealthy businesswoman.  She marries Rhett
and has a daughter, but her marriage is stormy.

Is "Gone with the Wind" pro-slavery?  In the pre-war scenes,
blacks seem content with their lot, and show devotion to the
white "masters" that control their lives.  Pork (Oscar Polk) is a
shuffling, slow-talking stereotype.  Prissy (Butterfly McQueen)
is described by Rhett as a "simple-minded darky".

But to its credit, "Gone with the Wind" has two very strong
and positive roles.  The characters listen with respect
to Mammy (Hattie McDaniel), whose straightforward comments
make for sage advice.  McDaniel won Best Supporting Actress,
an outstanding achievement during an era of segregation.
Big Sam (Everett Brown) shows great courage rescuing Scarlett
from grave danger.

However, my favorite supporting character is Scarlett's
exuberant first husband Charles Hamilton (Rand Brooks).
Also, Aunt Pittypat (Laura Hope Crews) gives an excellent
comic-relief performance.

"Gone with the Wind" also won major Oscars for Best Screenplay
(Sidney Howard), Best Actress (Scarlett O'Hara),
Best Color Cinematography, Best Director, and Best Picture.
Fleming was credited as director, although four directors
were used.  This was a clean sweep of all major awards
except Best Actor, which passed over Clark Gable.  (Vivien
Leigh's husband, Laurence Olivier, was also nominated, for
"Wuthering Heights."  The winner that year was Robert Donat).

"Gone with the Wind" clocks in at 222 minutes, more than twice
the length of an typical film from 1939.  The story does sag
once or twice, but only in comparison with its best parts.
The film peaks midway, during the siege of Atlanta.  The film's
best action scenes are here, and the devastation war is clearly
demonstrated by the horrific hospital scenes and acres of wounded
soldiers.

The film picks up again during a postwar sequence loaded with
suspense. Scarlett has narrowly escaped an attack on her by
lowlifes in a shantytown.  A dangerous vigilante action is then
taken by the men in Scarlett's life, while their wives wait
anxiously for their return.

Scarlett O'Hara, the central character, is shrewd, manipulating,
and selfish.  She is despised by most of the other female
characters.  Yet she is presented to the audience clearly as
a heroine.  Women identify with her determination, and she
shows positive traits helping Melanie to deliver her baby,
and saving and rebuilding Tara after the war.

Rhett Butler is a self-proclaimed scoundrel, but he keeps
performing heroic actions that contradict what he says,
just as his love for Scarlett shows despite his frequent
cruelty to her.  Although he enjoys adventures apart from
Scarlett, one of the film's recurrent themes is his
return to her, and his determination to have her love him
more than Ashley.

One wonders at first viewing why Melanie is so nice to
Scarlett, who constantly schemes to steal Ashley from her.
But Melanie does not view Scarlett as a threat, and
perhaps she loves her more than Scarlett loves Ashley.

Of course, "Gone with the Wind" is a costume epic and a
soap opera.  Because of its genre, and its strong appeal to
women (the story is told through Vivien Leigh's character),
there are naysayers (mostly men) who dislike the movie.
But there is no doubt that it an outstanding film.  If the
costumes, the cinematography, and the script aren't enough
to convince (which they certainly should be), the leading
characters are extremely interesting and well defined.

kollers@mpsi.net
http://members.tripod.com/~Brian_Koller/movies.html

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews

redpajama_set_name: RedPajamaGithub


text:
package com.doominoo.couchpotato.model;

import com.google.gson.annotations.SerializedName;

import javax.annotation.Generated;
import java.util.List;

@Generated("net.hexar.json2pojo")
@SuppressWarnings("unused")
public class CouchpotatoMovie {

    @SerializedName("category_id")
    private Object mCategoryId;
    @SerializedName("files")
    private Files mFiles;
    @SerializedName("identifiers")
    private Identifiers mIdentifiers;
    @SerializedName("info")
    private Info mInfo;
    @SerializedName("last_edit")
    private Long mLastEdit;
    @SerializedName("profile_id")
    private Object mProfileId;
    @SerializedName("releases")
    private List<Release> mReleases;
    @SerializedName("status")
    private String mStatus;
    @SerializedName("tags")
    private List<Object> mTags;
    @SerializedName("title")
    private String mTitle;
    @SerializedName("type")
    private String mType;
    @SerializedName("_id")
    private String m_id;
    @SerializedName("_rev")
    private String m_rev;
    @SerializedName("_t")
    private String m_t;

    public Object getCategoryId() {
        return mCategoryId;
    }

    public Files getFiles() {
        return mFiles;
    }

    public Identifiers getIdentifiers() {
        return mIdentifiers;
    }

    public Info getInfo() {
        return mInfo;
    }

    public Long getLastEdit() {
        return mLastEdit;
    }

    public Object getProfileId() {
        return mProfileId;
    }

    public List<Release> getReleases() {
        return mReleases;
    }

    public String getStatus() {
        return mStatus;
    }

    public List<Object> getTags() {
        return mTags;
    }

    public String getTitle() {
        return mTitle;
    }

    public String getType() {
        return mType;
    }

    public String get_id() {
        return m_id;
    }

    public String get_rev() {
        return m_rev;
    }

    public String get_t() {
        return m_t;
    }

    public static class Builder {

        private Object mCategoryId;
        private Files mFiles;
        private Identifiers mIdentifiers;
        private Info mInfo;
        private Long mLastEdit;
        private Object mProfileId;
        private List<Release> mReleases;
        private String mStatus;
        private List<Object> mTags;
        private String mTitle;
        private String mType;
        private String m_id;
        private String m_rev;
        private String m_t;

        public CouchpotatoMovie.Builder withCategoryId(Object categoryId) {
            mCategoryId = categoryId;
            return this;
        }

        public CouchpotatoMovie.Builder withFiles(Files files) {
            mFiles = files;
            return this;
        }

        public CouchpotatoMovie.Builder withIdentifiers(Identifiers identifiers) {
            mIdentifiers = identifiers;
            return this;
        }

        public CouchpotatoMovie.Builder withInfo(Info info) {
            mInfo = info;
            return this;
        }

        public CouchpotatoMovie.Builder withLastEdit(Long lastEdit) {
            mLastEdit = lastEdit;
            return this;
        }

        public CouchpotatoMovie.Builder withProfileId(Object profileId) {
            mProfileId = profileId;
            return this;
        }

        public CouchpotatoMovie.Builder withReleases(List<Release> releases) {
            mReleases = releases;
            return this;
        }

        public CouchpotatoMovie.Builder withStatus(String status) {
            mStatus = status;
            return this;
        }

        public CouchpotatoMovie.Builder withTags(List<Object> tags) {
            mTags = tags;
            return this;
        }

        public CouchpotatoMovie.Builder withTitle(String title) {
            mTitle = title;
            return this;
        }

        public CouchpotatoMovie.Builder withType(String type) {
            mType = type;
            return this;
        }

        public CouchpotatoMovie.Builder with_id(String _id) {
            m_id = _id;
            return this;
        }

        public CouchpotatoMovie.Builder with_rev(String _rev) {
            m_rev = _rev;
            return this;
        }

        public CouchpotatoMovie.Builder with_t(String _t) {
            m_t = _t;
            return this;
        }

        public CouchpotatoMovie build() {
            CouchpotatoMovie CouchpotatoMovie = new CouchpotatoMovie();
            CouchpotatoMovie.mCategoryId = mCategoryId;
            CouchpotatoMovie.mFiles = mFiles;
            CouchpotatoMovie.mIdentifiers = mIdentifiers;
            CouchpotatoMovie.mInfo = mInfo;
            CouchpotatoMovie.mLastEdit = mLastEdit;
            CouchpotatoMovie.mProfileId = mProfileId;
            CouchpotatoMovie.mReleases = mReleases;
            CouchpotatoMovie.mStatus = mStatus;
            CouchpotatoMovie.mTags = mTags;
            CouchpotatoMovie.mTitle = mTitle;
            CouchpotatoMovie.mType = mType;
            CouchpotatoMovie.m_id = m_id;
            CouchpotatoMovie.m_rev = m_rev;
            CouchpotatoMovie.m_t = m_t;
            return CouchpotatoMovie;
        }

    }

}


text:
set -e

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
OLDPATH="$PATH"

source "$DIR/common/_prettyprint.sh"

while [[ $# > 0 ]]; do
    lowerI="$(echo $1 | awk '{print tolower($0)}')"
    case $lowerI in
        -c|--configuration)
            export CONFIGURATION=$2
            shift
            ;;
        --targets)
            IFS=',' read -r -a targets <<< $2
            shift
            ;;
        --nopackage)
            export DOTNET_BUILD_SKIP_PACKAGING=1
            ;;
        --skip-prereqs)
            # Allow CI to disable prereqs check since the CI has the pre-reqs but not ldconfig it seems
            export DOTNET_INSTALL_SKIP_PREREQS=1
            ;;
        --help)
            echo "Usage: $0 [--configuration <CONFIGURATION>] [--skip-prereqs] [--nopackage] [--docker <IMAGENAME>] [--help] [--targets <TARGETS...>]"
            echo ""
            echo "Options:"
            echo "  --configuration <CONFIGURATION>     Build the specified Configuration (Debug or Release, default: Debug)"
            echo "  --targets <TARGETS...>              Comma separated build targets to run (Init, Compile, Publish, etc.; Default is a full build and publish)"
            echo "  --nopackage                         Skip packaging targets"
            echo "  --skip-prereqs                      Skip checks for pre-reqs in dotnet_install"
            echo "  --docker <IMAGENAME>                Build in Docker using the Dockerfile located in scripts/docker/IMAGENAME"
            echo "  --help                              Display this help message"
            echo "  <TARGETS...>                        The build targets to run (Init, Compile, Publish, etc.; Default is a full build and publish)"
            exit 0
            ;;
        *)
            break
            ;;
    esac

    shift
done

# Set up the environment to be used for building with clang.
if which "clang-3.5" > /dev/null 2>&1; then
    export CC="$(which clang-3.5)"
    export CXX="$(which clang++-3.5)"
elif which "clang-3.6" > /dev/null 2>&1; then
    export CC="$(which clang-3.6)"
    export CXX="$(which clang++-3.6)"
elif which clang > /dev/null 2>&1; then
    export CC="$(which clang)"
    export CXX="$(which clang++)"
else
    error "Unable to find Clang Compiler"
    error "Install clang-3.5 or clang3.6"
    exit 1
fi

# Load Branch Info
while read line; do
    if [[ $line != \#* ]]; then
        IFS='=' read -ra splat <<< "$line"
        export ${splat[0]}="${splat[1]}"
    fi
done < "$DIR/../branchinfo.txt"

# Use a repo-local install directory (but not the artifacts directory because that gets cleaned a lot
[ -z "$DOTNET_INSTALL_DIR" ] && export DOTNET_INSTALL_DIR=$DIR/../.dotnet_stage0/$(uname)
[ -d $DOTNET_INSTALL_DIR ] || mkdir -p $DOTNET_INSTALL_DIR

$DIR/obtain/install.sh --channel $CHANNEL --verbose

# Put stage 0 on the PATH (for this shell only)
PATH="$DOTNET_INSTALL_DIR:$PATH"

# Increases the file descriptors limit for this bash. It prevents an issue we were hitting during restore
FILE_DESCRIPTOR_LIMIT=$( ulimit -n )
if [ $FILE_DESCRIPTOR_LIMIT -lt 1024 ]
then
    echo "Increasing file description limit to 1024"
    ulimit -n 1024
fi

# Restore the build scripts
echo "Restoring Build Script projects..."
(
    cd $DIR
    dotnet restore --infer-runtimes
)

# Build the builder
echo "Compiling Build Scripts..."
dotnet publish "$DIR/dotnet-cli-build" -o "$DIR/dotnet-cli-build/bin" --framework netstandardapp1.5

export PATH="$OLDPATH"
# Run the builder
echo "Invoking Build Scripts..."
echo "Configuration: $CONFIGURATION"

if [ -f "$DIR/dotnet-cli-build/bin/dotnet-cli-build" ]; then
    $DIR/dotnet-cli-build/bin/dotnet-cli-build ${targets[@]}
    exit $?
else
    # We're on an older CLI. This is temporary while Ubuntu and CentOS VSO builds are stalled.
    $DIR/dotnet-cli-build/bin/Debug/dnxcore50/dotnet-cli-build "${targets[@]}"
    exit $?
fi


text:
require 'spec_helper'

describe PagSeguro::PaymentReleases do
  it "implements #each" do
    expect(PagSeguro::PaymentReleases.new).to respond_to(:each)
  end

  it "includes Enumerable" do
    expect(PagSeguro::PaymentReleases.included_modules).to include(Enumerable)
  end

  it "sets payment" do
    payment = PagSeguro::PaymentRelease.new
    payments = PagSeguro::PaymentReleases.new
    payments << payment

    expect(payments.size).to eql(1)
    expect(payments).to include(payment)
  end

  it "sets payment releases from Hash" do
    payment = PagSeguro::PaymentRelease.new(installment: 1)

    expect(PagSeguro::PaymentRelease).to(
      receive(:new)
      .with({installment: 1})
      .and_return(payment))

    payments = PagSeguro::PaymentReleases.new
    payments << {installment: 1}

    expect(payments).to include(payment)
  end
end


text:
import * as path from 'path';

import { EmptyTree } from '@angular-devkit/schematics';
import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';

describe('Update 9.1.0', () => {
    let appTree: UnitTestTree;
    const schematicRunner = new SchematicTestRunner('ig-migrate', path.join(__dirname, '../migration-collection.json'));
    const configJson = {
        defaultProject: 'testProj',
        projects: {
            testProj: {
                sourceRoot: '/testSrc'
            }
        },
        schematics: {
            '@schematics/angular:component': {
                prefix: 'appPrefix'
            }
        }
      };

    beforeEach(() => {
        appTree = new UnitTestTree(new EmptyTree());
        appTree.create('/angular.json', JSON.stringify(configJson));
    });

    it('should update igx-group supressInputAutofocus to suppressInputAutofocus', async () => {
        appTree.create(
            `/testSrc/appPrefix/component/input.component.html`,
            '<igx-input-group [supressInputAutofocus]="true"><input igxInput></igx-input-group>'
        );

        const tree = await schematicRunner.runSchematicAsync('migration-15', {}, appTree)
            .toPromise();

        expect(tree.readContent('/testSrc/appPrefix/component/input.component.html'))
            .toEqual('<igx-input-group [suppressInputAutofocus]="true"><input igxInput></igx-input-group>');

    });

    it('should move igx-toast message property between element tags', async () => {
        appTree.create(
            `/testSrc/appPrefix/component/input.component.html`,
            '<igx-toast message="test message"></igx-toast>'
        );

        const tree = await schematicRunner.runSchematicAsync('migration-15', {}, appTree)
            .toPromise();

        expect(tree.readContent('/testSrc/appPrefix/component/input.component.html'))
        .toEqual('<igx-toast>test message</igx-toast>');

    });

    // Except for testing for true and false (' and ") check for binded scenarios like "'prop'"
    it('should update rowSelectable to rowSelection', async () => {
        appTree.create(
            `/testSrc/appPrefix/component/input.component.html`,
            `<igx-grid [rowSelectable]="true"></igx-grid>`
        );

        const tree = await schematicRunner.runSchematicAsync('migration-15', {}, appTree)
            .toPromise();

        expect(tree.readContent('/testSrc/appPrefix/component/input.component.html'))
        .toEqual(`<igx-grid rowSelection="multiple"></igx-grid>`);

    });

    it('should update rowSelectable to rowSelection when false', async () => {
        appTree.create(
            `/testSrc/appPrefix/component/input.component.html`,
            `
[rowSelectable]="true"

<igx-grid [data]="data" [primaryKey]="'ProductID'" width="700px" height="400px" [rowEditable]="true"
    [autoGenerate]="true"
    [rowSelectable]="true"
>
</igx-grid>

[rowSelectable]="'false'"

<igx-grid [data]="data" [primaryKey]="'ProductID'" width="700px" height="400px" [rowEditable]="true"
    [autoGenerate]="true"
    [rowSelectable]="false"
>
</igx-grid>

rowSelectable="multiple"

<igx-grid rowSelectable="true" >`);

        const tree = await schematicRunner.runSchematicAsync('migration-15', {}, appTree)
            .toPromise();

        expect(tree.readContent('/testSrc/appPrefix/component/input.component.html'))
        .toEqual(`
[rowSelectable]="true"

<igx-grid [data]="data" [primaryKey]="'ProductID'" width="700px" height="400px" [rowEditable]="true"
    [autoGenerate]="true"
    rowSelection="multiple"
>
</igx-grid>

[rowSelectable]="'false'"

<igx-grid [data]="data" [primaryKey]="'ProductID'" width="700px" height="400px" [rowEditable]="true"
    [autoGenerate]="true"
    rowSelection="none"
>
</igx-grid>

rowSelectable="multiple"

<igx-grid rowSelection="multiple" >`);

    });
});


text:
Using Kerberos V5 Network Authentication with the Gateway ![This feature is available in KAAZING Gateway - Enterprise Edition](../images/enterprise-feature.png)
=================================================================================================================================

KAAZING Gateway supports the Kerberos authentication protocol, allowing you to proxy traffic to and from a KDC. This enables clients to communicate to a KDC over WebSocket. A gateway that is configured to proxy Kerberos traffic will be called a Ticket-Granting Gateway (TGG) in this section. This architecture provides all the benefits of a Kerberos-based security system to Web-based clients, without having to compromise overall site security by placing a KDC closer to the edge of the network.

![A gateway configured to proxy Kerberos traffic as a TGG](../images/f-kerberos5-kaazing-model-web.jpg)

**Figure: the Gateway is configured to proxy Kerberos traffic as a TGG**

1.  A KAAZING Gateway client running in a browser makes a request for a ticket from a TGG using a WebSocket-based connection.
2.  The TGG front-ends the KDC and proxies the incoming requests to the KDC, sending a request for a ticket-granting ticket (TGT) to the AS in the KDC.
3.  The AS returns a TGT.
4.  The TGG sends the TGT to the KAAZING Gateway client.
5.  The KAAZING Gateway client now makes a request for a ticket from a TGG using the TGT.
6.  The TGG sends the TGT to the ticket-granting service (TGS) in the KDC to get an encrypted ticket.
7.  The TGS returns encrypted ticket (the session ticket).
8.  The TGG proxies the encrypted ticket to the KAAZING Gateway client and it can now be used to access another service.

You can configure the Gateway to use the services of a KDC to provide Kerberos authentication for ticket-protected services running on the KAAZING Gateway. In this document, we will call a gateway that is configured that way a Ticket Protected Gateway (TPG).

See Also
------------------------------

-   [Configure Kerberos V5 Network Authentication](o_auth_configure.md)
    -   [Configure a Ticket Protected Gateway](p_kerberos_configure_ticket_protected_gateway.md)
    -   [Configure a Ticket Granting Gateway](p_kerberos_configure_ticket_granting_gateway.md)


text:
"""
Copyright 2015 SYSTRAN Software, Inc. All rights reserved.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

from __future__ import absolute_import

import sys
import os

# python 2 and python 3 compatibility library
from six import iteritems

from .. import configuration
from ..api_client import ApiClient

class PoiApi(object):

    def __init__(self, api_client=None):
        if api_client:
            self.api_client = api_client
        else:
            if not configuration.api_client:
                configuration.api_client = ApiClient('https://api-platform.systran.net')
            self.api_client = configuration.api_client

    def geographic_poi_get_get(self, id, **kwargs):
        """
        Get a specific Point of interest
        Get a specific `Point of interest`.

        :param str id: POI identifier (required)
        :param str accept_language: Preferred languages for response localization.\n\nSee [Accept-Language header specification for HTTP\n1.1](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)\n
        :param str callback: Javascript callback function name for JSONP Support\n

        :return: PoiDetailsResponse
        """

        # verify the required parameter 'id' is set
        if id is None:
            raise ValueError("Missing the required parameter `id` when calling `geographic_poi_get_get`")

        all_params = ['id', 'accept_language', 'callback']

        params = locals()
        for key, val in iteritems(params['kwargs']):
            if key not in all_params:
                raise TypeError("Got an unexpected keyword argument '%s' to method geographic_poi_get_get" % key)
            params[key] = val
        del params['kwargs']

        resource_path = '/geographic/poi/get'.replace('{format}', 'json')
        method = 'GET'

        path_params = {}

        query_params = {}

        if 'id' in params:
            query_params['id'] = params['id']

        if 'callback' in params:
            query_params['callback'] = params['callback']

        header_params = {}

        if 'accept_language' in params:
            header_params['Accept-Language'] = params['accept_language']

        form_params = {}
        files = {}

        body_params = None

        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.select_header_accept([])
        if not header_params['Accept']:
            del header_params['Accept']

        # HTTP header `Content-Type`
        header_params['Content-Type'] = self.api_client.select_header_content_type([])

        # Authentication setting
        auth_settings = ['accessToken', 'apiKey']

        response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
                                            body=body_params, post_params=form_params, files=files,
                                            response='PoiDetailsResponse', auth_settings=auth_settings)

        return response

    def geographic_poi_list_get(self, **kwargs):
        """
        List Point of interests\n
        Get a list of `Point of interests`.\n\nThe main criteria can be:\n* a position and a radius\n* a bounding box\n* a textual search\n\nAdditional critera can be added.\n

        :param float latitude: Latitude location. Musts be used together with `longitude` and `radius` parameters.
        :param float longitude: Longitude location. Musts be used together with `latitude` and `radius` parameters.
        :param float radius: Radius in meters. Musts be used together with `latitude` and `longitude` parameters.
        :param float maximum_latitude: Latitude of the top (northernmost) side of the bounding box. Musts be used together with `maximumLongitude`, `minimumLatitude` and `minimumLongitude` parameters.
        :param float maximum_longitude: Longitude of the right (easternmost) side of the bounding box. Musts be used together with `maximumLatitude`, `minimumLatitude` and `minimumLongitude` parameters.
        :param float minimum_latitude: Latitude of the bottom (southernmost) side of the bounding box. Musts be used together with `maximumLatitude`, `maximumLongitude` and `minimumLongitude` parameters.
        :param float minimum_longitude: Longitude of the left (westernmost) side of the bounding box. Musts be used together with `maximumLatitude`, `maximumLongitude` and `minimumLatitude` parameters.
        :param list[str] filter: Filter on all relevent POI data (name, type, address, ...)
        :param list[str] name: POI name
        :param str main_type: POI main type
        :param list[str] type: POI type
        :param str address: POI address
        :param str country: POI country
        :param str state: POI state
        :param str county: POI county
        :param str city: POI city
        :param str postal_code: POI postal code
        :param str street: POI street
        :param str rank_by: Ranking criteria
        :param bool open_now: Only open for business POI
        :param int minimum_rating: Minimum rating (from 1 to 5)
        :param int maximum_rating: Maximum rating (from 1 to 5)
        :param int minimum_price: Minimum price level (from 0 to 3)
        :param int maximum_price: Maximum price level (from 0 to 3)
        :param int limit: Pagination limit
        :param int offset: Pagination offset
        :param str accept_language: Preferred languages for response localization.\n\nSee [Accept-Language header specification for HTTP\n1.1](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)\n
        :param str callback: Javascript callback function name for JSONP Support\n

        :return: PoiResponse
        """

        all_params = ['latitude', 'longitude', 'radius', 'maximum_latitude', 'maximum_longitude', 'minimum_latitude', 'minimum_longitude', 'filter', 'name', 'main_type', 'type', 'address', 'country', 'state', 'county', 'city', 'postal_code', 'street', 'rank_by', 'open_now', 'minimum_rating', 'maximum_rating', 'minimum_price', 'maximum_price', 'limit', 'offset', 'accept_language', 'callback']

        params = locals()
        for key, val in iteritems(params['kwargs']):
            if key not in all_params:
                raise TypeError("Got an unexpected keyword argument '%s' to method geographic_poi_list_get" % key)
            params[key] = val
        del params['kwargs']

        resource_path = '/geographic/poi/list'.replace('{format}', 'json')
        method = 'GET'

        path_params = {}

        query_params = {}

        if 'latitude' in params:
            query_params['latitude'] = params['latitude']

        if 'longitude' in params:
            query_params['longitude'] = params['longitude']

        if 'radius' in params:
            query_params['radius'] = params['radius']

        if 'maximum_latitude' in params:
            query_params['maximumLatitude'] = params['maximum_latitude']

        if 'maximum_longitude' in params:
            query_params['maximumLongitude'] = params['maximum_longitude']

        if 'minimum_latitude' in params:
            query_params['minimumLatitude'] = params['minimum_latitude']

        if 'minimum_longitude' in params:
            query_params['minimumLongitude'] = params['minimum_longitude']

        if 'filter' in params:
            query_params['filter'] = params['filter']

        if 'name' in params:
            query_params['name'] = params['name']

        if 'main_type' in params:
            query_params['mainType'] = params['main_type']

        if 'type' in params:
            query_params['type'] = params['type']

        if 'address' in params:
            query_params['address'] = params['address']

        if 'country' in params:
            query_params['country'] = params['country']

        if 'state' in params:
            query_params['state'] = params['state']

        if 'county' in params:
            query_params['county'] = params['county']

        if 'city' in params:
            query_params['city'] = params['city']

        if 'postal_code' in params:
            query_params['postalCode'] = params['postal_code']

        if 'street' in params:
            query_params['street'] = params['street']

        if 'rank_by' in params:
            query_params['rankBy'] = params['rank_by']

        if 'open_now' in params:
            query_params['openNow'] = params['open_now']

        if 'minimum_rating' in params:
            query_params['minimumRating'] = params['minimum_rating']

        if 'maximum_rating' in params:
            query_params['maximumRating'] = params['maximum_rating']

        if 'minimum_price' in params:
            query_params['minimumPrice'] = params['minimum_price']

        if 'maximum_price' in params:
            query_params['maximumPrice'] = params['maximum_price']

        if 'limit' in params:
            query_params['limit'] = params['limit']

        if 'offset' in params:
            query_params['offset'] = params['offset']

        if 'callback' in params:
            query_params['callback'] = params['callback']

        header_params = {}

        if 'accept_language' in params:
            header_params['Accept-Language'] = params['accept_language']

        form_params = {}
        files = {}

        body_params = None

        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.select_header_accept([])
        if not header_params['Accept']:
            del header_params['Accept']

        # HTTP header `Content-Type`
        header_params['Content-Type'] = self.api_client.select_header_content_type([])

        # Authentication setting
        auth_settings = ['accessToken', 'apiKey']

        response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
                                            body=body_params, post_params=form_params, files=files,
                                            response='PoiResponse', auth_settings=auth_settings)

        return response

    def geographic_poi_types_get(self, **kwargs):
        """
        Get available Point of interest types
        Get available `Point of interest` types.

        :param str accept_language: Preferred languages for response localization.\n\nSee [Accept-Language header specification for HTTP\n1.1](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)\n
        :param str callback: Javascript callback function name for JSONP Support\n

        :return: PoiTypesResponse
        """

        all_params = ['accept_language', 'callback']

        params = locals()
        for key, val in iteritems(params['kwargs']):
            if key not in all_params:
                raise TypeError("Got an unexpected keyword argument '%s' to method geographic_poi_types_get" % key)
            params[key] = val
        del params['kwargs']

        resource_path = '/geographic/poi/types'.replace('{format}', 'json')
        method = 'GET'

        path_params = {}

        query_params = {}

        if 'callback' in params:
            query_params['callback'] = params['callback']

        header_params = {}

        if 'accept_language' in params:
            header_params['Accept-Language'] = params['accept_language']

        form_params = {}
        files = {}

        body_params = None

        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.select_header_accept([])
        if not header_params['Accept']:
            del header_params['Accept']

        # HTTP header `Content-Type`
        header_params['Content-Type'] = self.api_client.select_header_content_type([])

        # Authentication setting
        auth_settings = ['accessToken', 'apiKey']

        response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params,
                                            body=body_params, post_params=form_params, files=files,
                                            response='PoiTypesResponse', auth_settings=auth_settings)

        return response


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.phong.music.MainLayoutActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">
            <Button
                android:id="@+id/btnSearch"
                android:layout_width="35dp"
                android:layout_height="35dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="10dp"
                android:layout_gravity="right"
                android:background="@drawable/search"/>
        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="55dp"
        android:id="@+id/fragment_container"/>
</android.support.design.widget.CoordinatorLayout>


text:
import os
import subprocess

try:
    VERSION = __import__("pkg_resources").get_distribution("changes").version
except Exception:
    VERSION = "unknown"

def _get_git_revision(path):
    try:
        r = subprocess.check_output("git rev-parse HEAD", cwd=path, shell=True)
    except Exception:
        return None

    return r.strip()

def get_revision():
    """
    :returns: Revision number of this branch/checkout, if available. None if
        no revision number can be determined.
    """
    revision = os.environ.get("BUILD_REVISION")
    if revision:
        return revision

    package_dir = os.path.dirname(__file__)
    checkout_dir = os.path.normpath(os.path.join(package_dir, os.pardir))
    path = os.path.join(checkout_dir, ".git")
    if os.path.exists(path):
        return _get_git_revision(path)

    return None

def get_version():
    base = VERSION
    if __build__:
        base = "%s (%s)" % (base, __build__)
    return base

__build__ = get_revision()
__docformat__ = "restructuredtext en"