text:
declare namespace ts {
    function getNodeId(node: Node): number;
    interface Node extends TextRange {
        symbol?: Symbol;                // Symbol declared by node (initialized by binding)
    }

    interface DiagnosticCollection {
        add(diagnostic: Diagnostic): void;
        getGlobalDiagnostics(): Diagnostic[];
        getDiagnostics(fileName?: string): Diagnostic[];
        getModificationCount(): number;
    }

    interface ReferencePathMatchResult {
        fileReference?: FileReference;
        diagnosticMessage?: DiagnosticMessage;
        isNoDefaultLib?: boolean;
    }
    interface SynthesizedNode extends Node {
        leadingCommentRanges?: CommentRange[];
        trailingCommentRanges?: CommentRange[];
        startsOnNewLine: boolean;
    }
    function getDeclarationOfKind(symbol: Symbol, kind: SyntaxKind): Declaration;
    interface StringSymbolWriter extends SymbolWriter {
        string(): string;
    }
    interface EmitHost extends ScriptReferenceHost {
        getSourceFiles(): SourceFile[];
        getCommonSourceDirectory(): string;
        getCanonicalFileName(fileName: string): string;
        getNewLine(): string;
        isEmitBlocked(emitFileName: string): boolean;
        writeFile: WriteFileCallback;
    }
    function getSingleLineStringWriter(): StringSymbolWriter;
    function releaseStringWriter(writer: StringSymbolWriter): void;
    function getFullWidth(node: Node): number;
    function arrayIsEqualTo<T>(array1: T[], array2: T[], equaler?: (a: T, b: T) => boolean): boolean;
    function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean;
    function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule;
    function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModule): void;
    function containsParseError(node: Node): boolean;
    function getSourceFileOfNode(node: Node): SourceFile;
    function getStartPositionOfLine(line: number, sourceFile: SourceFile): number;
    function nodePosToString(node: Node): string;
    function getStartPosOfNode(node: Node): number;
    function nodeIsMissing(node: Node): boolean;
    function nodeIsPresent(node: Node): boolean;
    function getTokenPosOfNode(node: Node, sourceFile?: SourceFile): number;
    function getNonDecoratorTokenPosOfNode(node: Node, sourceFile?: SourceFile): number;
    function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node, includeTrivia?: boolean): string;
    function getTextOfNodeFromSourceText(sourceText: string, node: Node): string;
    function getTextOfNode(node: Node, includeTrivia?: boolean): string;
    function escapeIdentifier(identifier: string): string;
    function unescapeIdentifier(identifier: string): string;
    function makeIdentifierFromModuleName(moduleName: string): string;
    function isBlockOrCatchScoped(declaration: Declaration): boolean;
    function getEnclosingBlockScopeContainer(node: Node): Node;
    function isCatchClauseVariableDeclaration(declaration: Declaration): boolean;
    function declarationNameToString(name: DeclarationName): string;
    function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: any, arg1?: any, arg2?: any): Diagnostic;
    function createDiagnosticForNodeFromMessageChain(node: Node, messageChain: DiagnosticMessageChain): Diagnostic;
    function getSpanOfTokenAtPosition(sourceFile: SourceFile, pos: number): TextSpan;
    function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpan;
    function isExternalModule(file: SourceFile): boolean;
    function isExternalOrCommonJsModule(file: SourceFile): boolean;
    function isDeclarationFile(file: SourceFile): boolean;
    function isConstEnumDeclaration(node: Node): boolean;
    function getCombinedNodeFlags(node: Node): NodeFlags;
    function isConst(node: Node): boolean;
    function isLet(node: Node): boolean;
    function isPrologueDirective(node: Node): boolean;
    function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile): CommentRange[];
    function getLeadingCommentRangesOfNodeFromText(node: Node, text: string): CommentRange[];
    function getJsDocComments(node: Node, sourceFileOfNode: SourceFile): CommentRange[];
    function getJsDocCommentsFromText(node: Node, text: string): CommentRange[];
    let fullTripleSlashReferencePathRegEx: RegExp;
    let fullTripleSlashAMDReferencePathRegEx: RegExp;
    function isTypeNode(node: Node): boolean;
    function forEachReturnStatement<T>(body: Block, visitor: (stmt: ReturnStatement) => T): T;
    function forEachYieldExpression(body: Block, visitor: (expr: YieldExpression) => void): void;
    function isVariableLike(node: Node): node is VariableLikeDeclaration;
    function isAccessor(node: Node): node is AccessorDeclaration;
    function isClassLike(node: Node): node is ClassLikeDeclaration;
    function isFunctionLike(node: Node): node is FunctionLikeDeclaration;
    function isFunctionLikeKind(kind: SyntaxKind): boolean;
    function introducesArgumentsExoticObject(node: Node): boolean;
    function isIterationStatement(node: Node, lookInLabeledStatements: boolean): boolean;
    function isFunctionBlock(node: Node): boolean;
    function isObjectLiteralMethod(node: Node): node is MethodDeclaration;
    // function isIdentifierTypePredicate(predicate: TypePredicate): predicate is IdentifierTypePredicate;
    function getContainingFunction(node: Node): FunctionLikeDeclaration;
    function getContainingClass(node: Node): ClassLikeDeclaration;
    function getThisContainer(node: Node, includeArrowFunctions: boolean): Node;
    /**
      * Given an super call\property node returns a closest node where either
      * - super call\property is legal in the node and not legal in the parent node the node.
      *   i.e. super call is legal in constructor but not legal in the class body.
      * - node is arrow function (so caller might need to call getSuperContainer in case it needs to climb higher)
      * - super call\property is definitely illegal in the node (but might be legal in some subnode)
      *   i.e. super property access is illegal in function declaration but can be legal in the statement list
      */
    function getSuperContainer(node: Node, stopOnFunctions: boolean): Node;
    function getEntityNameFromTypeNode(node: TypeNode): EntityName | Expression;
    function getInvokedExpression(node: CallLikeExpression): Expression;
    function nodeCanBeDecorated(node: Node): boolean;
    function nodeIsDecorated(node: Node): boolean;
    function isPropertyAccessExpression(node: Node): node is PropertyAccessExpression;
    function isElementAccessExpression(node: Node): node is ElementAccessExpression;
    function isExpression(node: Node): boolean;
    function isExternalModuleNameRelative(moduleName: string): boolean;
    function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean;
    function isExternalModuleImportEqualsDeclaration(node: Node): boolean;
    function getExternalModuleImportEqualsDeclarationExpression(node: Node): Expression;
    function isInternalModuleImportEqualsDeclaration(node: Node): node is ImportEqualsDeclaration;
    function isSourceFileJavaScript(file: SourceFile): boolean;
    function isInJavaScriptFile(node: Node): boolean;
    /**
     * Returns true if the node is a CallExpression to the identifier 'require' with
     * exactly one string literal argument.
     * This function does not test if the node is in a JavaScript file or not.
    */
    function isRequireCall(expression: Node): expression is CallExpression;
    // function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind;
    function getExternalModuleName(node: Node): Expression;
    function hasQuestionToken(node: Node): boolean;
    function isJSDocConstructSignature(node: Node): boolean;
    function getJSDocTypeTag(node: Node): JSDocTypeTag;
    function getJSDocReturnTag(node: Node): JSDocReturnTag;
    function getJSDocTemplateTag(node: Node): JSDocTemplateTag;
    function getCorrespondingJSDocParameterTag(parameter: ParameterDeclaration): JSDocParameterTag;
    function hasRestParameter(s: SignatureDeclaration): boolean;
    function isRestParameter(node: ParameterDeclaration): boolean;
    function isLiteralKind(kind: SyntaxKind): boolean;
    function isTextualLiteralKind(kind: SyntaxKind): boolean;
    function isTemplateLiteralKind(kind: SyntaxKind): boolean;
    function isBindingPattern(node: Node): node is BindingPattern;
    function isNodeDescendentOf(node: Node, ancestor: Node): boolean;
    function isInAmbientContext(node: Node): boolean;
    function isDeclaration(node: Node): boolean;
    function isStatement(n: Node): boolean;
    function isClassElement(n: Node): boolean;
    function isDeclarationName(name: Node): name is Identifier | StringLiteral | LiteralExpression;
    function isIdentifierName(node: Identifier): boolean;
    function isAliasSymbolDeclaration(node: Node): boolean;
    function getClassExtendsHeritageClauseElement(node: ClassLikeDeclaration): ExpressionWithTypeArguments;
    function getClassImplementsHeritageClauseElements(node: ClassLikeDeclaration): NodeArray<ExpressionWithTypeArguments>;
    function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray<ExpressionWithTypeArguments>;
    function getHeritageClause(clauses: NodeArray<HeritageClause>, kind: SyntaxKind): HeritageClause;
    function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference): SourceFile;
    function getAncestor(node: Node, kind: SyntaxKind): Node;
    function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult;
    function isKeyword(token: SyntaxKind): boolean;
    function isTrivia(token: SyntaxKind): boolean;
    function isAsyncFunctionLike(node: Node): boolean;
    function isStringOrNumericLiteral(node: Node): boolean;
    /**
     * A declaration has a dynamic name if both of the following are true:
     *   1. The declaration has a computed property name
     *   2. The computed name is *not* expressed as Symbol.<name>, where name
     *      is a property of the Symbol constructor that denotes a built in
     *      Symbol.
     */
    function hasDynamicName(declaration: Declaration): boolean;
    function isDynamicName(name: DeclarationName): boolean;
    /**
     * Checks if the expression is of the form:
     *    Symbol.name
     * where Symbol is literally the word "Symbol", and name is any identifierName
     */
    function isWellKnownSymbolSyntactically(node: Expression): boolean;
    function getPropertyNameForPropertyNameNode(name: DeclarationName): string;
    function getPropertyNameForKnownSymbolName(symbolName: string): string;
    /**
     * Includes the word "Symbol" with unicode escapes
     */
    function isESSymbolIdentifier(node: Node): boolean;
    function isModifierKind(token: SyntaxKind): boolean;
    function isParameterDeclaration(node: VariableLikeDeclaration): boolean;
    function getRootDeclaration(node: Node): Node;
    function nodeStartsNewLexicalEnvironment(n: Node): boolean;
    /**
     * Creates a shallow, memberwise clone of a node. The "kind", "pos", "end", "flags", and "parent"
     * properties are excluded by default, and can be provided via the "location", "flags", and
     * "parent" parameters.
     * @param node The node to clone.
     * @param location An optional TextRange to use to supply the new position.
     * @param flags The NodeFlags to use for the cloned node.
     * @param parent The parent for the new node.
     */
    function cloneNode<T extends Node>(node: T, location?: TextRange, flags?: NodeFlags, parent?: Node): T;
    /**
     * Creates a deep clone of an EntityName, with new parent pointers.
     * @param node The EntityName to clone.
     * @param parent The parent for the cloned node.
     */
    function cloneEntityName(node: EntityName, parent?: Node): EntityName;
    function isQualifiedName(node: Node): node is QualifiedName;
    function nodeIsSynthesized(node: Node): boolean;
    function createSynthesizedNode(kind: SyntaxKind, startsOnNewLine?: boolean): Node;
    function createSynthesizedNodeArray(): NodeArray<any>;
    function createDiagnosticCollection(): DiagnosticCollection;
    /**
     * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
     * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
     * Note that this doesn't actually wrap the input in double quotes.
     */
    function escapeString(s: string): string;
    function isIntrinsicJsxName(name: string): boolean;
    function escapeNonAsciiCharacters(s: string): string;
    interface EmitTextWriter {
        write(s: string): void;
        writeTextOfNode(text: string, node: Node): void;
        writeLine(): void;
        increaseIndent(): void;
        decreaseIndent(): void;
        getText(): string;
        rawWrite(s: string): void;
        writeLiteral(s: string): void;
        getTextPos(): number;
        getLine(): number;
        getColumn(): number;
        getIndent(): number;
        reset(): void;
    }
    function getIndentString(level: number): string;
    function getIndentSize(): number;
    function createTextWriter(newLine: String): EmitTextWriter;
    /**
     * Resolves a local path to a path which is absolute to the base of the emit
     */
    function getExternalModuleNameFromPath(host: EmitHost, fileName: string): string;
    function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string): string;
    function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget;
    function getEmitModuleKind(compilerOptions: CompilerOptions): ModuleKind;
    interface EmitFileNames {
        jsFilePath: string;
        sourceMapFilePath: string;
        declarationFilePath: string;
    }
    function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, targetSourceFile?: SourceFile): void;
    function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string): string;
    function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean): void;
    function getLineOfLocalPosition(currentSourceFile: SourceFile, pos: number): number;
    function getLineOfLocalPositionFromLineMap(lineMap: number[], pos: number): number;
    function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration;
    function getSetAccessorTypeAnnotationNode(accessor: AccessorDeclaration): TypeNode;
    function getAllAccessorDeclarations(declarations: NodeArray<Declaration>, accessor: AccessorDeclaration): {
        firstAccessor: AccessorDeclaration;
        secondAccessor: AccessorDeclaration;
        getAccessor: AccessorDeclaration;
        setAccessor: AccessorDeclaration;
    };
    function emitNewLineBeforeLeadingComments(lineMap: number[], writer: EmitTextWriter, node: TextRange, leadingComments: CommentRange[]): void;
    function emitComments(text: string, lineMap: number[], writer: EmitTextWriter, comments: CommentRange[], trailingSeparator: boolean, newLine: string, writeComment: (text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string) => void): void;
    /**
     * Detached comment is a comment at the top of file or function body that is separated from
     * the next statement by space.
     */
    function emitDetachedComments(text: string, lineMap: number[], writer: EmitTextWriter, writeComment: (text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string) => void, node: TextRange, newLine: string, removeComments: boolean): {
        nodePos: number;
        detachedCommentEndPos: number;
    };
    function writeCommentRange(text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string): void;
    function modifierToFlag(token: SyntaxKind): NodeFlags;
    function isLeftHandSideExpression(expr: Expression): boolean;
    function isAssignmentOperator(token: SyntaxKind): boolean;
    function isExpressionWithTypeArgumentsInClassExtendsClause(node: Node): boolean;
    function isSupportedExpressionWithTypeArguments(node: ExpressionWithTypeArguments): boolean;
    function isRightSideOfQualifiedNameOrPropertyAccess(node: Node): boolean;
    function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean;
    function getLocalSymbolForExportDefault(symbol: Symbol): Symbol;
    function hasJavaScriptFileExtension(fileName: string): boolean;
    /**
     * Serialize an object graph into a JSON string. This is intended only for use on an acyclic graph
     * as the fallback implementation does not check for circular references by default.
     */
    const stringify: (value: any) => string;
    /**
     * Converts a string to a base-64 encoded ASCII string.
     */
    function convertToBase64(input: string): string;
    function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string;
    function getNewLineCharacter(options: CompilerOptions): string;
}


text:
<!doctype html>

  {% include head.html %}

    {% include header.html %}

		{{ content }}

    {% include footer.html %}
    {% include footerlogic.html %}

redpajama_set_name: RedPajamaGithub


text:
from filebeat import BaseTest
import os

"""
Contains tests for filtering.
"""

class Test(BaseTest):
    def test_dropfields(self):
        """
        Check drop_fields filtering action
        """
        self.render_config_template(
            path=os.path.abspath(self.working_dir) + "/test.log",
            drop_fields={
                "fields": ["beat"],
            },
        )
        with open(self.working_dir + "/test.log", "w") as f:
            f.write("test message\n")

        filebeat = self.start_beat()
        self.wait_until(lambda: self.output_has(lines=1))
        filebeat.check_kill_and_wait()

        output = self.read_output(
            required_fields=["@timestamp", "type"],
        )[0]
        assert "beat.name" not in output
        assert "message" in output

    def test_include_fields(self):
        """
        Check drop_fields filtering action
        """
        self.render_config_template(
            path=os.path.abspath(self.working_dir) + "/test.log",
            include_fields={
                "fields": ["source", "offset", "message"],
            },
        )
        with open(self.working_dir + "/test.log", "w") as f:
            f.write("test message\n")

        filebeat = self.start_beat()
        self.wait_until(lambda: self.output_has(lines=1))
        filebeat.check_kill_and_wait()

        output = self.read_output(
            required_fields=["@timestamp", "type"],
        )[0]
        assert "beat.name" not in output
        assert "message" in output

    def test_drop_event(self):
        """
        Check drop_event filtering action
        """
        self.render_config_template(
            path=os.path.abspath(self.working_dir) + "/test*.log",
            drop_event={
                "condition": "contains.source: test1",
            },
        )
        with open(self.working_dir + "/test1.log", "w") as f:
            f.write("test1 message\n")

        with open(self.working_dir + "/test2.log", "w") as f:
            f.write("test2 message\n")

        filebeat = self.start_beat()
        self.wait_until(lambda: self.output_has(lines=1))
        filebeat.check_kill_and_wait()

        output = self.read_output(
            required_fields=["@timestamp", "type"],
        )[0]
        assert "beat.name" in output
        assert "message" in output
        assert "test" in output["message"]


text:
package it.polito.softeng.lombokmigrator;

import it.polito.softeng.LombokMigrator;
import it.polito.softeng.MigrationLogic;
import japa.parser.ParseException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: federico
 * Date: 10/4/13
 * Time: 11:51 AM
 * To change this template use File | Settings | File Templates.
 */
public class MigrationLogicTest {
    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testGetterBooleanRemoval() throws IOException, ParseException {
        String code = "class A { private boolean a;\nboolean isA(){return this.a;}\n}";
        LombokMigrator lm = new LombokMigrator();
        assertEquals("class A {\n\n    @Getter()\n    private boolean a;\n}\n",lm.migrateCodeToString(code));
    }

    @Test
    public void testGetterRemoval() throws IOException, ParseException {
        String code = "class A { private String a;\nString getA(){return this.a;}\n}";
        LombokMigrator lm = new LombokMigrator();
        assertEquals("class A {\n\n    @Getter()\n    private String a;\n}\n",lm.migrateCodeToString(code));
    }

    @Test
    public void testSetterRemoval() throws IOException, ParseException {
        String code = "class A { private String a;\nvoid setA(String a){this.a=a;}\n}";
        LombokMigrator lm = new LombokMigrator();
        assertEquals("class A {\n\n    @Setter()\n    private String a;\n}\n",lm.migrateCodeToString(code));
    }
}


text:
using Newtonsoft.Json;
using QuickBooks.Net.Data.Models.Fields;

namespace QuickBooks.Net.Data.Models
{
    public class Class : QuickBooksBaseModelString
    {

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
        public string Name { get; set; }

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
        public bool SubClass { get; set; }

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
        public Ref ParentRef { get; set; }

        [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
        public string FullyQualifiedName { get; set; }

        public bool Active { get; set; }

        internal override QuickBooksBaseModelString CreateReturnObject()
        {
            return new Class
            {
                Id = Id,
                Name = Name,
                SubClass = SubClass,
                ParentRef = ParentRef,
                FullyQualifiedName = FullyQualifiedName,
                Active = Active
            };
        }

        internal override QuickBooksBaseModelString UpdateReturnObject()
        {
            return this;
        }

        internal override QuickBooksBaseModelString DeleteReturnObject()
        {
            return new Class
            {
                Id = Id,
                SyncToken = SyncToken,
                Active = false,
                Name = Name
            };
        }
    }
}


text:
@interface DPFactoryMethodTests : XCTestCase

@end

@implementation DPFactoryMethodTests

- (void)testFactoryMethod {
    id<DPLeiFengFactory> leiFengFactory = [[DPUndergraduateFactory alloc] init];
//    id<DPLeiFengFactory> leiFengFactory = [[DPVolunteerFactory alloc] init];

    id<DPLeiFeng> studentA = [leiFengFactory createLeiFeng];
    [studentA sweep];
    [studentA wash];
    [studentA buyRice];

    id<DPLeiFeng> studentB = [leiFengFactory createLeiFeng];
    [studentB sweep];
    [studentB wash];
    [studentB buyRice];

    id<DPLeiFeng> studentC = [leiFengFactory createLeiFeng];
    [studentC sweep];
    [studentC wash];
    [studentC buyRice];
}

@end


text:
import { Text, View, Platform, Image, ScrollView } from 'react-native';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import I18n from 'react-native-i18n';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import NavigationBar from 'react-native-navbar';

import { setHomeTab } from '@actions/globals';
import { openDrawer } from '@actions/drawer';
import { replaceRoute, pushNewRoute, popRoute } from '@actions/route';

import Constants from '@src/constants';
import { Metrics, Styles, Colors, Fonts, Icon } from '@theme/';
import styles from './styles';
import CommonWidgets from '@components/CommonWidgets';
import DashboardItem from '@components/DashboardItem';
import CampHistoryCell from '@components/MenuView/CampHistoryCell';

class CampHistory extends Component {
  render() {
    return (
      <View style={{ flex: 1, backgroundColor: 'white' }}>
        {CommonWidgets.renderStatusBar(Colors.brandPrimary) }
        <NavigationBar
          style={Styles.navBarStyle}
          title={CommonWidgets.renderNavBarHeader(I18n.t('CAMP_HISTORY'))}
          tintColor={Colors.brandSecondary}
          leftButton={CommonWidgets.renderNavBarLeftButton(() => this.props.popRoute())}
          rightButton={CommonWidgets.renderNavBarLeftButton(() => {}, 'menu')} />

        <ScrollView>
          <CampHistoryCell onPress={() => this.props.pushNewRoute('campHistoryDetail')} />
        </ScrollView>
      </View>
    );
  }
}

CampHistory.propTypes = {
  dispatch: React.PropTypes.func.isRequired,
  setHomeTab: React.PropTypes.func.isRequired,
  replaceRoute: React.PropTypes.func.isRequired,
  popRoute: React.PropTypes.func.isRequired,
  pushNewRoute: React.PropTypes.func.isRequired,
  openDrawer: React.PropTypes.func.isRequired,
};

function mapDispatchToProps(dispatch) {
  return {
    dispatch,
    setHomeTab: homeTab => dispatch(setHomeTab(homeTab)),
    openDrawer: () => dispatch(openDrawer()),
    replaceRoute: route => dispatch(replaceRoute(route)),
    pushNewRoute: route => dispatch(pushNewRoute(route)),
    popRoute: () => dispatch(popRoute()),
  };
}

function mapStateToProps(state) {
  const globals = state.get('globals');
  return { globals };
}

export default connect(mapStateToProps, mapDispatchToProps)(CampHistory);


text:
package ragefist.packets;

import com.juniform.JUniformMutableObject;
import com.juniform.JUniformObject;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatcher;
import static org.mockito.Mockito.*;
import ragefist.core.distribution.DistributedServerController;
import ragefist.core.distribution.DistributedServerController.DistributedServerControllerAPI;
import ragefist.core.network.Connection;

public class PacketHandlerRPCTest
{
	private DistributedServerController _controller;
	private DistributedServerControllerAPI _controllerAPI;
	private PacketHandlerRPC _packetHandler;

	private class ObjectEqualityArgumentMatcher<T> extends ArgumentMatcher<T> {
		T matchObject;
		public ObjectEqualityArgumentMatcher(T thisObject) {
			this.matchObject = thisObject;
		}

		@Override
		public boolean matches(Object argument) {
			return argument.equals(matchObject);
		}
	}

	@Before
	public void setUp() {
		_controller    = mock(DistributedServerController.class);
		_packetHandler = new PacketHandlerRPC(_controllerAPI);
	}

	@Test
	public void testExecuteNullRequest() {
		ArgumentMatcher matcher = new ArgumentMatcher<JUniformObject>() {
			@Override
			public boolean matches(Object argument) {
				JUniformObject object = (JUniformObject)argument;
				boolean result =
					object != null &&
					object.getProperty("rs").toInteger() == 0 &&
					object.getProperty("error").toString().equals("ERROR_UNKNOWN_ACTION")
				;
				if (result == false) System.out.println(object);
				return result;
			}
		};

		Connection connection = mock(Connection.class);
		_packetHandler.handlePacket(JUniformObject.OBJECT_NIL, connection);
		verify(connection, times(1)).sendPacket((JUniformObject)argThat(matcher));
	}

	@Test
	public void testExecuteNoSequenceNumberRequest() {
		JUniformMutableObject packet = JUniformMutableObject.newMap();
		packet.setProperty("action", "ExecuteCode");

		ArgumentMatcher matcher = new ArgumentMatcher<JUniformObject>() {
			@Override
			public boolean matches(Object argument) {
				JUniformObject object = (JUniformObject)argument;
				boolean result =
					object != null &&
					object.getProperty("rs").toInteger() == 0 &&
					object.getProperty("error").toString().equals("ERROR_BAD_PACKET")
				;
				if (result == false) System.out.println(object);
				return result;
			}
		};

		Connection connection = mock(Connection.class);
		_packetHandler.handlePacket(packet, connection);
		verify(connection, times(1)).sendPacket((JUniformObject)argThat(matcher));
	}

	@Test
	public void testExecuteNoDataRequest() {
		JUniformMutableObject packet = JUniformMutableObject.newMap();
		packet.setProperty("action", "ExecuteCode");
		packet.setProperty("sq", 1);

		ArgumentMatcher matcher = new ArgumentMatcher<JUniformObject>() {
			@Override
			public boolean matches(Object argument) {
				JUniformObject object = (JUniformObject)argument;
				boolean result =
					object != null &&
					object.getProperty("rs").toInteger() == 0 &&
					object.getProperty("error").toString().equals("ERROR_BAD_DATA")
				;
				if (result == false) System.out.println(object);
				return result;
			}
		};

		Connection connection = mock(Connection.class);
		_packetHandler.handlePacket(packet, connection);
		verify(connection, times(1)).sendPacket((JUniformObject)argThat(matcher));
	}

	@Test
	public void testExecuteNoDataEnvironmentRequest() {
		JUniformMutableObject packet = JUniformMutableObject.newMap();
		packet.setProperty("action", "ExecuteCode");
		packet.setProperty("sq", 1);
		packet.setProperty("data", JUniformMutableObject.newMap());

		ArgumentMatcher matcher = new ArgumentMatcher<JUniformObject>() {
			@Override
			public boolean matches(Object argument) {
				JUniformObject object = (JUniformObject)argument;
				boolean result =
					object != null &&
					object.getProperty("rs").toInteger() == 0 &&
					object.getProperty("error").toString().equals("ERROR_BAD_ENVIRONMENT")
				;
				if (result == false) System.out.println(object);
				return result;
			}
		};

		Connection connection = mock(Connection.class);
		_packetHandler.handlePacket(packet, connection);
		verify(connection, times(1)).sendPacket((JUniformObject)argThat(matcher));
	}
}


text:
ClassMethods
============

.. toctree::
   :maxdepth: 3
   :titlesonly:

Constants
---------

Files
-----

  * `lib/neo4j/active_node/validations.rb:16 <https://github.com/neo4jrb/neo4j/blob/master/lib/neo4j/active_node/validations.rb#L16>`_

Methods
-------

.. _`Neo4j/ActiveNode/Validations/ClassMethods#validates_uniqueness_of`:

**#validates_uniqueness_of**

  .. hidden-code-block:: ruby

     def validates_uniqueness_of(*attr_names)
       validates_with UniquenessValidator, _merge_attributes(attr_names)
     end


text:
using namespace std;

// ----- ReadGraph -----
// Referring to ymatsux-san's source code: https://atcoder.jp/contests/abc138/submissions/7016619

struct Edge
{
  int src, dst, id, rev;
  // ll cost;
  Edge() {}
  Edge(int src, int dst, int id, int rev) : src{src}, dst{dst}, id{id}, rev{rev} {}

  void added_edge(vector<vector<Edge>> &V)
  {
    V[src].push_back(*this);
  }

  void added_rev(vector<vector<Edge>> &V)
  {
    V[dst].push_back(rev_edge());
  }

  Edge rev_edge()
  {
    Edge edge{*this};
    swap(edge.src, edge.dst);
    swap(edge.id, edge.rev);
    return edge;
  }
};

enum class GraphType
{
  Undirected,
  Directed,
  RevEdge,
};

tuple<vector<vector<Edge>>, vector<Edge>> ReadGraphWithEdges(int N, int M, GraphType type = GraphType::Undirected, bool is_one_indexed = true)
{
  vector<vector<Edge>> V(N);
  vector<Edge> E;
  for (auto i = 0; i < M; ++i)
  {
    int v, w;
    cin >> v >> w;
    if (is_one_indexed)
    {
      --v;
      --w;
    }
    switch (type)
    {
    case GraphType::Undirected:
    {
      Edge edge{v, w, static_cast<int>(E.size()), static_cast<int>(E.size())};
      edge.added_edge(V);
      edge.added_rev(V);
      E.push_back(edge);
      break;
    }
    case GraphType::Directed:
    {
      Edge edge{v, w, static_cast<int>(E.size()), static_cast<int>(E.size())};
      edge.added_edge(V);
      E.push_back(edge);
      break;
    }
    case GraphType::RevEdge:
    {
      Edge edge{v, w, static_cast<int>(E.size()), static_cast<int>(E.size()) + 1};
      edge.added_edge(V);
      edge.added_rev(V);
      E.push_back(edge);
      E.push_back(edge.rev_edge());
      break;
    }
    default:
      break;
    }
  }
  return make_tuple(V, E);
}

vector<vector<Edge>> ReadGraph(int N, int M, GraphType type = GraphType::Undirected, bool is_one_indexed = true)
{
  return get<0>(ReadGraphWithEdges(N, M, type, is_one_indexed));
}

tuple<vector<vector<Edge>>, vector<Edge>> ReadTreeWithEdges(int N, GraphType type = GraphType::Undirected, bool is_one_indexed = true)
{
  return ReadGraphWithEdges(N, N - 1, type, is_one_indexed);
}

vector<vector<Edge>> ReadTree(int N, GraphType type = GraphType::Undirected, bool is_one_indexed = true)
{
  return ReadGraph(N, N - 1, type, is_one_indexed);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _01.ReverseString
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = Console.ReadLine();

            char[] arrChar = input.ToCharArray().Reverse().ToArray();
            Console.WriteLine(string.Join("", arrChar));
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<Definitions>
    <Application id="id01" name="testapp">
		<confs>
		  <property key="serde.simpleserde.separator" value=","/>
		  <property key="operator.kafka.brokers" value="158.1.130.12:9092"/>
		</confs>
        <Schemas>
            <Schema id="s01">
                <name>n03</name>
                <attribute name="c1" type="java.lang.String"/>
                <attribute name="c2" type="java.lang.Integer"/>
            </Schema>
            <Schema unkown="false" name="n02">
                <attribute name="c3" type="java.lang.String"/>
                <attribute name="c4" type="java.lang.Integer"/>
            </Schema>
            <Schema id="unkown" name="n03">
                <attribute name="类型" type="java.lang.String"/>
            </Schema>
        </Schemas>
        <Operators>
            <KafkaInput id="id1" name="name1" parallel="1">
                <properties>
                    <property key="zookeeper.port" value="2180"/>
                    <property key="zookeeper.ip.address" value="localhost"/>
                </properties>
                <deserializer class="SimpleSerDe">
                    <separator>|</separator>
                </deserializer>
                <groupId>g1</groupId>
                <zookeepers>localhost:2181</zookeepers>
            </KafkaInput>
            <KafkaInput id="id2" name="name2" parallel="1">
                <properties>
                    <property key="zookeeper.port" value="2180"/>
                    <property key="zookeeper.ip.address" value="localhost"/>
                </properties>
                <deserializer class="SimpleSerDe" id="reader2">
                    <serde.simpleserde.separator>|</serde.simpleserde.separator>
                </deserializer>
                <groupId>g1</groupId>
                <zookeepers>localhost:2181</zookeepers>
            </KafkaInput>
            <Filter id="id3" name="name3" parallel="1">
                <properties>
                    <property key="filter.optimizer" value="com.huawei.optimizer.filter"/>
                </properties>
                <filterExpression>(a<=1) or (a>10) and b is not null and c in
                    ('1','2','3')
                </filterExpression>
            </Filter>
            <Join id="id5" name="name5" parallel="1">
                <properties>
                    <property key="join.type" value="hashjoini"/>
                </properties>
                <outputExpression>udf(c1),to_String(c4)</outputExpression>
                <leftStreamName>s3</leftStreamName>
                <rightStreamName>s4</rightStreamName>
                <leftWindow name="keepall"/>
                <rightWindow name="time_slide">
                    <length>100</length>
                </rightWindow>
                <joinType>INNER_JOIN</joinType>
                <joinExpression>name3.c1 = name4.c1 and name3.c2 = name4.c4+2
                </joinExpression>
                <filterAfterJoinExpression>name4.c1<10
                </filterAfterJoinExpression>
            </Join>
            <Filter id="id6" name="name6" parallel="1">
                <properties>
                    <property key="filter.before.window" value="true"/>
                </properties>
                <filterExpression>c3<=1</filterExpression>
            </Filter>
            <TCPOutput id="id7" name="name7" parallel="1">
                <properties>
                    <property key="split" value="|"/>
                </properties>
                <serializer class="SimpleSerDe" id="writer">
                    <serde.simpleserde.separator>,</serde.simpleserde.separator>
                </serializer>
                <server>localhost</server>
                <port>10000</port>
            </TCPOutput>
        </Operators>
        <Transitions>
            <Transition id="s1" streamName="s1" from="id1" to="id3">
                <distributedType>SHUFFLE</distributedType>
                <schemaName>s01</schemaName>
            </Transition>
            <Transition id="s2" streamName="s2" from="id2" to="id5">
                <distributedType>FIELDS</distributedType>
                <distributedFields>id,name</distributedFields>
                <schemaName>s02</schemaName>
            </Transition>
            <Transition id="s3" streamName="s3" from="id3" to="id5">
                <distributedType>FIELDS</distributedType>
                <distributedFields>id,name</distributedFields>
                <schemaName>s01</schemaName>
            </Transition>
            <Transition id="s4" streamName="s4" from="id5" to="id6">
                <distributedType>SHUFFLE</distributedType>
                <schemaName>s01</schemaName>
            </Transition>
            <Transition id="s5" streamName="s5" from="id6" to="id7">
                <distributedType>SHUFFLE</distributedType>
                <schemaName>s01</schemaName>
            </Transition>
        </Transitions>
    </Application>
</Definitions>


text:
require 'spec_helper'

describe "organizations/index" do
  before(:each) do
    assign(:organizations, [
      stub_model(Organization),
      stub_model(Organization)
    ])
  end

  it "renders a list of organizations" do
    render
    # Run the generator again with the --webrat flag if you want to use webrat matchers
  end
end


text:
<?php
class DBConnection
{
	private $servername;
	private	$dbuser;
	private	$password;
	private	$dbName;
	public $conn;

	function __construct()
	{
			$this->servername = "localhost";
			$this->dbuser = "root";
			$this->password = "";
			$this->dbName = "russelioshoes";
			$this->conn = new mysqli($this->servername, $this->dbuser, $this->password, $this->dbName);
	}

	function getInstance()
	{
					/* Connect */
		if($this->conn->connect_error){
			die("Connection failed: " . $conn->connect_error);
		}
		else return $this->conn;
	}
}
?>


text:
function usage {
    echo "Usage: $0 COMPUTED EXPECTED NFIELDS MESSAGE [-zero THR]" 1>&2
    exit 1
}

# Check for files and number of fields
COMPUTED="$1"
EXPECTED="$2"
NFIELDS="$3"
MESSAGE="$4"
if [ ! -f "$COMPUTED" ]; then echo "Missing computed value file" 1>&2; usage; fi
if [ ! -f "$EXPECTED" ]; then echo "Missing expected value file" 1>&2; usage; fi
if [ "$NFIELDS" == "" ]; then echo "Missing number of fields" 1>&2; usage; fi
if [ "$MESSAGE" == "" ]; then echo "Missing descriptive error message" 1>&2; usage; fi

# Parse optional arguments
THRESHOLD="1.0e-6"
if [ $# -ge 5 ]
then
    shift;shift;shift;shift
    while [ "$1" != "" ]
    do
        case $1 in
            -zero) shift;THRESHOLD=$1;echo "$0: new zero level set to $THRESHOLD";;
            *) echo "$0: no option \"$1\"" 1>&2;;
        esac
        shift
    done
fi

# Trap result.tmp file
trap "rm -f result.tmp" 0 1 2 3 8 9

# Compare computed and expected values
paste $COMPUTED $EXPECTED |\
    awk '{
        for (i=1;i<='$NFIELDS';i++) {
            computed = $i
            expected = $('$NFIELDS'+i)
            diff = computed - expected

            # Absolute value of difference
            if (diff<0) {
                diff = -diff
            }

            # Absolute value of expected (defined by user)
            if (expected<0) {
                expected_abs = -expected
            } else {
                expected_abs = expected
            }

            # Compare calculated difference with allowed threshold difference
            if (expected_abs<'"$THRESHOLD"'/10) {
                if (diff>'"$THRESHOLD"') {
                    print "FAIL",NR
                    printf("computed %14.6e\n"),computed > "/dev/stderr"
                    printf("expected %14.6e\n"),expected > "/dev/stderr"
                    exit
                } else {
                    print "PASS"
                }
            } else {
                if (diff/expected_abs>'"$THRESHOLD"') {
                    print "FAIL",NR
                    printf("computed %16.8e\n"),computed > "/dev/stderr"
                    printf("expected %16.8e\n"),expected > "/dev/stderr"
                    exit
                } else {
                    print "PASS"
                }
            }
        }
    }' > result.tmp
FAIL=`grep FAIL result.tmp`
if [ "$FAIL" != "" ]
then
    echo "Failed test $MESSAGE" 1>&2
    echo
    OFFENDING_LINE=$(echo $FAIL | awk '{print $2}')
    echo "Offending line of \"$COMPUTED\" is line $OFFENDING_LINE:" 1>&2
    sed -ne "${OFFENDING_LINE}p" $COMPUTED 1>&2
    echo
    echo "Expected to see:" 1>&2
    sed -ne "${OFFENDING_LINE}p" $EXPECTED 1>&2
    exit 1
fi


text:
import Ember from 'ember';
import { githubCommit as githubCommitUrl } from 'travis/utils/urls';
import TravisRoute from 'travis/routes/basic';
import config from 'travis/config/environment';

export default Ember.Component.extend({
  routing: Ember.inject.service('-routing'),
  tagName: 'li',
  classNameBindings: ['build.last_build.state'],
  classNames: ['branch-row', 'row-li'],
  isLoading: false,
  isTriggering: false,
  hasTriggered: false,

  urlGithubCommit: function() {
    return githubCommitUrl(this.get('build.repository.slug'), this.get('build.last_build.commit.sha'));
  }.property('build.last_build'),

  getLast5Builds: function() {
    var apiEndpoint, branchName, lastBuilds, options, repoId;
    lastBuilds = Ember.ArrayProxy.create({
      content: [{}, {}, {}, {}, {}],
      isLoading: true,
      count: 0
    });
    if (!this.get('build.last_build')) {
      lastBuilds.set('isLoading', false);
    } else {
      apiEndpoint = config.apiEndpoint;
      repoId = this.get('build.repository.id');
      branchName = this.get('build.name');
      options = {};
      if (this.get('auth.signedIn')) {
        options.headers = {
          Authorization: "token " + (this.auth.token())
        };
      }
      $.ajax(apiEndpoint + "/v3/repo/" + repoId + "/builds?branch.name=" + branchName + "&limit=5&build.event_type=push,api", options).then(function(response) {
        var array, i, j, ref;
        array = response.builds.map(function(build) {
          return Ember.Object.create(build);
        });
        if (array.length < 5) {
          for (i = j = 1, ref = 5 - array.length; j <= ref; i = j += 1) {
            array.push({});
          }
        }
        lastBuilds.set('count', response['@pagination'].count);
        lastBuilds.set('content', array);
        return lastBuilds.set('isLoading', false);
      });
    }
    return lastBuilds;
  }.property(),

  canTrigger: function() {
    var permissions;
    if (!this.get('auth.signedIn')) {
      return false;
    } else {
      permissions = this.get('auth.currentUser.permissions');
      if (permissions.contains(parseInt(this.get('build.repository.id')))) {
        return true;
      } else {
        return false;
      }
    }
  }.property(),

  triggerBuild: function() {
    var apiEndpoint, options, repoId;
    apiEndpoint = config.apiEndpoint;
    repoId = this.get('build.repository.id');
    options = {
      type: 'POST',
      body: {
        request: {
          branch: this.get('build.name')
        }
      }
    };
    if (this.get('auth.signedIn')) {
      options.headers = {
        Authorization: "token " + (this.auth.token())
      };
    }
    return $.ajax(apiEndpoint + "/v3/repo/" + repoId + "/requests", options).then(() => {
      this.set('isTriggering', false);
      return this.set('hasTriggered', true);
    });
  },

  actions: {
    tiggerBuild(branch) {
      this.set('isTriggering', true);
      return this.triggerBuild();
    },

    viewAllBuilds(branch) {
      return this.get('routing').transitionTo('builds');
    }
  }
});


text:
class CreateDemands < ActiveRecord::Migration[5.2]
  def change
    create_table :demands do |t|
      t.integer :user_id
      t.integer :item_id
      t.integer :message_id

      t.timestamps null: false
    end
    add_index :demands, :user_id
    add_index :demands, :item_id
    add_index :demands, :message_id
  end
end


text:
package spotify

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"
	"time"
)

func TestFeaturedPlaylists(t *testing.T) {
	client, server := testClientFile(http.StatusOK, "test_data/featured_playlists.txt")
	defer server.Close()

	country := "SE"

	msg, p, err := client.FeaturedPlaylists(context.Background(), Country(country))
	if err != nil {
		t.Error(err)
		return
	}
	if msg != "New Music Friday!" {
		t.Errorf("Want 'Enjoy a mellow afternoon.', got'%s'\n", msg)
	}
	if p.Playlists == nil || len(p.Playlists) == 0 {
		t.Fatal("Empty playlists result")
	}
	expected := "New Music Friday Sweden"
	if name := p.Playlists[0].Name; name != expected {
		t.Errorf("Want '%s', got '%s'\n", expected, name)
	}
	expected = "Äntligen fredag och ny musik! Happy New Music Friday!"
	if desc := p.Playlists[0].Description; desc != expected {
		t.Errorf("Want '%s', got '%s'\n", expected, desc)
	}

}

func TestFeaturedPlaylistsExpiredToken(t *testing.T) {
	json := `{
		"error": {
			"status": 401,
			"message": "The access token expired"
		}
	}`
	client, server := testClientString(http.StatusUnauthorized, json)
	defer server.Close()

	msg, pl, err := client.FeaturedPlaylists(context.Background())
	if msg != "" || pl != nil || err == nil {
		t.Fatal("Expected an error")
	}
	serr, ok := err.(Error)
	if !ok {
		t.Fatalf("Expected spotify Error, got %T", err)
	}
	if serr.Status != http.StatusUnauthorized {
		t.Error("Expected HTTP 401")
	}
}

func TestPlaylistsForUser(t *testing.T) {
	client, server := testClientFile(http.StatusOK, "test_data/playlists_for_user.txt")
	defer server.Close()

	playlists, err := client.GetPlaylistsForUser(context.Background(), "whizler")
	if err != nil {
		t.Error(err)
	}
	if l := len(playlists.Playlists); l == 0 {
		t.Fatal("Didn't get any results")
	} else if l != 7 {
		t.Errorf("Got %d playlists, expected 7\n", l)
	}

	p := playlists.Playlists[0]
	if p.Name != "Top 40" {
		t.Error("Expected Top 40, got", p.Name)
	}
	if p.Tracks.Total != 40 {
		t.Error("Expected 40 tracks, got", p.Tracks.Total)
	}
	expected := "Nederlandse Top 40, de enige echte hitlijst van Nederland! Official Dutch Top 40. Check top40.nl voor alle details en luister iedere vrijdag vanaf 14.00 uur naar de lijst op Qmusic met Domien Verschuuren."
	if p.Description != expected {
		t.Errorf("Expected '%s', got '%s'\n", expected, p.Description)
	}

}

func TestGetPlaylist(t *testing.T) {
	client, server := testClientFile(http.StatusOK, "test_data/get_playlist.txt")
	defer server.Close()

	p, err := client.GetPlaylist(context.Background(), "1h9q8vXXDl2vHOmwdsuXms")
	if err != nil {
		t.Error(err)
	}
	if p.Collaborative {
		t.Error("Playlist shouldn't be collaborative")
	}
	if p.Description != "Bit of a overlap with phonk but whatever" {
		t.Error("Description is invalid")
	}

	// Ensure the Description field is also present in the SimplePlaylist part of the object
	if p.SimplePlaylist.Description != "Bit of a overlap with phonk but whatever" {
		t.Error("Description is invalid in the SimplePlaylist part of the object")
	}
}

func TestGetPlaylistOpt(t *testing.T) {
	client, server := testClientFile(http.StatusOK, "test_data/get_playlist_opt.txt")
	defer server.Close()

	fields := "href,name,owner(!href,external_urls),tracks.items(added_by.id,track(name,href,album(name,href)))"
	p, err := client.GetPlaylist(context.Background(), "59ZbFPES4DQwEjBpWHzrtC", Fields(fields))
	if err != nil {
		t.Error(err)
	}
	if p.Collaborative {
		t.Error("Playlist shouldn't be collaborative")
	}
	if p.Description != "" {
		t.Error("No description should be included")
	}
	// A bit counterintuitive, but we excluded tracks.total from the API call so it should be 0 in the model.
	if p.Tracks.Total != 0 {
		t.Errorf("Tracks.Total should be 0, got %d", p.Tracks.Total)
	}
}

func TestFollowPlaylistSetsContentType(t *testing.T) {
	client, server := testClientString(http.StatusOK, "", func(req *http.Request) {
		if req.Header.Get("Content-Type") != "application/json" {
			t.Error("Follow playlist request didn't contain Content-Type: application/json")
		}
	})
	defer server.Close()

	err := client.FollowPlaylist(context.Background(), "playlistID", true)
	if err != nil {
		t.Error(err)
	}
}

func TestGetPlaylistTracks(t *testing.T) {
	client, server := testClientFile(http.StatusOK, "test_data/playlist_tracks.txt")
	defer server.Close()

	tracks, err := client.GetPlaylistTracks(context.Background(), "5lH9NjOeJvctAO92ZrKQNB")
	if err != nil {
		t.Error(err)
	}
	if tracks.Total != 40 {
		t.Errorf("Got %d tracks, expected 40\n", tracks.Total)
	}
	if len(tracks.Tracks) == 0 {
		t.Fatal("No tracks returned")
	}
	expected := "Calm Down"
	actual := tracks.Tracks[0].Track.Name
	if expected != actual {
		t.Errorf("Got '%s', expected '%s'\n", actual, expected)
	}
	added := tracks.Tracks[0].AddedAt
	tm, err := time.Parse(TimestampLayout, added)
	if err != nil {
		t.Error(err)
	}
	if f := tm.Format(DateLayout); f != "2022-07-15" {
		t.Errorf("Expected added at 2022-07-15, got %s\n", f)
	}
}

func TestGetPlaylistItemsEpisodes(t *testing.T) {
	client, server := testClientFile(http.StatusOK, "test_data/playlist_items_episodes.json")
	defer server.Close()

	tracks, err := client.GetPlaylistItems(context.Background(), "playlistID")
	if err != nil {
		t.Error(err)
	}
	if tracks.Total != 4 {
		t.Errorf("Got %d tracks, expected 47\n", tracks.Total)
	}
	if len(tracks.Items) == 0 {
		t.Fatal("No tracks returned")
	}
	expected := "112: Dirty Coms"
	actual := tracks.Items[0].Track.Episode.Name
	if expected != actual {
		t.Errorf("Got '%s', expected '%s'\n", actual, expected)
	}
	added := tracks.Items[0].AddedAt
	tm, err := time.Parse(TimestampLayout, added)
	if err != nil {
		t.Error(err)
	}
	if f := tm.Format(DateLayout); f != "2022-05-20" {
		t.Errorf("Expected added at 2014-11-25, got %s\n", f)
	}
}

func TestGetPlaylistItemsTracks(t *testing.T) {
	client, server := testClientFile(http.StatusOK, "test_data/playlist_items_tracks.json")
	defer server.Close()

	tracks, err := client.GetPlaylistItems(context.Background(), "playlistID")
	if err != nil {
		t.Error(err)
	}
	if tracks.Total != 2 {
		t.Errorf("Got %d tracks, expected 47\n", tracks.Total)
	}
	if len(tracks.Items) == 0 {
		t.Fatal("No tracks returned")
	}
	expected := "Typhoons"
	actual := tracks.Items[0].Track.Track.Name
	if expected != actual {
		t.Errorf("Got '%s', expected '%s'\n", actual, expected)
	}
	added := tracks.Items[0].AddedAt
	tm, err := time.Parse(TimestampLayout, added)
	if err != nil {
		t.Error(err)
	}
	if f := tm.Format(DateLayout); f != "2022-05-20" {
		t.Errorf("Expected added at 2014-11-25, got %s\n", f)
	}
}

func TestGetPlaylistItemsTracksAndEpisodes(t *testing.T) {
	client, server := testClientFile(http.StatusOK, "test_data/playlist_items_episodes_and_tracks.json")
	defer server.Close()

	tracks, err := client.GetPlaylistItems(context.Background(), "playlistID")
	if err != nil {
		t.Error(err)
	}
	if tracks.Total != 4 {
		t.Errorf("Got %d tracks, expected 47\n", tracks.Total)
	}
	if len(tracks.Items) == 0 {
		t.Fatal("No tracks returned")
	}

	expected := "491- The Missing Middle"
	actual := tracks.Items[0].Track.Episode.Name
	if expected != actual {
		t.Errorf("Got '%s', expected '%s'\n", actual, expected)
	}
	added := tracks.Items[0].AddedAt
	tm, err := time.Parse(TimestampLayout, added)
	if err != nil {
		t.Error(err)
	}
	if f := tm.Format(DateLayout); f != "2022-05-20" {
		t.Errorf("Expected added at 2014-11-25, got %s\n", f)
	}

	expected = "Typhoons"
	actual = tracks.Items[2].Track.Track.Name
	if expected != actual {
		t.Errorf("Got '%s', expected '%s'\n", actual, expected)
	}
	added = tracks.Items[0].AddedAt
	tm, err = time.Parse(TimestampLayout, added)
	if err != nil {
		t.Error(err)
	}
	if f := tm.Format(DateLayout); f != "2022-05-20" {
		t.Errorf("Expected added at 2014-11-25, got %s\n", f)
	}
}

func TestGetPlaylistItemsOverride(t *testing.T) {
	var types string
	client, server := testClientString(http.StatusForbidden, "", func(r *http.Request) {
		types = r.URL.Query().Get("additional_types")
	})
	defer server.Close()

	_, _ = client.GetPlaylistItems(context.Background(), "playlistID", AdditionalTypes(EpisodeAdditionalType))

	if types != "episode" {
		t.Errorf("Expected additional type episode, got %s\n", types)
	}
}

func TestGetPlaylistItemsDefault(t *testing.T) {
	var types string
	client, server := testClientString(http.StatusForbidden, "", func(r *http.Request) {
		types = r.URL.Query().Get("additional_types")
	})
	defer server.Close()

	_, _ = client.GetPlaylistItems(context.Background(), "playlistID")

	if types != "episode,track" {
		t.Errorf("Expected additional type episode, got %s\n", types)
	}
}

func TestUserFollowsPlaylist(t *testing.T) {
	client, server := testClientString(http.StatusOK, `[ true, false ]`)
	defer server.Close()

	follows, err := client.UserFollowsPlaylist(context.Background(), ID("2v3iNvBS8Ay1Gt2uXtUKUT"), "possan", "elogain")
	if err != nil {
		t.Error(err)
	}
	if len(follows) != 2 || !follows[0] || follows[1] {
		t.Errorf("Expected '[true, false]', got %#v\n", follows)
	}
}

// NOTE collaborative is a fmt boolean.
var newPlaylist = `
{
"collaborative": %t,
"description": "Test Description",
"external_urls": {
	"spotify": "api.http://open.spotify.com/user/thelinmichael/playlist/7d2D2S200NyUE5KYs80PwO"
},
"followers": {
	"href": null,
	"total": 0
},
"href": "https://api.spotify.com/v1/users/thelinmichael/playlists/7d2D2S200NyUE5KYs80PwO",
"id": "7d2D2S200NyUE5KYs80PwO",
"images": [ ],
"name": "A New Playlist",
"owner": {
	"external_urls": {
	"spotify": "api.http://open.spotify.com/user/thelinmichael"
	},
	"href": "https://api.spotify.com/v1/users/thelinmichael",
	"id": "thelinmichael",
	"type": "user",
	"url": "spotify:user:thelinmichael"
},
"public": false,
"snapshot_id": "s0o3TSuYnRLl2jch+oA4OEbKwq/fNxhGBkSPnvhZdmWjNV0q3uCAWuGIhEx8SHIx",
"tracks": {
	"href": "https://api.spotify.com/v1/users/thelinmichael/playlists/7d2D2S200NyUE5KYs80PwO/tracks",
	"items": [ ],
	"limit": 100,
	"next": null,
	"offset": 0,
	"previous": null,
	"total": 0
},
"type": "playlist",
"url": "spotify:user:thelinmichael:playlist:7d2D2S200NyUE5KYs80PwO"
}`

func TestCreatePlaylist(t *testing.T) {
	client, server := testClientString(http.StatusCreated, fmt.Sprintf(newPlaylist, false))
	defer server.Close()

	p, err := client.CreatePlaylistForUser(context.Background(), "thelinmichael", "A New Playlist", "Test Description", false, false)
	if err != nil {
		t.Error(err)
	}
	if p.IsPublic {
		t.Error("Expected private playlist, got public")
	}
	if p.Name != "A New Playlist" {
		t.Errorf("Expected 'A New Playlist', got '%s'\n", p.Name)
	}
	if p.Description != "Test Description" {
		t.Errorf("Expected 'Test Description', got '%s'\n", p.Description)
	}
	if p.Tracks.Total != 0 {
		t.Error("Expected new playlist to be empty")
	}
	if p.Collaborative {
		t.Error("Expected non-collaborative playlist, got collaborative")
	}
}

func TestCreateCollaborativePlaylist(t *testing.T) {
	client, server := testClientString(http.StatusCreated, fmt.Sprintf(newPlaylist, true))
	defer server.Close()

	p, err := client.CreatePlaylistForUser(context.Background(), "thelinmichael", "A New Playlist", "Test Description", false, true)
	if err != nil {
		t.Error(err)
	}
	if p.IsPublic {
		t.Error("Expected private playlist, got public")
	}
	if p.Name != "A New Playlist" {
		t.Errorf("Expected 'A New Playlist', got '%s'\n", p.Name)
	}
	if p.Description != "Test Description" {
		t.Errorf("Expected 'Test Description', got '%s'\n", p.Description)
	}
	if p.Tracks.Total != 0 {
		t.Error("Expected new playlist to be empty")
	}
	if !p.Collaborative {
		t.Error("Expected collaborative playlist, got non-collaborative")
	}
}

func TestRenamePlaylist(t *testing.T) {
	client, server := testClientString(http.StatusOK, "")
	defer server.Close()

	if err := client.ChangePlaylistName(context.Background(), ID("playlist-id"), "new name"); err != nil {
		t.Error(err)
	}
}

func TestChangePlaylistAccess(t *testing.T) {
	client, server := testClientString(http.StatusOK, "")
	defer server.Close()

	if err := client.ChangePlaylistAccess(context.Background(), ID("playlist-id"), true); err != nil {
		t.Error(err)
	}
}

func TestChangePlaylistDescription(t *testing.T) {
	client, server := testClientString(http.StatusOK, "")
	defer server.Close()

	if err := client.ChangePlaylistDescription(context.Background(), ID("playlist-id"), "new description"); err != nil {
		t.Error(err)
	}
}

func TestChangePlaylistNameAndAccess(t *testing.T) {
	client, server := testClientString(http.StatusOK, "")
	defer server.Close()

	if err := client.ChangePlaylistNameAndAccess(context.Background(), ID("playlist-id"), "new_name", true); err != nil {
		t.Error(err)
	}
}

func TestChangePlaylistNameAccessAndDescription(t *testing.T) {
	client, server := testClientString(http.StatusOK, "")
	defer server.Close()

	if err := client.ChangePlaylistNameAccessAndDescription(context.Background(), ID("playlist-id"), "new_name", "new description", true); err != nil {
		t.Error(err)
	}
}

func TestChangePlaylistNameFailure(t *testing.T) {
	client, server := testClientString(http.StatusForbidden, "")
	defer server.Close()

	if err := client.ChangePlaylistName(context.Background(), ID("playlist-id"), "new_name"); err == nil {
		t.Error("Expected error but didn't get one")
	}
}

func TestAddTracksToPlaylist(t *testing.T) {
	client, server := testClientString(http.StatusCreated, `{ "snapshot_id" : "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" }`)
	defer server.Close()

	snapshot, err := client.AddTracksToPlaylist(context.Background(), ID("playlist_id"), ID("track1"), ID("track2"))
	if err != nil {
		t.Error(err)
	}
	if snapshot != "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" {
		t.Error("Didn't get expected snapshot ID")
	}
}

func TestRemoveTracksFromPlaylist(t *testing.T) {
	client, server := testClientString(http.StatusOK, `{ "snapshot_id" : "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" }`, func(req *http.Request) {
		requestBody, err := ioutil.ReadAll(req.Body)
		if err != nil {
			t.Fatal("Could not read request body:", err)
		}

		var body map[string]interface{}
		err = json.Unmarshal(requestBody, &body)
		if err != nil {
			t.Fatal("Error decoding request body:", err)
		}
		tracksArray, ok := body["tracks"]
		if !ok {
			t.Error("No tracks JSON object in request body")
		}
		tracksSlice := tracksArray.([]interface{})
		if l := len(tracksSlice); l != 2 {
			t.Fatalf("Expected 2 tracks, got %d\n", l)
		}
		track0 := tracksSlice[0].(map[string]interface{})
		trackURI, ok := track0["uri"]
		if !ok {
			t.Error("Track object doesn't contain 'uri' field")
		}
		if trackURI != "spotify:track:track1" {
			t.Errorf("Expected URI: 'spotify:track:track1', got '%s'\n", trackURI)
		}
	})
	defer server.Close()

	snapshotID, err := client.RemoveTracksFromPlaylist(context.Background(), "playlistID", "track1", "track2")
	if err != nil {
		t.Error(err)
	}
	if snapshotID != "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" {
		t.Error("Incorrect snapshot ID")
	}
}

func TestRemoveTracksFromPlaylistOpt(t *testing.T) {
	client, server := testClientString(http.StatusOK, `{ "snapshot_id" : "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" }`, func(req *http.Request) {
		requestBody, err := ioutil.ReadAll(req.Body)
		if err != nil {
			t.Fatal(err)
		}

		var body map[string]interface{}
		err = json.Unmarshal(requestBody, &body)
		if err != nil {
			t.Fatal(err)
		}
		if _, ok := body["snapshot_id"]; ok {
			t.Error("JSON contains snapshot_id field when none was specified")
			fmt.Println(string(requestBody))
			return
		}
		jsonTracks := body["tracks"].([]interface{})
		if len(jsonTracks) != 3 {
			t.Fatal("Expected 3 tracks, got", len(jsonTracks))
		}
		track1 := jsonTracks[1].(map[string]interface{})
		expected := "spotify:track:track1"
		if track1["uri"] != expected {
			t.Fatalf("Want '%s', got '%s'\n", expected, track1["uri"])
		}
		indices := track1["positions"].([]interface{})
		if len(indices) != 1 || int(indices[0].(float64)) != 9 {
			t.Error("Track indices incorrect")
		}
	})
	defer server.Close()

	tracks := []TrackToRemove{
		NewTrackToRemove("track0", []int{0, 4}), // remove track0 in position 0 and 4
		NewTrackToRemove("track1", []int{9}),    // remove track1 in position 9...
		NewTrackToRemove("track2", []int{8}),
	}
	// intentionally not passing a snapshot ID here
	snapshotID, err := client.RemoveTracksFromPlaylistOpt(context.Background(), "playlistID", tracks, "")
	if err != nil || snapshotID != "JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+" {
		t.Fatal("Remove call failed. err=", err)
	}
}

func TestClient_ReplacePlaylistItems(t *testing.T) {
	type clientFields struct {
		httpCode int
		body     string
	}
	type args struct {
		ctx        context.Context
		playlistID ID
		items      []URI
	}
	type want struct {
		requestBody string
		snapshot    string
		err         string
	}
	tests := []struct {
		name         string
		clientFields clientFields
		args         args
		want         want
	}{
		{
			name: "Happy path",
			clientFields: clientFields{
				httpCode: http.StatusCreated,
				body:     `{"snapshot_id": "test_snapshot"}`,
			},
			args: args{
				ctx:        context.TODO(),
				playlistID: "playlistID",
				items:      []URI{"spotify:track:track1", "spotify:track:track2"},
			},
			want: want{
				requestBody: `{"uris":["spotify:track:track1","spotify:track:track2"]}`,
				snapshot:    "test_snapshot",
			},
		}, {
			name: "Forbidden",
			clientFields: clientFields{
				httpCode: http.StatusForbidden,
			},
			args: args{
				ctx:        context.TODO(),
				playlistID: "playlistID",
				items:      []URI{"spotify:track:track1", "spotify:track:track2"},
			},
			want: want{
				err: "spotify: HTTP 403: Forbidden (body empty)",
			},
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			var gotRequestBody string

			c, server := testClientString(tt.clientFields.httpCode, tt.clientFields.body, func(request *http.Request) {
				b, err := ioutil.ReadAll(request.Body)
				defer request.Body.Close()
				if err != nil {
					t.Error(err)
				}

				gotRequestBody = string(b)
			})
			defer server.Close()

			gotSnapshot, gotErr := c.ReplacePlaylistItems(tt.args.ctx, tt.args.playlistID, tt.args.items...)
			if gotErr == nil && tt.want.err != "" {
				t.Errorf("Expected an error %s, got nil", tt.want.err)
				return
			}
			if gotErr != nil {
				if gotErr.Error() != tt.want.err {
					t.Errorf("Expected error %s, got %s", tt.want.err, gotErr)
				}

				return
			}

			if gotSnapshot != tt.want.snapshot {
				t.Errorf("Expected snapshot %s, got %s", tt.want.snapshot, gotSnapshot)
			}

			if gotRequestBody != tt.want.requestBody {
				t.Errorf("Expected requestBody %s, got %s", tt.want.requestBody, gotRequestBody)
			}
		})
	}
}

func TestReplacePlaylistTracks(t *testing.T) {
	client, server := testClientString(http.StatusCreated, "")
	defer server.Close()

	err := client.ReplacePlaylistTracks(context.Background(), "playlistID", "track1", "track2")
	if err != nil {
		t.Error(err)
	}
}

func TestReplacePlaylistTracksForbidden(t *testing.T) {
	client, server := testClientString(http.StatusForbidden, "")
	defer server.Close()

	err := client.ReplacePlaylistTracks(context.Background(), "playlistID", "track1", "track2")
	if err == nil {
		t.Error("Replace succeeded but shouldn't have")
	}
}

func TestReorderPlaylistRequest(t *testing.T) {
	client, server := testClientString(http.StatusNotFound, "", func(req *http.Request) {
		if ct := req.Header.Get("Content-Type"); ct != "application/json" {
			t.Errorf("Expected Content-Type: application/json, got '%s'\n", ct)
		}
		if req.Method != "PUT" {
			t.Errorf("Expected a PUT, got a %s\n", req.Method)
		}
		// unmarshal the JSON into a map[string]interface{}
		// so we can test for existence of certain keys
		var body map[string]interface{}
		err := json.NewDecoder(req.Body).Decode(&body)
		if err != nil {
			t.Errorf("Expected no error, got %v", err)
		}

		if start, ok := body["range_start"]; ok {
			if start != float64(3) {
				t.Errorf("Expected range_start to be 3, but it was %#v\n", start)
			}
		} else {
			t.Errorf("Required field range_start is missing")
		}

		if ib, ok := body["insert_before"]; ok {
			if ib != float64(8) {
				t.Errorf("Expected insert_before to be 8, but it was %#v\n", ib)
			}
		} else {
			t.Errorf("Required field insert_before is missing")
		}

		if _, ok := body["range_length"]; ok {
			t.Error("Parameter range_length shouldn't have been in body")
		}
		if _, ok := body["snapshot_id"]; ok {
			t.Error("Parameter snapshot_id shouldn't have been in body")
		}
	})
	defer server.Close()

	_, err := client.ReorderPlaylistTracks(context.Background(), "playlist", PlaylistReorderOptions{
		RangeStart:   3,
		InsertBefore: 8,
	})
	if err == nil || !strings.Contains(err.Error(), "HTTP 404: Not Found") {
		t.Errorf("Expected error 'spotify: HTTP 404: Not Found (body empty)', got %v", err)
	}
}

func TestSetPlaylistImage(t *testing.T) {
	client, server := testClientString(http.StatusAccepted, "", func(req *http.Request) {
		if ct := req.Header.Get("Content-Type"); ct != "image/jpeg" {
			t.Errorf("wrong content type, got %s, want image/jpeg", ct)
		}
		if req.Method != "PUT" {
			t.Errorf("expected a PUT, got a %s\n", req.Method)
		}
		body, err := ioutil.ReadAll(req.Body)
		if err != nil {
			t.Fatal(err)
		}

		if !bytes.Equal(body, []byte("Zm9v")) {
			t.Errorf("invalid request body: want Zm9v, got %s", string(body))
		}
	})
	defer server.Close()

	err := client.SetPlaylistImage(context.Background(), "playlist", bytes.NewReader([]byte("foo")))
	if err != nil {
		t.Fatal(err)
	}
}


text:
package squidpony.squidai;

import squidpony.squidgrid.Radius;
import squidpony.squidgrid.Spill;
import squidpony.squidmath.Coord;
import squidpony.squidmath.LightRNG;
import squidpony.squidmath.RNG;

import java.util.*;

/**
 * An AOE type that has a center and a volume, and will randomly expand in all directions until it reaches volume or
 * cannot expand further. Specify the RadiusType as Radius.DIAMOND for Manhattan distance (and the best results),
 * RADIUS.SQUARE for Chebyshev, or RADIUS.CIRCLE for Euclidean. You can specify a seed for the RNG and a fresh RNG will
 * be used for all random expansion; the RNG will reset to the specified seed after each generation so the same
 * CloudAOE can be used in different places by just changing the center. You can cause the CloudAOE to not reset after
 * generating each time by using setExpanding(true) and cause it to reset after the next generation by setting it back
 * to the default of false. If expanding is true, then multiple calls to findArea with the same center and larger
 * volumes will produce more solid clumps of affected area with fewer gaps, and can be spaced out over multiple calls.
 *
 * This will produce doubles for its findArea() method which are equal to 1.0.
 *
 * This class uses squidpony.squidgrid.Spill to create its area of effect.
 * Created by Tommy Ettinger on 7/13/2015.
 */
public class CloudAOE implements AOE {
    private Spill spill;
    private Coord center, origin = null;
    private int volume;
    private long seed;
    private boolean expanding;
    private Radius rt, limitType = null;
    private int minRange = 1, maxRange = 1;
    private Radius metric = Radius.SQUARE;
    private char[][] dungeon;

    public CloudAOE(Coord center, int volume, Radius radiusType)
    {
        LightRNG l = new LightRNG();
        this.seed = l.getState();
        this.spill = new Spill(new RNG(l));
        this.center = center;
        this.volume = volume;
        this.expanding = false;
        rt = radiusType;
        switch (radiusType)
        {
            case SPHERE:
            case CIRCLE: this.spill.measurement = Spill.Measurement.EUCLIDEAN;
                break;
            case CUBE:
            case SQUARE: this.spill.measurement = Spill.Measurement.CHEBYSHEV;
                break;
            default: this.spill.measurement = Spill.Measurement.MANHATTAN;
                break;
        }
    }

    public CloudAOE(Coord center, int volume, Radius radiusType, int minRange, int maxRange)
    {
        LightRNG l = new LightRNG();
        this.seed = l.getState();
        this.spill = new Spill(new RNG(l));
        this.center = center;
        this.volume = volume;
        this.expanding = false;
        rt = radiusType;
        this.minRange = minRange;
        this.maxRange = maxRange;
        switch (radiusType)
        {
            case SPHERE:
            case CIRCLE: this.spill.measurement = Spill.Measurement.EUCLIDEAN;
                break;
            case CUBE:
            case SQUARE: this.spill.measurement = Spill.Measurement.CHEBYSHEV;
                break;
            default: this.spill.measurement = Spill.Measurement.MANHATTAN;
                break;
        }
    }
    public CloudAOE(Coord center, int volume, Radius radiusType, long rngSeed)
    {
        this.seed = rngSeed;
        this.spill = new Spill(new RNG(new LightRNG(rngSeed)));
        this.center = center;
        this.volume = volume;
        this.expanding = false;
        rt = radiusType;
        switch (radiusType)
        {
            case SPHERE:
            case CIRCLE: this.spill.measurement = Spill.Measurement.EUCLIDEAN;
                break;
            case CUBE:
            case SQUARE: this.spill.measurement = Spill.Measurement.CHEBYSHEV;
                break;
            default: this.spill.measurement = Spill.Measurement.MANHATTAN;
                break;
        }
    }
    public CloudAOE(Coord center, int volume, Radius radiusType, long rngSeed, int minRange, int maxRange)
    {
        this.seed = rngSeed;
        this.spill = new Spill(new RNG(new LightRNG(rngSeed)));
        this.center = center;
        this.volume = volume;
        this.expanding = false;
        rt = radiusType;
        switch (radiusType)
        {
            case SPHERE:
            case CIRCLE: this.spill.measurement = Spill.Measurement.EUCLIDEAN;
                break;
            case CUBE:
            case SQUARE: this.spill.measurement = Spill.Measurement.CHEBYSHEV;
                break;
            default: this.spill.measurement = Spill.Measurement.MANHATTAN;
                break;
        }
        this.minRange = minRange;
        this.maxRange = maxRange;
    }

    public Coord getCenter() {
        return center;
    }

    public void setCenter(Coord center) {
        if (AreaUtils.verifyLimit(limitType, origin, center)) {
            this.center = center;
        }
    }

    public int getVolume() {
        return volume;
    }

    public void setVolume(int volume) {
        this.volume = volume;
    }

    public Radius getRadiusType() {
        return rt;
    }

    public void setRadiusType(Radius radiusType) {
        rt = radiusType;
        switch (radiusType)
        {
            case SPHERE:
            case CIRCLE:
                break;
            case CUBE:
            case SQUARE:
                break;
            default:
                break;
        }
    }

    @Override
    public void shift(Coord aim) {
        setCenter(aim);
    }

    @Override
    public boolean mayContainTarget(Set<Coord> targets) {
        for (Coord p : targets)
        {
            if(rt.radius(center.x, center.y, p.x, p.y) <= Math.sqrt(volume) * 0.75)
                return true;
        }
        return false;
    }

    @Override
    public LinkedHashMap<Coord, ArrayList<Coord>> idealLocations(Set<Coord> targets, Set<Coord> requiredExclusions) {
        if(targets == null)
            return new LinkedHashMap<Coord, ArrayList<Coord>>();
        if(requiredExclusions == null) requiredExclusions = new LinkedHashSet<Coord>();

        //requiredExclusions.remove(origin);
        int totalTargets = targets.size();
        LinkedHashMap<Coord, ArrayList<Coord>> bestPoints = new LinkedHashMap<Coord, ArrayList<Coord>>(totalTargets * 8);

        if(totalTargets == 0 || volume <= 0)
            return bestPoints;

        if(volume == 1)
        {
            for(Coord p : targets)
            {
                ArrayList<Coord> ap = new ArrayList<Coord>();
                ap.add(p);
                bestPoints.put(p, ap);
            }
            return bestPoints;
        }
        Coord[] ts = targets.toArray(new Coord[targets.size()]);
        Coord[] exs = requiredExclusions.toArray(new Coord[requiredExclusions.size()]);
        Coord t = exs[0];

        double[][][] compositeMap = new double[ts.length][dungeon.length][dungeon[0].length];

        Spill sp;

        char[][] dungeonCopy = new char[dungeon.length][dungeon[0].length];
        for (int i = 0; i < dungeon.length; i++) {
            System.arraycopy(dungeon[i], 0, dungeonCopy[i], 0, dungeon[i].length);
        }

        Coord tempPt = Coord.get(0, 0);
        for (int i = 0; i < exs.length; ++i) {
            t = exs[i];
            sp = new Spill(dungeon, spill.measurement);
            sp.lrng.setState(this.seed);

            sp.start(t, volume, null);
            for (int x = 0; x < dungeon.length; x++) {
                tempPt = tempPt.setX(x);
                for (int y = 0; y < dungeon[x].length; y++) {
                    tempPt = tempPt.setY(y);
                    dungeonCopy[x][y] = (sp.spillMap[x][y] || !AreaUtils.verifyLimit(limitType, origin, tempPt)) ? '!' : dungeonCopy[x][y];
                }
            }
        }

        t = ts[0];

        DijkstraMap.Measurement dmm = DijkstraMap.Measurement.MANHATTAN;
        if(spill.measurement == Spill.Measurement.CHEBYSHEV) dmm = DijkstraMap.Measurement.CHEBYSHEV;
        else if(spill.measurement == Spill.Measurement.EUCLIDEAN) dmm = DijkstraMap.Measurement.EUCLIDEAN;

        double radius = Math.sqrt(volume) * 0.75;

        for (int i = 0; i < ts.length; ++i) {
            DijkstraMap dm = new DijkstraMap(dungeon, dmm);

            t = ts[i];
            sp = new Spill(dungeon, spill.measurement);
            sp.lrng.setState(this.seed);

            sp.start(t, volume, null);

            double dist = 0.0;
            for (int x = 0; x < dungeon.length; x++) {
                for (int y = 0; y < dungeon[x].length; y++) {
                    if (sp.spillMap[x][y]){
                        dist = metric.radius(origin.x, origin.y, x, y);
                        if(dist <= maxRange + radius && dist >= minRange - radius)
                            compositeMap[i][x][y] = dm.physicalMap[x][y];
                        else
                            compositeMap[i][x][y] = DijkstraMap.WALL;
                    }
                    else compositeMap[i][x][y] = DijkstraMap.WALL;
                }
            }
            if(compositeMap[i][ts[i].x][ts[i].y] > DijkstraMap.FLOOR)
            {
                for (int x = 0; x < dungeon.length; x++) {
                    Arrays.fill(compositeMap[i][x], 99999.0);
                }
                continue;
            }

            dm.initialize(compositeMap[i]);
            dm.setGoal(t);
            dm.scan(null);
            for (int x = 0; x < dungeon.length; x++) {
                for (int y = 0; y < dungeon[x].length; y++) {
                    compositeMap[i][x][y] = (dm.gradientMap[x][y] < DijkstraMap.FLOOR  && dungeonCopy[x][y] != '!') ? dm.gradientMap[x][y] : 99999.0;
                }
            }
            dm.resetMap();
            dm.clearGoals();
        }
        double bestQuality = 99999 * ts.length;
        double[][] qualityMap = new double[dungeon.length][dungeon[0].length];
        for (int x = 0; x < qualityMap.length; x++) {
            for (int y = 0; y < qualityMap[x].length; y++) {
                qualityMap[x][y] = 0.0;
                long bits = 0;
                for (int i = 0; i < ts.length; ++i) {
                    qualityMap[x][y] += compositeMap[i][x][y];
                    if(compositeMap[i][x][y] < 99999.0 && i < 63)
                        bits |= 1 << i;
                }
                if(qualityMap[x][y] < bestQuality)
                {
                    ArrayList<Coord> ap = new ArrayList<Coord>();

                    for (int i = 0; i < ts.length && i < 63; ++i) {
                        if((bits & (1 << i)) != 0)
                            ap.add(ts[i]);
                    }

                    if(ap.size() > 0) {
                        bestQuality = qualityMap[x][y];
                        bestPoints.clear();
                        bestPoints.put(Coord.get(x, y), ap);
                    }
                }
                else if(qualityMap[x][y] == bestQuality)
                {
                    ArrayList<Coord> ap = new ArrayList<Coord>();

                    for (int i = 0; i < ts.length && i < 63; ++i) {
                        if((bits & (1 << i)) != 0)
                            ap.add(ts[i]);
                    }

                    if (ap.size() > 0) {
                        bestPoints.put(Coord.get(x, y), ap);
                    }
                }
            }
        }

        return bestPoints;
    }

    @Override
    public LinkedHashMap<Coord, ArrayList<Coord>> idealLocations(Set<Coord> priorityTargets, Set<Coord> lesserTargets, Set<Coord> requiredExclusions) {
        if(priorityTargets == null)
            return idealLocations(lesserTargets, requiredExclusions);
        if(requiredExclusions == null) requiredExclusions = new LinkedHashSet<Coord>();

        //requiredExclusions.remove(origin);

        int totalTargets = priorityTargets.size() + lesserTargets.size();
        LinkedHashMap<Coord, ArrayList<Coord>> bestPoints = new LinkedHashMap<Coord, ArrayList<Coord>>(totalTargets * 8);

        if(totalTargets == 0 || volume <= 0)
            return bestPoints;

        if(volume == 1)
        {
            for(Coord p : priorityTargets)
            {
                ArrayList<Coord> ap = new ArrayList<Coord>();
                ap.add(p);
                bestPoints.put(p, ap);
            }
            return bestPoints;
        }
        Coord[] pts = priorityTargets.toArray(new Coord[priorityTargets.size()]);
        Coord[] lts = lesserTargets.toArray(new Coord[lesserTargets.size()]);
        Coord[] exs = requiredExclusions.toArray(new Coord[requiredExclusions.size()]);
        Coord t = exs[0];

        double[][][] compositeMap = new double[totalTargets][dungeon.length][dungeon[0].length];
        Spill sp;

        char[][] dungeonCopy = new char[dungeon.length][dungeon[0].length],
                dungeonPriorities = new char[dungeon.length][dungeon[0].length];
        for (int i = 0; i < dungeon.length; i++) {
            System.arraycopy(dungeon[i], 0, dungeonCopy[i], 0, dungeon[i].length);
            Arrays.fill(dungeonPriorities[i], '#');
        }
        Coord tempPt = Coord.get(0, 0);
        for (int i = 0; i < exs.length; ++i) {
            t = exs[i];
            sp = new Spill(dungeon, spill.measurement);
            sp.lrng.setState(this.seed);

            sp.start(t, volume, null);
            for (int x = 0; x < dungeon.length; x++) {
                tempPt = tempPt.setX(x);
                for (int y = 0; y < dungeon[x].length; y++) {
                    tempPt = tempPt.setY(y);
                    dungeonCopy[x][y] = (sp.spillMap[x][y] || !AreaUtils.verifyLimit(limitType, origin, tempPt)) ? '!' : dungeonCopy[x][y];
                }
            }
        }

        t = pts[0];

        DijkstraMap.Measurement dmm = DijkstraMap.Measurement.MANHATTAN;
        if(spill.measurement == Spill.Measurement.CHEBYSHEV) dmm = DijkstraMap.Measurement.CHEBYSHEV;
        else if(spill.measurement == Spill.Measurement.EUCLIDEAN) dmm = DijkstraMap.Measurement.EUCLIDEAN;

        double radius = Math.sqrt(volume) * 0.75;

        for (int i = 0; i < pts.length; ++i) {
            DijkstraMap dm = new DijkstraMap(dungeon, dmm);

            t = pts[i];
            sp = new Spill(dungeon, spill.measurement);
            sp.lrng.setState(this.seed);

            sp.start(t, volume, null);

            double dist = 0.0;
            for (int x = 0; x < dungeon.length; x++) {
                for (int y = 0; y < dungeon[x].length; y++) {
                    if (sp.spillMap[x][y]){
                        dist = metric.radius(origin.x, origin.y, x, y);
                        if(dist <= maxRange + radius && dist >= minRange - radius) {
                            compositeMap[i][x][y] = dm.physicalMap[x][y];
                            dungeonPriorities[x][y] = dungeon[x][y];
                        }
                        else
                            compositeMap[i][x][y] = DijkstraMap.WALL;
                    }
                    else compositeMap[i][x][y] = DijkstraMap.WALL;
                }
            }
            if(compositeMap[i][pts[i].x][pts[i].y] > DijkstraMap.FLOOR)
            {
                for (int x = 0; x < dungeon.length; x++) {
                    Arrays.fill(compositeMap[i][x], 399999.0);
                }
                continue;
            }

            dm.initialize(compositeMap[i]);
            dm.setGoal(t);
            dm.scan(null);
            for (int x = 0; x < dungeon.length; x++) {
                for (int y = 0; y < dungeon[x].length; y++) {
                    compositeMap[i][x][y] = (dm.gradientMap[x][y] < DijkstraMap.FLOOR  && dungeonCopy[x][y] != '!') ? dm.gradientMap[x][y] : 399999.0;
                }
            }
            dm.resetMap();
            dm.clearGoals();
        }

        t = lts[0];

        for (int i = pts.length; i < totalTargets; ++i) {
            DijkstraMap dm = new DijkstraMap(dungeon, dmm);

            t = lts[i - pts.length];
            sp = new Spill(dungeon, spill.measurement);
            sp.lrng.setState(this.seed);

            sp.start(t, volume, null);

            double dist = 0.0;
            for (int x = 0; x < dungeon.length; x++) {
                for (int y = 0; y < dungeon[x].length; y++) {
                    if (sp.spillMap[x][y]){
                        dist = metric.radius(origin.x, origin.y, x, y);
                        if(dist <= maxRange + radius && dist >= minRange - radius)
                            compositeMap[i][x][y] = dm.physicalMap[x][y];
                        else
                            compositeMap[i][x][y] = DijkstraMap.WALL;
                    }
                    else compositeMap[i][x][y] = DijkstraMap.WALL;
                }
            }
            if(compositeMap[i][lts[i - pts.length].x][lts[i - pts.length].y] > DijkstraMap.FLOOR)
            {
                for (int x = 0; x < dungeon.length; x++)
                {
                    Arrays.fill(compositeMap[i][x], 99999.0);
                }
                continue;
            }

            dm.initialize(compositeMap[i]);
            dm.setGoal(t);
            dm.scan(null);
            for (int x = 0; x < dungeon.length; x++) {
                for (int y = 0; y < dungeon[x].length; y++) {
                    compositeMap[i][x][y] = (dm.gradientMap[x][y] < DijkstraMap.FLOOR  && dungeonCopy[x][y] != '!' && dungeonPriorities[x][y] != '#') ? dm.gradientMap[x][y] : 99999.0;
                }
            }
            dm.resetMap();
            dm.clearGoals();
        }
        double bestQuality = 99999 * lts.length + 399999 * pts.length;
        double[][] qualityMap = new double[dungeon.length][dungeon[0].length];
        for (int x = 0; x < qualityMap.length; x++) {
            for (int y = 0; y < qualityMap[x].length; y++) {
                qualityMap[x][y] = 0.0;
                long pbits = 0, lbits = 0;
                for (int i = 0; i < pts.length; ++i) {
                    qualityMap[x][y] += compositeMap[i][x][y];
                    if(compositeMap[i][x][y] < 399999.0 && i < 63)
                        pbits |= 1 << i;
                }
                for (int i = pts.length; i < totalTargets; ++i) {
                    qualityMap[x][y] += compositeMap[i][x][y];
                    if(compositeMap[i][x][y] < 99999.0 && i < 63)
                        lbits |= 1 << i;
                }
                if(qualityMap[x][y] < bestQuality)
                {
                    ArrayList<Coord> ap = new ArrayList<Coord>();

                    for (int i = 0; i < pts.length && i < 63; ++i) {
                        if((pbits & (1 << i)) != 0)
                            ap.add(pts[i]);
                    }
                    for (int i = pts.length; i < totalTargets && i < 63; ++i) {
                        if((lbits & (1 << i)) != 0)
                            ap.add(lts[i - pts.length]);
                    }

                    if(ap.size() > 0) {
                        bestQuality = qualityMap[x][y];
                        bestPoints.clear();
                        bestPoints.put(Coord.get(x, y), ap);
                    }
                }
                else if(qualityMap[x][y] == bestQuality)
                {
                    ArrayList<Coord> ap = new ArrayList<Coord>();

                    for (int i = 0; i < pts.length && i < 63; ++i) {
                        if((pbits & (1 << i)) != 0)
                            ap.add(pts[i]);
                    }
                    for (int i = pts.length; i < totalTargets && i < 63; ++i) {
                        if ((pbits & (1 << i)) != 0) {
                            ap.add(pts[i]);
                            ap.add(pts[i]);
                            ap.add(pts[i]);
                            ap.add(pts[i]);
                        }
                    }

                    if (ap.size() > 0) {
                        bestPoints.put(Coord.get(x, y), ap);
                    }
                }
            }
        }

        return bestPoints;
    }

/*
    @Override
    public ArrayList<ArrayList<Coord>> idealLocations(Set<Coord> targets, Set<Coord> requiredExclusions) {
        int totalTargets = targets.size() + 1;
        int radius = Math.max(1, (int) (Math.sqrt(volume) * 1.5));
        ArrayList<ArrayList<Coord>> locs = new ArrayList<ArrayList<Coord>>(totalTargets);

        for(int i = 0; i < totalTargets; i++)
        {
            locs.add(new ArrayList<Coord>(volume));
        }
        if(totalTargets == 1)
            return locs;
        double ctr = 0;
        if(radius < 1)
        {
            locs.get(totalTargets - 2).addAll(targets);
            return locs;
        }
        double tempRad;
        boolean[][] tested = new boolean[dungeon.length][dungeon[0].length];
        for (int x = 1; x < dungeon.length - 1; x += radius) {
            BY_POINT:
            for (int y = 1; y < dungeon[x].length - 1; y += radius) {
                for(Coord ex : requiredExclusions)
                {
                    if(rt.radius(x, y, ex.x, ex.y) <= radius * 0.75)
                        continue BY_POINT;
                }
                ctr = 0;
                for(Coord tgt : targets)
                {
                    tempRad = rt.radius(x, y, tgt.x, tgt.y);
                    if(tempRad < radius)
                        ctr += 1.0 - (tempRad / radius) * 0.5;
                }
                if(ctr >= 1)
                    locs.get((int)(totalTargets - ctr)).add(Coord.get(x, y));
            }
        }
        Coord it;
        for(int t = 0; t < totalTargets - 1; t++)
        {
            if(locs.get(t).size() > 0) {
                int numPoints = locs.get(t).size();
                for (int i = 0; i < numPoints; i++) {
                    it = locs.get(t).get(i);
                    for (int x = Math.max(1, it.x - radius / 2); x < it.x + (radius + 1) / 2 && x < dungeon.length - 1; x++) {
                        BY_POINT:
                        for (int y = Math.max(1, it.y - radius / 2); y <= it.y + (radius - 1) / 2 && y < dungeon[0].length - 1; y++)
                        {
                            if(tested[x][y])
                                continue;
                            tested[x][y] = true;

                            for(Coord ex : requiredExclusions)
                            {
                                if(rt.radius(x, y, ex.x, ex.y) <= radius * 0.75)
                                    continue BY_POINT;
                            }

                            ctr = 0;
                            for(Coord tgt : targets)
                            {
                                tempRad = rt.radius(x, y, tgt.x, tgt.y);
                                if(tempRad < radius)
                                    ctr += 1.0 - (tempRad / radius) * 0.5;
                            }
                            if(ctr >= 1)
                                locs.get((int)(totalTargets - ctr)).add(Coord.get(x, y));
                        }
                    }
                }
            }
        }
        return locs;
    }
*/

    @Override
    public void setMap(char[][] map) {
        spill.initialize(map);
        this.dungeon = map;
    }

    @Override
    public LinkedHashMap<Coord, Double> findArea() {
        spill.start(center, volume, null);
        LinkedHashMap<Coord, Double> r = AreaUtils.arrayToHashMap(spill.spillMap);
        if(!expanding)
        {
            spill.reset();
            spill.lrng.setState(this.seed);
        }
        return r;
    }

    @Override
    public Coord getOrigin() {
        return origin;
    }

    @Override
    public void setOrigin(Coord origin) {
        this.origin = origin;

    }

    @Override
    public Radius getLimitType() {
        return limitType;
    }

    @Override
    public int getMinRange() {
        return minRange;
    }

    @Override
    public int getMaxRange() {
        return maxRange;
    }

    @Override
    public Radius getMetric() {
        return metric;
    }

    @Override
    public void setLimitType(Radius limitType) {
        this.limitType = limitType;

    }

    @Override
    public void setMinRange(int minRange) {
        this.minRange = minRange;
    }

    @Override
    public void setMaxRange(int maxRange) {
        this.maxRange = maxRange;

    }

    @Override
    public void setMetric(Radius metric) {
        this.metric = metric;
    }

    public boolean isExpanding() {
        return expanding;
    }

    public void setExpanding(boolean expanding) {
        this.expanding = expanding;
    }
}


text:
import React from 'react';

export default() => (

);


text:
class HackDecrypter():

    def encrypt(self, val):
        return val

    def decrypt(self, val):
        return val


text:
import * as React from 'react'
import { SemanticShorthandContent, SemanticSIZES } from '../../generic'

export interface LoaderProps extends StrictLoaderProps {
  [key: string]: any
}

export interface StrictLoaderProps {
  /** An element type to render as (string or function). */
  as?: any

  /** A loader can be active or visible. */
  active?: boolean

  /** Primary content. */
  children?: React.ReactNode

  /** Additional classes. */
  className?: string

  /** Shorthand for primary content. */
  content?: SemanticShorthandContent

  /** A loader can be disabled or hidden. */
  disabled?: boolean

  /** A loader can show it's unsure of how long a task will take. */
  indeterminate?: boolean

  /** Loaders can appear inline with content. */
  inline?: boolean | 'centered'

  /** Loaders can have their colors inverted. */
  inverted?: boolean

  /** Loaders can have different sizes. */
  size?: SemanticSIZES
}

declare const Loader: React.FC<LoaderProps>

export default Loader


text:
check() {
	file=$1
	line=$(grep -n 'ERROR HERE' $file | sed 's/:.*//')
	if [ "$line" = "" ]; then
		echo 1>&2 misc/cgo/errors/test.bash: BUG: cannot find ERROR HERE in $file
		exit 1
	fi
	expect $file $file:$line:
}

expect() {
	file=$1
	shift
	if go build -gcflags=-C $file >errs 2>&1; then
		echo 1>&2 misc/cgo/errors/test.bash: BUG: expected cgo to fail on $file but it succeeded
		exit 1
	fi
	if ! test -s errs; then
		echo 1>&2 misc/cgo/errors/test.bash: BUG: expected error output for $file but saw none
		exit 1
	fi
	for error; do
		if ! fgrep $error errs >/dev/null 2>&1; then
			echo 1>&2 misc/cgo/errors/test.bash: BUG: expected error output for $file to contain \"$error\" but saw:
			cat 1>&2 errs
			exit 1
		fi
	done
}

check err1.go
check err2.go
check err3.go
check issue7757.go
check issue8442.go
check issue11097a.go
check issue11097b.go
expect issue13129.go C.ushort
check issue13423.go
expect issue13635.go C.uchar C.schar C.ushort C.uint C.ulong C.longlong C.ulonglong C.complexfloat C.complexdouble
check issue13830.go
check issue16116.go
check issue16591.go

if ! go build issue14669.go; then
	exit 1
fi
if ! CGO_CFLAGS="-O" go build issue14669.go; then
	exit 1
fi

if ! go run ptr.go; then
	exit 1
fi

# The malloc.go test should crash.
rm -f malloc.out
if go run malloc.go >malloc.out 2>&1; then
	echo '`go run malloc.go` succeeded unexpectedly'
	cat malloc.out
	rm -f malloc.out
	exit 1
fi
rm -f malloc.out

rm -rf errs _obj
exit 0


text:
#ifndef itkMalcolmSparseLevelSetImage_h
#define itkMalcolmSparseLevelSetImage_h

#include "itkImage.h"
#include "itkLevelSetSparseImage.h"

#include "itkLabelObject.h"
#include "itkLabelMap.h"

namespace itk
{
/**
 *  \class MalcolmSparseLevelSetImage
 *  \brief Derived class for the Malcolm representation of level-set function
 *
 *  This representation is a "sparse" level-set function, where values could
 *  only be { -1, 0, +1 } and organized into 1 layer { 0 }.
 *
 *  \tparam VDimension Dimension of the input space
 *  \ingroup ITKLevelSetsv4
 */
template< unsigned int VDimension >
class ITK_TEMPLATE_EXPORT MalcolmSparseLevelSetImage :
    public LevelSetSparseImage< int8_t, VDimension >
{
public:
  ITK_DISALLOW_COPY_AND_ASSIGN(MalcolmSparseLevelSetImage);

  using Self = MalcolmSparseLevelSetImage;
  using Pointer = SmartPointer< Self >;
  using ConstPointer = SmartPointer< const Self >;
  using Superclass = LevelSetSparseImage< int8_t, VDimension >;

  /** Method for creation through the object factory. */
  itkNewMacro(Self);

  /** Run-time type information (and related methods). */
  itkTypeMacro(MalcolmSparseLevelSetImage, LevelSetSparseImage);

  static constexpr unsigned int Dimension = VDimension;

  using InputType = typename Superclass::InputType;
  using OutputType = typename Superclass::OutputType;
  using OutputRealType = typename Superclass::OutputRealType;
  using GradientType = typename Superclass::GradientType;
  using HessianType = typename Superclass::HessianType;
  using LevelSetDataType = typename Superclass::LevelSetDataType;

  using LayerIdType = typename Superclass::LayerIdType;
  using LabelObjectType = typename Superclass::LabelObjectType;
  using LabelObjectPointer = typename Superclass::LabelObjectPointer;
  using LabelObjectLengthType = typename Superclass::LabelObjectLengthType;
  using LabelObjectLineType = typename Superclass::LabelObjectLineType;

  using LabelMapType = typename Superclass::LabelMapType;
  using LabelMapPointer = typename Superclass::LabelMapPointer;
  using RegionType = typename Superclass::RegionType;

  using LayerType = typename Superclass::LayerType;
  using LayerIterator = typename Superclass::LayerIterator;
  using LayerConstIterator = typename Superclass::LayerConstIterator;

  using LayerMapType = typename Superclass::LayerMapType;
  using LayerMapIterator = typename Superclass::LayerMapIterator;
  using LayerMapConstIterator = typename Superclass::LayerMapConstIterator;

  /** Returns the value of the level set function at a given location inputPixel */
  using Superclass::Evaluate;
  OutputType Evaluate( const InputType& inputPixel ) const override;

  /** Returns the Hessian of the level set function at a given location inputPixel */
  HessianType EvaluateHessian( const InputType& inputPixel ) const override;

  /** Returns the Laplacian of the level set function at a given location inputPixel */
  OutputRealType EvaluateLaplacian( const InputType& inputPixel ) const override;

  /** Returns the MeanCurvature of the level set function at a given location inputPixel */
  OutputRealType EvaluateMeanCurvature( const InputType& inputPixel ) const override;

  void EvaluateHessian( const InputType& inputPixel, LevelSetDataType& data ) const override;
  void EvaluateLaplacian( const InputType& inputPixel, LevelSetDataType& data ) const override;
  void EvaluateMeanCurvature( const InputType& inputPixel, LevelSetDataType& data ) const override;

  static inline LayerIdType MinusOneLayer() { return -1; }
  static inline LayerIdType ZeroLayer() { return 0; }
  static inline LayerIdType PlusOneLayer() { return 1; }

protected:

  MalcolmSparseLevelSetImage();

  ~MalcolmSparseLevelSetImage() override;

  /** Initialize the sparse field layers */
  void InitializeLayers() override;

  void InitializeInternalLabelList() override;
};
}
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkMalcolmSparseLevelSetImage.hxx"
#endif

#endif // itkMalcolmSparseLevelSetImage_h