text:
import * as ts from "typescript"
import * as glob from "glob"
import * as path from "path"
import * as stringify from "json-stable-stringify"
import * as vm from "vm"
import { Argv } from "yargs"

const REGEX_FILE_NAME = /".*"\./
const REGEX_TJS_JSDOC = /^-([\w]+)\s([\w]+)/g

export type ValidationKeywords = {
    [prop: string]: boolean
}

export class Args {
    useRef = true
    useTypeAliasRef = false
    useRootRef = false
    useTitle = false
    useDefaultProperties = false
    disableExtraProperties = false
    usePropertyOrder = false
    useTypeOfKeyword = false
    ignoreObjectMethods = false
    generateRequired = false
    strictNullChecks = false
    ignoreErrors = false
    out = ""
    validationKeywords: string[] = []
}

export type PartialArgs = Partial<Args>

export type PrimitiveType = number | boolean | string | null

export type Definition = {
    $ref?: string,
    description?: string,
    allOf?: Definition[],
    oneOf?: Definition[],
    anyOf?: Definition[],
    title?: string,
    type?: string | string[],
    definitions?: { [key: string]: any },
    format?: string,
    items?: Definition,
    minItems?: number,
    additionalItems?: {
        anyOf: Definition
    },
    enum?: PrimitiveType[] | Definition[],
    default?: PrimitiveType | Object,
    additionalProperties?: Definition,
    required?: string[],
    propertyOrder?: string[],
    properties?: {},
    defaultProperties?: string[],
    ignore?: boolean,

    typeof?: "function"
}

export class JsonSchemaGenerator {
    /**
     * JSDoc keywords that should be used to annotate the JSON schema.
     */
    private static validationKeywords = {
        ignore: true,
        description: true,
        type: true,
        minimum: true,
        exclusiveMinimum: true,
        maximum: true,
        exclusiveMaximum: true,
        multipleOf: true,
        minLength: true,
        maxLength: true,
        format: true,
        pattern: true,
        minItems: true,
        maxItems: true,
        uniqueItems: true,
        default: true,
        additionalProperties: true,
        enum: true
    }

    private reffedDefinitions: { [key: string]: Definition } = {}
    private userValidationKeywords: ValidationKeywords

    constructor(
        private allSymbols: { [name: string]: ts.Type },
        private userSymbols: { [name: string]: ts.Type },
        private inheritingTypes: { [baseName: string]: string[] },
        private tc: ts.TypeChecker,
        private args = new Args(),
    ) {
        this.userValidationKeywords = args.validationKeywords.reduce(
            (acc, word) => ({ ...acc, [word]: true }),
            {}
        )
    }

    public get ReffedDefinitions(): { [key: string]: Definition } {
        return this.reffedDefinitions
    }

    /**
     * Try to parse a value and returns the string if it fails.
     */
    private parseValue(value: string) {
        try {
            return JSON.parse(value)
        } catch (error) {
            return value
        }
    }

    /**
     * Parse the comments of a symbol into the definition and other annotations.
     */
    private parseCommentsIntoDefinition(symbol: ts.Symbol, definition: { description?: string }, otherAnnotations: {}): void {
        if (!symbol) {
            return
        }

        // the comments for a symbol
        let comments = symbol.getDocumentationComment()
        if (comments.length) {
            definition.description = comments.map(comment => comment.kind === "lineBreak" ? comment.text : comment.text.trim().replace(/\r\n/g, "\n")).join("")
        }

        // jsdocs are separate from comments
        symbol.getJsDocTags().forEach(doc => {
            // if we have @TJS-... annotations, we have to parse them
            const [name, text] = (doc.name === "TJS" ? new RegExp(REGEX_TJS_JSDOC).exec(doc.text!)!.slice(1, 3) : [doc.name, doc.text]) as string[]
            if (JsonSchemaGenerator.validationKeywords[name] || this.userValidationKeywords[name]) {
                definition[name] = this.parseValue(text)
            } else {
                // special annotations
                otherAnnotations[doc.name] = true
            }
        })
    }

    private extractLiteralValue(typ: ts.Type): PrimitiveType | undefined {
        if (typ.flags & ts.TypeFlags.EnumLiteral) {
            let str = (<ts.LiteralType>typ).text
            let num = parseFloat(str)
            return isNaN(num) ? str : num
        } else if (typ.flags & ts.TypeFlags.StringLiteral) {
            return (<ts.LiteralType>typ).text
        } else if (typ.flags & ts.TypeFlags.NumberLiteral) {
            return parseFloat((<ts.LiteralType>typ).text)
        } else if (typ.flags & ts.TypeFlags.BooleanLiteral) {
            return (typ as any).intrinsicName === "true"
        }
        return undefined
    }

    /**
     * Checks whether a type is a tuple type.
     */
    private resolveTupleType(propertyType: ts.Type): ts.TupleTypeNode | null {
        if (!propertyType.getSymbol() && (propertyType.getFlags() & ts.TypeFlags.Object && (<ts.ObjectType>propertyType).objectFlags & ts.ObjectFlags.Reference)) {
            return (propertyType as ts.TypeReference).target as any
        }
        if (!(propertyType.getFlags() & ts.TypeFlags.Object && (<ts.ObjectType>propertyType).objectFlags & ts.ObjectFlags.Tuple)) {
            return null
        }
        return propertyType as any
    }

    private getDefinitionForRootType(propertyType: ts.Type, tc: ts.TypeChecker, reffedType: ts.Symbol, definition: Definition) {
        const symbol = propertyType.getSymbol()

        const tupleType = this.resolveTupleType(propertyType)

        if (tupleType) { // tuple
            const elemTypes: ts.NodeArray<ts.TypeNode> = tupleType.elementTypes || (propertyType as any).typeArguments
            const fixedTypes = elemTypes.map(elType => this.getTypeDefinition(elType as any, tc))
            definition.type = "array"
            definition.items = fixedTypes
            definition.minItems = fixedTypes.length
            definition.additionalItems = {
                "anyOf": fixedTypes
            }
        } else {
            const propertyTypeString = tc.typeToString(propertyType, undefined, ts.TypeFormatFlags.UseFullyQualifiedType).toLowerCase()
            switch (propertyTypeString) {
                case "string":
                case "boolean":
                case "null":
                case "undefined":
                    definition.type = propertyTypeString
                    break

                case "number":
                    const isInteger = (definition.type === "integer" || (reffedType && reffedType.getName() === "integer"))
                    definition.type = isInteger ? "integer" : "number"
                    break

                case "any":
                    // no type restriction, so that anything will match
                    break

                case "date":
                    definition.type = "string"
                    definition.format = "date-time"
                    break

                default:
                    const value = this.extractLiteralValue(propertyType)
                    if (value !== undefined) {
                        definition.type = typeof value
                        definition.enum = [value]
                    } else if (symbol && (symbol.getName() === "Array" || symbol.getName() === "ReadonlyArray")) {
                        const arrayType = (<ts.TypeReference>propertyType).typeArguments[0]
                        definition.type = "array"
                        definition.items = this.getTypeDefinition(arrayType, tc)
                    } else {
                        // Report that type could not be processed
                        let info: any
                        try {
                            info = JSON.stringify(propertyType)
                        } catch (err) {
                            info = propertyType
                        }
                        console.error("Unsupported type: ", info)
                        // definition = this.getTypeDefinition(propertyType, tc)
                    }
            }
        }

        return definition
    }

    private getReferencedTypeSymbol(prop: ts.Symbol, tc: ts.TypeChecker): ts.Symbol | undefined {
        const decl = prop.getDeclarations()
        if (decl && decl.length) {
            const type = (<ts.TypeReferenceNode>(<any>decl[0]).type)
            if (type && (type.kind & ts.SyntaxKind.TypeReference) && type.typeName) {
                return tc.getSymbolAtLocation(type.typeName)
            }
        }
        return undefined
    }

    private getDefinitionForProperty(prop: ts.Symbol, tc: ts.TypeChecker, node: ts.Node) {
        const propertyName = prop.getName()
        const propertyType = tc.getTypeOfSymbolAtLocation(prop, node)

        const reffedType = this.getReferencedTypeSymbol(prop, tc)

        let definition = this.getTypeDefinition(propertyType, tc, undefined, undefined, prop, reffedType)
        if (this.args.useTitle) {
            definition.title = propertyName
        }

        if (definition.hasOwnProperty("ignore")) {
            return null
        }

        // try to get default value
        let initial = (<ts.VariableDeclaration>prop.valueDeclaration).initializer

        if (initial) {
            if ((<any>initial).expression) { // node
                console.warn("initializer is expression for property " + propertyName)
            } else if ((<any>initial).kind && (<any>initial).kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral) {
                definition.default = initial.getText()
            } else {
                try {
                    const sandbox = { sandboxvar: null as any }
                    vm.runInNewContext("sandboxvar=" + initial.getText(), sandbox)

                    const val = sandbox.sandboxvar
                    if (val === null || typeof val === "string" || typeof val === "number" || typeof val === "boolean" || Object.prototype.toString.call(val) === "[object Array]") {
                        definition.default = val
                    } else if (val) {
                        console.warn("unknown initializer for property " + propertyName + ": " + val)
                    }
                } catch (e) {
                    console.warn("exception evaluating initializer for property " + propertyName)
                }
            }
        }

        return definition
    }

    private getEnumDefinition(clazzType: ts.Type, tc: ts.TypeChecker, definition: Definition): Definition {
        const node = clazzType.getSymbol().getDeclarations()[0]
        const fullName = tc.typeToString(clazzType, undefined, ts.TypeFormatFlags.UseFullyQualifiedType)
        const enm = <ts.EnumDeclaration>node

        var enumValues: (number | boolean | string | null)[] = []
        let enumTypes = new Set<string>()

        enm.members.forEach(member => {
            const caseLabel = (<ts.Identifier>member.name).text
            const constantValue = tc.getConstantValue(member)
            if (constantValue !== undefined) {
                enumValues.push(constantValue)
                enumTypes.add(typeof constantValue)
            } else {
                // try to extract the enums value it will probably by a cast expression
                let initial: ts.Expression | undefined = member.initializer
                if (initial) {
                    if ((<any>initial).expression) { // node
                        const exp = (<any>initial).expression
                        const text = (<any>exp).text
                        // if it is an expression with a text literal, chances are it is the enum convension:
                        // CASELABEL = 'literal' as any
                        if (text) {
                            enumValues.push(text)
                            enumTypes.add("string")
                        } else if (exp.kind === ts.SyntaxKind.TrueKeyword || exp.kind === ts.SyntaxKind.FalseKeyword) {
                            enumValues.push((exp.kind === ts.SyntaxKind.TrueKeyword))
                            enumTypes.add("boolean")
                        } else {
                            console.warn("initializer is expression for enum: " + fullName + "." + caseLabel)
                        }
                    } else if (initial.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral) {
                        enumValues.push(initial.getText())
                        enumTypes.add("string")
                    } else if (initial.kind === ts.SyntaxKind.NullKeyword) {
                        enumValues.push(null)
                        enumTypes.add("null")
                    }
                }
            }
        })

        if (enumTypes.size) {
            definition.type = (enumTypes.size === 1) ? enumTypes.values().next().value : [...enumTypes]
        }

        if (enumValues.length > 0) {
            definition.enum = enumValues.sort()
        }

        return definition
    }

    private getUnionDefinition(unionType: ts.UnionType, prop: ts.Symbol, tc: ts.TypeChecker, unionModifier: string, definition: Definition) {
        const enumValues = new Set<PrimitiveType>()
        const simpleTypes = new Set<string>()
        const schemas: Definition[] = []

        unionType.types.forEach(valueType => {
            const value = this.extractLiteralValue(valueType)
            if (value !== undefined) {
                enumValues.add(value)
            } else {
                const def = this.getTypeDefinition(valueType, tc)
                if (def.type === "undefined") {
                    if (prop) {
                        (<any>prop).mayBeUndefined = true
                    }
                } else {
                    const keys = Object.keys(def)
                    if (keys.length === 1 && keys[0] === "type") {
                        if (typeof def.type !== "string") {
                            console.error("Expected only a simple type.")
                        } else {
                            simpleTypes.add(def.type)
                        }
                    } else {
                        schemas.push(def)
                    }
                }
            }
        })

        if (enumValues.size > 0) {
            const types = new Set<string>()
            enumValues.forEach(value => types.add(typeof value))

            if (types.size === 1 && enumValues.size === 2 && types.values().next().value === "boolean") {
                // If the values are true and false, just add "boolean" as simple type
                simpleTypes.add("boolean")
            } else {
                const enumSchema: Definition = { enum: [...enumValues].sort() }

                // If all values are of the same primitive type, add a "type" field to the schema
                if (types.size === 1) {
                    enumSchema.type = types.values().next().value
                }

                schemas.push(enumSchema)
            }
        }

        if (simpleTypes.size > 0) {
            schemas.push({ type: simpleTypes.size === 1 ? simpleTypes.values().next().value : [...simpleTypes] })
        }

        if (schemas.length === 1) {
            for (let k in schemas[0]) {
                if (schemas[0].hasOwnProperty(k)) {
                    definition[k] = schemas[0][k]
                }
            }
        } else {
            definition[unionModifier] = schemas
        }
        return definition
    }

    private getClassDefinition(clazzType: ts.Type, tc: ts.TypeChecker, definition: Definition): Definition {
        const node = clazzType.getSymbol().getDeclarations()[0]
        if (this.args.useTypeOfKeyword && node.kind === ts.SyntaxKind.FunctionType) {
            definition.typeof = "function"
            return definition
        }

        const clazz = <ts.ClassDeclaration>node
        const props = tc.getPropertiesOfType(clazzType)
        const fullName = tc.typeToString(clazzType, undefined, ts.TypeFormatFlags.UseFullyQualifiedType)

        const modifierFlags = ts.getCombinedModifierFlags(node)

        if (props.length === 0 && clazz.members && clazz.members.length === 1 && clazz.members[0].kind === ts.SyntaxKind.IndexSignature) {
            // for case "array-types"
            const indexSignature = <ts.IndexSignatureDeclaration>clazz.members[0]
            if (indexSignature.parameters.length !== 1) {
                throw "Not supported: IndexSignatureDeclaration parameters.length != 1"
            }
            const indexSymbol: ts.Symbol = (<any>indexSignature.parameters[0]).symbol
            const indexType = tc.getTypeOfSymbolAtLocation(indexSymbol, node)
            const isStringIndexed = (indexType.flags === ts.TypeFlags.String)
            if (indexType.flags !== ts.TypeFlags.Number && !isStringIndexed) {
                throw "Not supported: IndexSignatureDeclaration with index symbol other than a number or a string"
            }

            const typ = tc.getTypeAtLocation(indexSignature.type!)
            const def = this.getTypeDefinition(typ, tc, undefined, "anyOf")

            if (isStringIndexed) {
                definition.type = "object"
                definition.additionalProperties = def
            } else {
                definition.type = "array"
                definition.items = def
            }
        } else if (modifierFlags & ts.ModifierFlags.Abstract) {
            const oneOf = this.inheritingTypes[fullName].map((typename) => {
                return this.getTypeDefinition(this.allSymbols[typename], tc)
            })

            definition.oneOf = oneOf
        } else {
            const propertyDefinitions = props.reduce((all, prop) => {
                const propertyName = prop.getName()
                const propDef = this.getDefinitionForProperty(prop, tc, node)
                if (propDef != null) {
                    all[propertyName] = propDef
                }
                return all
            }, {})

            definition.type = "object"
            definition.properties = propertyDefinitions

            if (this.args.useDefaultProperties) {
                definition.defaultProperties = []
            }
            if (this.args.disableExtraProperties && definition.additionalProperties === undefined) {
                definition.additionalProperties = false
            }
            if (this.args.usePropertyOrder) {
                // propertyOrder is non-standard, but useful:
                // https://github.com/json-schema/json-schema/issues/87
                definition.propertyOrder = props.map(prop => prop.getName())
            }
            if (this.args.generateRequired) {
                const requiredProps = props.filter(prop =>
                    !(prop.flags & ts.SymbolFlags.Optional)
                    && !(<any>prop).mayBeUndefined
                    && definition.properties
                    && prop.getName() in definition.properties
                ).map(prop => prop.getName())

                if (requiredProps.length > 0) {
                    definition.required = requiredProps
                }
            }
        }
        return definition
    }

    private simpleTypesAllowedProperties = {
        type: true,
        description: true
    }

    private addSimpleType(def: Definition, type: string) {
        for (let k in def) {
            if (!this.simpleTypesAllowedProperties[k]) {
                return false
            }
        }

        if (!def.type) {
            def.type = type
        } else if (Array.isArray(def.type)) {
            if (!def.type.every((val) => typeof val === "string")) {
                return false
            }

            if (def.type.indexOf("null") === -1) {
                def.type.push("null")
            }
        } else {
            if (typeof def.type !== "string") {
                return false
            }

            if (def.type !== "null") {
                def.type = [def.type, "null"]
            }
        }
        return true
    }

    private makeNullable(def: Definition) {
        if (!this.addSimpleType(def, "null")) {
            let union = def.oneOf || def.anyOf
            if (union) {
                union.push({ type: "null" })
            } else {
                const subdef = {}
                for (var k in def) {
                    if (def.hasOwnProperty(k)) {
                        subdef[k] = def[k]
                        delete def[k]
                    }
                }
                def.anyOf = [subdef, { type: "null" }]
            }
        }
        return def
    }

    private getTypeDefinition(typ: ts.Type, tc: ts.TypeChecker, asRef = this.args.useRef, unionModifier: string = "anyOf", prop?: ts.Symbol, reffedType?: ts.Symbol): Definition {
        const definition: Definition = {} // real definition
        let returnedDefinition = definition // returned definition, may be a $ref

        const symbol = typ.getSymbol()
        const isRawType = (!symbol || symbol.name === "integer" || symbol.name === "Array" || symbol.name === "ReadonlyArray" || symbol.name === "Date")

        // special case: an union where all child are string literals -> make an enum instead
        let isStringEnum = false
        if (typ.flags & ts.TypeFlags.Union) {
            const unionType = <ts.UnionType>typ
            isStringEnum = (unionType.types.every(propType => {
                return (propType.getFlags() & ts.TypeFlags.StringLiteral) !== 0
            }))
        }

        // aliased types must be handled slightly different
        const asTypeAliasRef = asRef && reffedType && (this.args.useTypeAliasRef || isStringEnum)
        if (!asTypeAliasRef) {
            if (isRawType || typ.getFlags() & ts.TypeFlags.Object && (<ts.ObjectType>typ).objectFlags & ts.ObjectFlags.Anonymous) {
                asRef = false  // raw types and inline types cannot be reffed,
                // unless we are handling a type alias
            }
        }

        let fullTypeName = ""
        if (asTypeAliasRef) {
            fullTypeName = tc.getFullyQualifiedName(
                reffedType!.getFlags() & ts.SymbolFlags.Alias ?
                    tc.getAliasedSymbol(reffedType!) :
                    reffedType!
            ).replace(REGEX_FILE_NAME, "")
        } else if (asRef) {
            fullTypeName = tc.typeToString(typ, undefined, ts.TypeFormatFlags.UseFullyQualifiedType)
        }

        if (asRef) {
            returnedDefinition = {
                "$ref": "#/definitions/" + fullTypeName
            }
        }

        // Parse comments
        const otherAnnotations = {}
        this.parseCommentsIntoDefinition(reffedType!, definition, otherAnnotations) // handle comments in the type alias declaration
        if (prop) {
            this.parseCommentsIntoDefinition(prop, returnedDefinition, otherAnnotations)
        }
        this.parseCommentsIntoDefinition(symbol, definition, otherAnnotations)

        // Create the actual definition only if is an inline definition, or
        // if it will be a $ref and it is not yet created
        if (!asRef || !this.reffedDefinitions[fullTypeName]) {
            if (asRef) { // must be here to prevent recursivity problems
                this.reffedDefinitions[fullTypeName] = asTypeAliasRef && reffedType!.getFlags() & ts.TypeFlags.IndexedAccess && symbol ? this.getTypeDefinition(typ, tc, true, undefined, symbol, symbol) : definition
                if (this.args.useTitle && fullTypeName) {
                    definition.title = fullTypeName
                }
            }
            const node = symbol && symbol.getDeclarations() !== undefined ? symbol.getDeclarations()[0] : null
            if (node && node.kind === ts.SyntaxKind.MethodDeclaration && this.args.ignoreObjectMethods) {
                definition.ignore = true
                return definition
            }

            if (definition.type === undefined) {  // if users override the type, do not try to infer it
                if (typ.flags & ts.TypeFlags.Union) {
                    this.getUnionDefinition(typ as ts.UnionType, prop!, tc, unionModifier, definition)
                } else if (typ.flags & ts.TypeFlags.Intersection) {
                    definition.allOf = (<ts.IntersectionType>typ).types.map(type => this.getTypeDefinition(type, tc))
                } else if (isRawType) {
                    this.getDefinitionForRootType(typ, tc, reffedType!, definition)
                } else if (node && (node.kind === ts.SyntaxKind.EnumDeclaration || node.kind === ts.SyntaxKind.EnumMember)) {
                    this.getEnumDefinition(typ, tc, definition)
                } else if (symbol && symbol.flags & ts.SymbolFlags.TypeLiteral && Object.keys(symbol.members).length === 0) {
                    // {} is TypeLiteral with no members. Need special case because it doesn't have declarations.
                    definition.type = "object"
                    definition.properties = {}
                } else {
                    this.getClassDefinition(typ, tc, definition)
                }
            }
        }

        if (otherAnnotations["nullable"]) {
            this.makeNullable(returnedDefinition)
        }

        return returnedDefinition
    }

    public setSchemaOverride(symbolName: string, schema: Definition) {
        this.reffedDefinitions[symbolName] = schema
    }

    public getSchemaForSymbol(symbolName: string, includeReffedDefinitions: boolean = true): Definition {
        if (!this.allSymbols[symbolName]) {
            throw `type ${symbolName} not found`
        }
        let def = this.getTypeDefinition(this.allSymbols[symbolName], this.tc, this.args.useRootRef)

        if (this.args.useRef && includeReffedDefinitions && Object.keys(this.reffedDefinitions).length > 0) {
            def.definitions = this.reffedDefinitions
        }
        def["$schema"] = "http://json-schema.org/draft-04/schema#"
        return def
    }

    public getSchemaForSymbols(symbols: string[]): Definition {
        const root = {
            "$schema": "http://json-schema.org/draft-04/schema#",
            definitions: {}
        }
        symbols.forEach(symbol => root.definitions[symbol] = this.getTypeDefinition(this.userSymbols[symbol], this.tc, this.args.useRootRef))
        return root
    }

    public getUserSymbols() {
        return Object.keys(this.userSymbols)
    }
}

export function getProgramFromFiles(files: string[], compilerOptions: ts.CompilerOptions = {}): ts.Program {
    // use built-in default options
    const options: ts.CompilerOptions = {
        noEmit: true, emitDecoratorMetadata: true, experimentalDecorators: true, target: ts.ScriptTarget.ES5, module: ts.ModuleKind.CommonJS
    }
    for (const k in compilerOptions) {
        if (compilerOptions.hasOwnProperty(k)) {
            options[k] = compilerOptions[k]
        }
    }
    return ts.createProgram(files, options)
}

export function buildGenerator(program: ts.Program, args: PartialArgs = {}): JsonSchemaGenerator | null {
    // Use defaults unles otherwise specified
    let settings = new Args()

    for (const pref in args) {
        if (args.hasOwnProperty(pref)) {
            settings[pref] = args[pref]
        }
    }

    const typeChecker = program.getTypeChecker()

    var diagnostics = ts.getPreEmitDiagnostics(program)

    if (diagnostics.length === 0 || args.ignoreErrors) {

        const allSymbols: { [name: string]: ts.Type } = {}
        const userSymbols: { [name: string]: ts.Type } = {}
        const inheritingTypes: { [baseName: string]: string[] } = {}

        program.getSourceFiles().forEach((sourceFile, _sourceFileIdx) => {
            function inspect(node: ts.Node, tc: ts.TypeChecker) {

                if (node.kind === ts.SyntaxKind.ClassDeclaration
                    || node.kind === ts.SyntaxKind.InterfaceDeclaration
                    || node.kind === ts.SyntaxKind.EnumDeclaration
                    || node.kind === ts.SyntaxKind.TypeAliasDeclaration
                ) {
                    const symbol: ts.Symbol = (<any>node).symbol
                    let fullName = tc.getFullyQualifiedName(symbol)

                    const nodeType = tc.getTypeAtLocation(node)

                    // remove file name
                    // TODO: we probably don't want this eventually,
                    // as same types can occur in different files and will override eachother in allSymbols
                    // This means atm we can't generate all types in large programs.
                    fullName = fullName.replace(/".*"\./, "")

                    allSymbols[fullName] = nodeType

                    // if (sourceFileIdx == 0)
                    if (!sourceFile.hasNoDefaultLib) {
                        userSymbols[fullName] = nodeType
                    }

                    const baseTypes = nodeType.getBaseTypes() || []

                    baseTypes.forEach(baseType => {
                        var baseName = tc.typeToString(baseType, undefined, ts.TypeFormatFlags.UseFullyQualifiedType)
                        if (!inheritingTypes[baseName]) {
                            inheritingTypes[baseName] = []
                        }
                        inheritingTypes[baseName].push(fullName)
                    })
                } else {
                    ts.forEachChild(node, (n) => inspect(n, tc))
                }
            }
            inspect(sourceFile, typeChecker)
        })

        return new JsonSchemaGenerator(allSymbols, userSymbols, inheritingTypes, typeChecker, settings)
    } else {
        diagnostics.forEach((diagnostic) => {
            let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")
            if (diagnostic.file) {
                let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start)
                console.error(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`)
            } else {
                console.error(message)
            }
        })
        return null
    }
}

export function generateSchema(program: ts.Program, fullTypeName: string, args: PartialArgs = {}): Definition | null {
    const generator = buildGenerator(program, args)

    if (generator === null) {
        return null
    }

    let definition: Definition
    if (fullTypeName === "*") { // All types in file(s)
        definition = generator.getSchemaForSymbols(generator.getUserSymbols())
    } else { // Use specific type as root object
        definition = generator.getSchemaForSymbol(fullTypeName)
    }
    return definition
}

export function programFromConfig(configFileName: string): ts.Program {
    // basically a copy of https://github.com/Microsoft/TypeScript/blob/3663d400270ccae8b69cbeeded8ffdc8fa12d7ad/src/compiler/tsc.ts -> parseConfigFile
    const result = ts.parseConfigFileTextToJson(configFileName, ts.sys.readFile(configFileName))
    const configObject = result.config

    const configParseResult = ts.parseJsonConfigFileContent(configObject, ts.sys, path.dirname(configFileName), {}, configFileName)
    const options = configParseResult.options
    options.noEmit = true
    delete options.out
    delete options.outDir
    delete options.outFile
    delete options.declaration

    const program = ts.createProgram(configParseResult.fileNames, options)
    return program
}

export function exec(filePattern: string, fullTypeName: string, args = new Args()) {
    let program: ts.Program
    if (path.basename(filePattern) === "tsconfig.json") {
        program = programFromConfig(filePattern)
    } else {
        program = getProgramFromFiles(glob.sync(filePattern), {
            strictNullChecks: args.strictNullChecks
        })
    }

    const definition = generateSchema(program, fullTypeName, args)
    if (definition === null) {
        return
    }

    const json = stringify(definition, { space: 4 }) + "\n\n"
    if (args.out) {
        require("fs").writeFile(args.out, json, function (err: Error) {
            if (err) {
                console.error("Unable to write output file: " + err.message)
            }
        })
    } else {
        process.stdout.write(json)
    }
}

export function run() {
    var helpText = "Usage: node typescript-json-schema.js <path-to-typescript-files-or-tsconfig> <type>"
    const scriptArgs = new Args()
    var args = (<Argv>require("yargs"))
        .usage(helpText)
        .demand(2)
        .options({
            useRef: {
                boolean: true,
                default: scriptArgs.useRef,
                description: "Create shared ref definitions."
            },
            useTypeAliasRef: {
                boolean: true,
                default: scriptArgs.useTypeAliasRef,
                description: "Create shared ref definitions for the type aliases."
            },
            useRootRef: {
                boolean: true,
                default: scriptArgs.useRootRef,
                description: "Create a top-level ref definition."
            },
            useTitle: {
                boolean: true,
                default: scriptArgs.useTitle,
                description: "Creates titles in the output schema."
            },
            useDefaultProperties: {
                boolean: true,
                default: scriptArgs.useDefaultProperties,
                description: "Create default properties definitions."
            },
            disableExtraProperties: {
                boolean: true,
                default: scriptArgs.disableExtraProperties,
                description: "Disable additional properties in objects by default."
            },
            usePropertyOrder: {
                boolean: true,
                default: scriptArgs.usePropertyOrder,
                description: "Create property order definitions."
            },
            useTypeOfKeyword: {
                boolean: true,
                default: scriptArgs.useTypeOfKeyword,
                description: "Use typeOf keyword (https://goo.gl/DC6sni) for functions."
            },
            ignoreObjectMethods: {
                boolean: true,
                default: scriptArgs.ignoreObjectMethods,
                description: "Exclude methods from the generated schema"
            },
            generateRequired: {
                boolean: true,
                default: scriptArgs.generateRequired,
                description: "Create required array for non-optional properties."
            },
            strictNullChecks: {
                boolean: true,
                default: scriptArgs.strictNullChecks,
                description: "Make values non-nullable by default."
            },
            ignoreErrors: {
                boolean: true,
                default: scriptArgs.ignoreErrors,
                description: "Generate even if the program has errors."
            },
            validationKeywords: {
                array: true,
                default: scriptArgs.validationKeywords,
                description: "Provide additional validation keywords to include."
            },
            out: {
                alias: "o",
                description: "The output file, defaults to using stdout"
            }
        })
        .argv

    for (let k in scriptArgs) {
        if (args.hasOwnProperty(k)) {
            scriptArgs[k] = args[k]
        }
    }
    exec(args._[0], args._[1], scriptArgs)
}


text:
<?php

class TaShiftsController extends TaController {

	public function __construct()
	{
		parent::__construct();
		if (isset($this->user))
			$this->beforeFilter('active:'.$this->user['active']);
	}

	//Method to view shifts for a certain week
	public function getIndex()
	{
		$week = array(
			"Sunday" => array(),
			"Monday" => array(),
			"Tuesday" => array(),
			"Wednesday" => array(),
			"Thursday" => array(),
			"Friday" => array(),
			"Saturday" => array()
		);

		$days = array(
			"Sunday",
			"Monday",
			"Tuesday",
			"Wednesday",
			"Thursday",
			"Friday",
			"Saturday"
		);

		//Check if asked for a different week from the GET request
		if (Input::has('week_start'))
			$week_start = Input::get('week_start');
		else
		{
			$week_start = time() - (date('w') * 24 * 60 * 60);
			$week_start = date('Y-m-d', $week_start);
		}

		//Compute end of week which is start week plus 6 days
		$week_end = strtotime($week_start) + (6 * 24 * 60 * 60);
		$week_end = date('Y-m-d', $week_end);

		//Get all shifts for the TA from start of the week to the end
		$shifts = Auth::user()->TA()->shifts($week_start, $week_end);

		if (Input::has('ajax'))
			return $shifts->toJson();

		//Get the defined start time of the LC
		$start = Settings::get("availability_start_hour")->value;
		$start = Time::ToNumber($start);
		$time['start'] = $start;

		//Get the defined start time of the LC
		$end = Settings::get("availability_end_hour")->value;
		$end = Time::ToNumber($end);
		$time['end'] = $end;

		//Set up the data of shifts for the view to use
		foreach ($shifts as $shift){
			$day = date("l",strtotime($shift->date));
			//First cell contains all the data for the shift
			$week[$day][$shift->start]['id'] = $shift->id;

			$old = $shift->date < date("Y-m-d", strtotime('today'));
			$passed = $shift->date == date("Y-m-d", strtotime('today')) && $shift->start < Time::toNumber(date("G:i"));
			if( $old || $passed )
				$week[$day][$shift->start]['old'] = true;
			else $week[$day][$shift->start]['old'] = false;

			$week[$day][$shift->start]['mine'] = true;
			$week[$day][$shift->start]['length'] = ($shift->end - $shift->start) / 50;
			//Rest of the cells will be skipped
			for ($i=$shift->start+50; $i < $shift->end; $i+=50)
				$week[$day][$i]['skip'] = 1;
		}

		//Set up the data of free shifts for the view to use, same as the regular shifts
		$shifts = Shift::free(( $week_start > date('Y-m-d')? $week_start : date('Y-m-d') ), $week_end);
		foreach ($shifts as $shift){
			$day = date("l",strtotime($shift->date));
			if ($shift->date != date("Y-m-d") || $shift->start > Time::toNumber(date("G:i")) )
				for ($i=$shift->start; $i < $shift->end; $i+=50){
					if ( ! isset($week[$day][$i]) ){
						$week[$day][$i]['id'] = $shift->id;
						$week[$day][$i]['mine'] = false;
						if (ShiftBid::shift($shift->id, Auth::user()->TA()->id))
							$week[$day][$i]['bid'] = true;
						else $week[$day][$i]['bid'] = false;
						$week[$day][$i]['length'] = ($shift->end - $i) / 50;
						$shift_start = $i;
						for ($i=$i+50; $i < $shift->end; $i+=50)
							if (! isset($week[$day][$i]))
								$week[$day][$i]['skip'] = 1;
							else
							{
								$week[$day][$shift_start]['length'] = ($i - $shift->start) / 50;
								break;
							}
					}
				}
		}

		//Set the page selected to Shifts
		$this->navbar['Shifts']['active'] = true;

		return View::make('ta/shifts')
					->with('user', $this->user)
					->with('navbar',$this->navbar)
					->with('days', $days)
					->with('week', $week)
					->with('time', $time)
					->with('week_start', $week_start);
	}

	//Method to drop a shift
	public function deleteIndex()
	{
		$shift = Shift::find(Input::get('shift_id'));

		$ta_id = Auth::user()->TA()->id;

		//The week start for the shift
		$week_start = strtotime($shift->date) - (date('w', strtotime($shift->date)) * 24 * 60 * 60);
		$week_start = date('Y-m-d', $week_start);

		//make sure the shift belongs to the TA
		if ($shift->ta_id == $ta_id )
		{
			$shift->ta_id = null;
			$shift->save();

			Session::flash('success', "Shift on ".date('l, F jS',strtotime($shift->date))." has been dropped.");

			$tas = TA::active();

			//Send email to all active TAs
			foreach ($tas as $ta) {
				$email = $ta->user()->email;

				//No need to send email to TA who dropped the shift
				if ($ta_id != $ta->id)
				{
					Mail::send('emails.shiftAvailable', array('name' => $ta->name, 'shift'=>$shift, 'week_start'=>$week_start), function($message) use ($ta, $email)
					{
						$message->to($email, $ta->name )->subject('Shift Available!');
					});
				}
			}
		}
		//error message, Shift does not belong to the TA
		else Session::flash('fail', "Shift does not belong to you.");

		return Redirect::to('ta/shifts?week_start='.$week_start);
	}

	//Method to make a bid for a shift
	public function putIndex()
	{
		$bid = Input::except('_token','_method');

		$shift = Shift::find($bid['shift_id']);

		//The week start for the shift
		$week_start = strtotime($shift->date) - (date('w', strtotime($shift->date)) * 24 * 60 * 60);
		$week_start = date('Y-m-d', $week_start);

		//Can cover the whole shift
		if ( $shift->start == $bid['start'] && $shift->end == $bid['end'] )
		{
			$overlap = $this->checkOverlap($bid);
			if (! $overlap )
			{
				$bid['date'] = $shift->date;
				if ($old_shift = $this->checkCover($bid))
					Shift::destroy($old_shift->id);

				$shift->ta_id = $bid['ta_id'];
				$shift->save();

				//Remove all bids for the shift
				$this->clearBids($shift->id);

				Session::flash('success', "Shift on ".date('l, F jS',strtotime($shift->date))." has been added to your schedule.");
			}
			else Session::flash('fail', "Bid overlaps with existing shift.");
		}
		//Can't cover the entire shift, updating exsisting bid
		else if ( $my_bid = ShiftBid::shift($bid['shift_id'],$bid['ta_id']) )
		{
			$overlap = $this->checkOverlap($bid);
			if (! $overlap)
			{
				$my_bid->start = $bid['start'];
				$my_bid->end = $bid['end'];
				$my_bid->save();

				//Vatiable to store the total hours of combined bids
				$total_bid = new stdClass();
				$total_bid->start = $my_bid->start;
				$total_bid->end = $my_bid->end;

				//Array to store all chosen bids
				$chosen_bids = array($my_bid);
				$shift_bids = ShiftBid::shift($my_bid->shift_id);

				//Two flags for iteration
				$prev_chosen = -1;
				$stop = false;

				//Keep iterating until found enough bids or until not matching bids found
				while ( $prev_chosen != count($chosen_bids) && !$stop )
				{
					$prev_chosen = count($chosen_bids);
					foreach ($shift_bids as $bid) {
						if ($bid->end == $total_bid->start || $bid->start == $total_bid->end)
						{
							$chosen_bids[] = $bid;
							$total_bid->start = min($total_bid->start, $bid->start);
							$total_bid->end = max($total_bid->end, $bid->end);
						}
					}

					if ($total_bid->start == $shift->start && $total_bid->end == $shift->end)
					{
						$stop = true;
						foreach ($chosen_bids as $bid) {
							unset($bid->shift_id);
							$bid->date = $shift->date;

							Shift::create($bid->toArray());

							if ($shift = $this->checkCover($bid))
								Shift::destroy($shift->id);
						}

						//Remove all bids for the shift
						$this->clearBids($shift->id);

						//Remove the old shift
						Shift::destroy($shift->id);

						Session::flash('success', "Shift on ".date('l, F jS',strtotime($shift->date))." has been added to your schedule.");
					}
					else Session::flash('success', "Bid has been changed.");
				}
			}
			else Session::flash('fail', "Bid overlaps with existing shift.");
		}
		//Can't cover the entire shift, new bid
		else
		{
			//No empty bids
			if ($bid['start'] != $bid['end'])
			{
				$overlap = $this->checkOverlap($bid);
				if (! $overlap ){
					ShiftBid::create($bid);
					Session::flash('success', "Bid has been added.");
				}
				else Session::flash('fail', "Bid overlaps with existing shift.");
			}
			else Session::flash('fail', "No empty bids allowed.");
		}

		return Redirect::to('ta/shifts?week_start='.$week_start);
	}

	//Get the shift details of a shift with ID as $id
	public function getShift($id)
	{
		$shift = Shift::find($id);
		return $shift->toJson();
	}

	//Get all the bids for a shift with ID as $id
	public function getBids($id)
	{
		$shift_bids = ShiftBid::shift($id);
		return $shift_bids->toJson();
	}

	// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
	//								Private									   //
	// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

	private function checkOverlap($bid)
	{
		$ta_id = $bid['ta_id'];
		$shift = Shift::find($bid['shift_id']);

		$overlap_shifts = TA::find($ta_id)->shifts($shift->date,$shift->date);

		//No shifts that day, no overlap
		if ( count($overlap_shifts) == 0 )
			return false;
		//Need to check each shift
		else
		{
			foreach ($overlap_shifts as $shift)
				if ( ($shift->start < $bid['start'] && $bid['start'] < $shift->end ) || ($shift->start < $bid['end'] && $bid['end'] < $shift->end ) )
					return true;
		}

		return false;
	}

	private function checkCover($bid)
	{
		$ta_id = $bid['ta_id'];

		$shifts = TA::find($ta_id)->shifts($bid['date'],$bid['date']);

		//No shifts that day, no overlap
		if ( count($shifts) == 0 )
			return false;
		//Need to check each shift
		else {
			foreach ($shifts as $shift)
				if ( $bid['start'] <= $shift->start && $shift->end <= $bid['end'])
					return $shift;
		}

		return false;
	}

	private function clearBids($shift_id)
	{
		$bids = ShiftBid::shift($shift_id);
		foreach ($bids as $bid)
			ShiftBid::destroy($bid->id);
	}
}

redpajama_set_name: RedPajamaGithub


text:
require 'gcm'
require 'json'

before do
  headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
  headers['Access-Control-Allow-Origin'] = 'http://localhost:4567'
  headers['Access-Control-Allow-Headers'] = 'accept, authorization, origin'
  headers['Access-Control-Allow-Credentials'] = 'true'
end

get "/" do
	erb :index_age
end

post "/register" do
	@user = User.create(regid: params["Reg Id"])
	@notification = Notification.create(message: "Welcome! You've successfuly registered.")
	@user.notifications << @notification
	@user.notify(@notification)
end

post "/refresh" do
	p params
end

get "/regids" do
	erb :regids
end

get "/testjson" do
	yo = {"test" => [ {"obj1" => 1}, {"obj2" => 2} ]}
	sup = yo.to_json
	return sup
end

post "/testjson" do
	p params
	return "hello I'm sending data to you!"
end


text:
      Pseudominima

      Pseudomaxima


text:
/*global d3 */

// construct query string
var params = d3.select("#api_key");
if (!params.empty()) {
  var id = params.attr('data-id');
  var query = encodeURI("/api/docs/" + id);
}

// load the data from the Lagotto API
if (query) {
  d3.json(query)
    .header("Accept", "application/json; version=6")
    .get(function(error, json) {
      if (error) { return console.warn(error); }
      var data = json.doc;
  });
}


text:
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no">

	<title>Online 3D Viewer</title>

	<script type="text/javascript" src="../build/o3dv.min-dev.js"></script>

    <style>
        div.online_3d_viewer
        {
            float: left;
            border: 1px solid #eeeeee;
            width: 640px;
            height: 480px;
        }
    </style>

    <script type='text/javascript'>
        window.addEventListener ('load', () => {
            // get the parent element of the viewer
            let parentDiv = document.getElementById ('viewer');

            // initialize the viewer with the parent element and some parameters
            let viewer = new OV.EmbeddedViewer (parentDiv, {
                camera : new OV.Camera (
                    new OV.Coord3D (-1.5, 2.0, 3.0),
                    new OV.Coord3D (0.0, 0.0, 0.0),
                    new OV.Coord3D (0.0, 1.0, 0.0),
                    45.0
                ),
                backgroundColor : new OV.RGBAColor (255, 255, 255, 255),
                defaultColor : new OV.RGBColor (200, 200, 200),
                edgeSettings : {
                    showEdges : false,
                    edgeColor : new OV.RGBColor (0, 0, 0),
                    edgeThreshold : 1
                },
                environmentSettings : {
                    environmentMap : [
                        '../website/assets/envmaps/fishermans_bastion/posx.jpg',
                        '../website/assets/envmaps/fishermans_bastion/negx.jpg',
                        '../website/assets/envmaps/fishermans_bastion/posy.jpg',
                        '../website/assets/envmaps/fishermans_bastion/negy.jpg',
                        '../website/assets/envmaps/fishermans_bastion/posz.jpg',
                        '../website/assets/envmaps/fishermans_bastion/negz.jpg'
                    ],
                    backgroundIsEnvMap : false
                }
            });

            // load a model providing model urls
            viewer.LoadModelFromUrlList ([
                '../../test/testfiles/gltf/DamagedHelmet/glTF-Binary/DamagedHelmet.glb'
            ]);
        });
    </script>
</head>

<body>
    <div class="online_3d_viewer" id="viewer">
    </div>
</body>

</html>


text: from .stack import YowsupSyncStack


text:
package org.ontoware.rdf2go.util;

/**
 *
 * Converts instances from one type to another.
 * Useful for implementing adapters.
 * @author sauermann <leo.sauermann@dfki.de>
 * @param <FROM> The class that is the source of conversion
 * @param <TO> The class that is converted to
 */
public interface Converter<FROM, TO> {

    /**
     * convert the passed object to the outgoing object
     * @param source the source object to convert
     * @return the converted object
     * @throws ConversionException if something goes wrong.
     */
    public TO convert(FROM source) throws ConversionException;

}


text:
#ifndef ASYLO_PLATFORM_COMMON_FUTEX_H_
#define ASYLO_PLATFORM_COMMON_FUTEX_H_

#include <cstdint>

extern "C" {

// Tests that the memory location `futex` contains the value `expected` and, if
// so, suspends the calling thread until `futex` is notified by a call to
// `futex_wake`. Otherwise returns immediately. If a timeout of more than 0
// microseconds is provided, the calling thread will wake after the given number
// of microseconds, if not woken earlier. If a timeout of 0 microseconds is
// provided, the calling thread will wait indefinitely, until woken by a
// sys_futex_wake call. Returns 0 if the caller has woken up, similar to syscall
// futex.
int sys_futex_wait(int32_t *futex, int32_t expected, int64_t timeout_microsec);

// Wakes at most `num` of the threads waiting on `futex`. Returns the number of
// threads awakened.
int sys_futex_wake(int32_t *futex, int32_t num);
}
#endif  // ASYLO_PLATFORM_COMMON_FUTEX_H_


text:
namespace SSS_Windows_Forms.Forms.Administrator
{
    partial class SystemSettingsModal
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.attendanceTableAdapter1 = new SSS_Library.IS2G10_DBSSSDataSetTableAdapters.ATTENDANCETableAdapter();
            this.studenT_ACTIVITYTableAdapter1 = new SSS_Library.IS2G10_DBSSSDataSetTableAdapters.STUDENT_ACTIVITYTableAdapter();
            this.tutorTableAdapter1 = new SSS_Library.IS2G10_DBSSSDataSetTableAdapters.TUTORTableAdapter();
            this.userprofileTableAdapter1 = new SSS_Library.IS2G10_DBSSSDataSetTableAdapters.USERPROFILETableAdapter();
            this.studentTableAdapter1 = new SSS_Library.IS2G10_DBSSSDataSetTableAdapters.STUDENTTableAdapter();
            this.ssS_COORDINATORTableAdapter1 = new SSS_Library.IS2G10_DBSSSDataSetTableAdapters.SSS_COORDINATORTableAdapter();
            this.tutoR_AVAILABLE_TIMESTableAdapter1 = new SSS_Library.IS2G10_DBSSSDataSetTableAdapters.TUTOR_AVAILABLE_TIMESTableAdapter();
            this.doDbOpButton = new System.Windows.Forms.Button();
            this.dBOpsComboBox = new System.Windows.Forms.ComboBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.cleanDatabaseButton = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            //
            // attendanceTableAdapter1
            //
            this.attendanceTableAdapter1.ClearBeforeFill = true;
            //
            // studenT_ACTIVITYTableAdapter1
            //
            this.studenT_ACTIVITYTableAdapter1.ClearBeforeFill = true;
            //
            // tutorTableAdapter1
            //
            this.tutorTableAdapter1.ClearBeforeFill = true;
            //
            // userprofileTableAdapter1
            //
            this.userprofileTableAdapter1.ClearBeforeFill = true;
            //
            // studentTableAdapter1
            //
            this.studentTableAdapter1.ClearBeforeFill = true;
            //
            // ssS_COORDINATORTableAdapter1
            //
            this.ssS_COORDINATORTableAdapter1.ClearBeforeFill = true;
            //
            // tutoR_AVAILABLE_TIMESTableAdapter1
            //
            this.tutoR_AVAILABLE_TIMESTableAdapter1.ClearBeforeFill = true;
            //
            // doDbOpButton
            //
            this.doDbOpButton.Location = new System.Drawing.Point(79, 131);
            this.doDbOpButton.Name = "doDbOpButton";
            this.doDbOpButton.Size = new System.Drawing.Size(75, 23);
            this.doDbOpButton.TabIndex = 0;
            this.doDbOpButton.Text = "Do Op";
            this.doDbOpButton.UseVisualStyleBackColor = true;
            this.doDbOpButton.Click += new System.EventHandler(this.doDbOpButton_Click);
            //
            // dBOpsComboBox
            //
            this.dBOpsComboBox.FormattingEnabled = true;
            this.dBOpsComboBox.Location = new System.Drawing.Point(33, 104);
            this.dBOpsComboBox.Name = "dBOpsComboBox";
            this.dBOpsComboBox.Size = new System.Drawing.Size(121, 21);
            this.dBOpsComboBox.TabIndex = 1;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Calibri", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(12, 23);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(186, 33);
            this.label1.TabIndex = 18;
            this.label1.Text = "System Settings";
            //
            // label2
            //
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(33, 85);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(107, 13);
            this.label2.TabIndex = 19;
            this.label2.Text = "Database Operations";
            //
            // cleanDatabaseButton
            //
            this.cleanDatabaseButton.Location = new System.Drawing.Point(33, 34);
            this.cleanDatabaseButton.Name = "cleanDatabaseButton";
            this.cleanDatabaseButton.Size = new System.Drawing.Size(98, 23);
            this.cleanDatabaseButton.TabIndex = 20;
            this.cleanDatabaseButton.Text = "Clean Database";
            this.cleanDatabaseButton.UseVisualStyleBackColor = true;
            this.cleanDatabaseButton.Click += new System.EventHandler(this.cleanDatabaseButton_Click);
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.cleanDatabaseButton);
            this.groupBox1.Controls.Add(this.doDbOpButton);
            this.groupBox1.Controls.Add(this.label2);
            this.groupBox1.Controls.Add(this.dBOpsComboBox);
            this.groupBox1.Location = new System.Drawing.Point(89, 81);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(193, 196);
            this.groupBox1.TabIndex = 21;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Database";
            //
            // SystemSettingsModal
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(746, 501);
            this.ControlBox = false;
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.label1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Name = "SystemSettingsModal";
            this.Text = "SystemSettingsModal";
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private SSS_Library.IS2G10_DBSSSDataSetTableAdapters.ATTENDANCETableAdapter attendanceTableAdapter1;
        private SSS_Library.IS2G10_DBSSSDataSetTableAdapters.STUDENT_ACTIVITYTableAdapter studenT_ACTIVITYTableAdapter1;
        private SSS_Library.IS2G10_DBSSSDataSetTableAdapters.TUTORTableAdapter tutorTableAdapter1;
        private SSS_Library.IS2G10_DBSSSDataSetTableAdapters.USERPROFILETableAdapter userprofileTableAdapter1;
        private SSS_Library.IS2G10_DBSSSDataSetTableAdapters.STUDENTTableAdapter studentTableAdapter1;
        private SSS_Library.IS2G10_DBSSSDataSetTableAdapters.SSS_COORDINATORTableAdapter ssS_COORDINATORTableAdapter1;
        private SSS_Library.IS2G10_DBSSSDataSetTableAdapters.TUTOR_AVAILABLE_TIMESTableAdapter tutoR_AVAILABLE_TIMESTableAdapter1;
        private System.Windows.Forms.Button doDbOpButton;
        private System.Windows.Forms.ComboBox dBOpsComboBox;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button cleanDatabaseButton;
        private System.Windows.Forms.GroupBox groupBox1;
    }
}


text:
ENV['KITCHEN_SUITE'] = File.basename(__FILE__, '.*').gsub('_spec', '')
require File.expand_path('../exec_order_spec.rb', File.dirname(__FILE__))


text:
   get

      template <class T>
T get(const char *key,
      const T &default_)
      template <class T>
T get(
    const char *key,
    const T &default_
)

      Source

      template <class T>
T get(const std::string &key,
      const T &default_)
      template <class T>
T get(
    const std::string &key,
    const T &default_
)

      Source

   Description

Similar to [operator []](/api/json/operator_brackets) which can be used to get a value, but avoids parsing `/` as paths


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>D</logradouro><bairro>Parque das Acácias</bairro><cidade>Assis</cidade><uf>SP</uf><cep>19813115</cep></feed>


text:
<?php

namespace App\Providers;

use App\Helpers\CurrentPostId;
use Illuminate\Support\ServiceProvider;

class CurrentPostIdServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('currentPostId', function(){
            return new CurrentPostId();
        });
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Aunt Clara's Fruit Salad</title>
      <categories>
        <cat>None</cat></categories>
      <yield>1</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>can</unit></amt>
        <item>(20 ounce) chunk pineapple</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Vinegar or lemon juice</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Egg</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Cornstarch</item></ing>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>pints</unit></amt>
        <item>Whipping cream or medium size container of Cool Whip; (I use Cool Whip)</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Fruit; bananas, seedless grapes, apples, oranges, berries*</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit/></amt>
        <item>Bag miniature marshmellows; (may not use the whole bag, depending on preferences)</item></ing></ingredients>
    <directions>
      <step>  This is a fourth generation handed down receipe. We call it Aunt Clara's
  Fruit Salad because my Great-Great Aunt Clara used to bring this to family
  functions.

  *NOTE: - whatever is in season at the time. I usually put in two large
  bunches of green grapes, 4 large apples and 4 larger bananas plus whatever
  else I have on hand.

  Drain juice from pineapple into 2 qt saucepan and heat juice until hot;
  wisk in vinegar/lemon juice and coarnstarch until smooth and very thick
  (like pudding.) Cool mixture. Put fruit (cut up in bite sized pieces) into
  serving bowl/container, add marshmellows and whipped cream/Cool Whip and
  gently stir to coat. Refrigerate until serving time. (Can coat apple and
  banana pieces in a little of the lemon juice to keep them from turning
  brown.)

  Note: This is my daughters' favorite salad which I am 'required' to bring
  to all family functions such as Christmas and Easter get-togethers. It can
  make a large salad if you add lots of fruit - if I need a larger salad, I
  usually use a larger container of Cool Whip.

  Posted to TNT Recipes Digest by Cathie Marty <cmarty@madison.tec.wi.us> on
  Mar 11, 1998

</step></directions></recipe></recipeml>


text:
Resume

Consulting


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

function createWorkspace(runner: SchematicTestRunner): Promise<UnitTestTree> {
  return runner
      .runExternalSchematicAsync('@schematics/angular', 'workspace', {
        name: 'workspace',
        version: '13.0.0',
        newProjectRoot: 'projects',
      })
      .toPromise();
}

/**
 * Creates a sample workspace with two applications: 'app' (default) and 'second-app'
 */
export async function createTestApp(runner: SchematicTestRunner, appOptions = {}): Promise<UnitTestTree> {
  let tree = await createWorkspace(runner);
  tree =
      await runner.runExternalSchematicAsync('@schematics/angular', 'application', {name: 'app', ...appOptions}, tree)
          .toPromise();

  return runner
      .runExternalSchematicAsync('@schematics/angular', 'application', {name: 'second-app', ...appOptions}, tree)
      .toPromise();
}


text:
package edu.virginia.psyc.r01.persistence;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.mindtrails.domain.questionnaire.SecureQuestionnaireData;

import javax.persistence.Entity;
import javax.persistence.Table;

/**
 * Created by samportnow on 7/21/14.
 */
@Entity
@Table(name="DD")
@EqualsAndHashCode(callSuper = true)
@Data
public class DD extends SecureQuestionnaireData {

    private int monday_count;
    private int tuesday_count;
    private int wednesday_count;
    private int thursday_count;
    private int friday_count;
    private int saturday_count;
    private int sunday_count;

    private int monday_hours;
    private int tuesday_hours;
    private int wednesday_hours;
    private int thursday_hours;
    private int friday_hours;
    private int saturday_hours;
    private int sunday_hours;

    private int average_freq;
    private int average_amount;
    private boolean q1_noAns;
    private boolean q2_noAns;

}


text:
User.find(:all).each do |user|
  user.plugins.create(:name => "brewers",
                      :position => (user.plugins.maximum(:position) || -1) +1)
end

page = Page.create(
  :title => "Brewers",
  :link_url => "/brewers",
  :deletable => false,
  :position => ((Page.maximum(:position, :conditions => {:parent_id => nil}) || -1)+1),
  :menu_match => "^/brewers(\/|\/.+?|)$"
)
Page.default_parts.each do |default_page_part|
  page.parts.create(:title => default_page_part, :body => nil)
end


text:
/**
 *
 * Contains an abstract XML-based {@code BeanFactory} implementation,
 * including a standard "spring-beans" DTD.
 *
 */
package org.springframework.beans.factory.xml;


text:
namespace base {
class SequencedTaskRunner;
}

namespace storage_monitor {
class StorageInfo;
}

namespace extensions {

namespace api {
namespace system_storage {
struct StorageUnitInfo;
}  // namespace system_storage
}  // namespace api

namespace systeminfo {

// Build StorageUnitInfo struct from StorageInfo instance. The |unit|
// parameter is the output value.
void BuildStorageUnitInfo(const storage_monitor::StorageInfo& info,
                          api::system_storage::StorageUnitInfo* unit);

}  // namespace systeminfo

// An abstract base class for all kinds of system information providers. Each
// kind of SystemInfoProvider is a single shared instance. It is created if
// needed, and destroyed at exit time. This is done via LazyInstance and
// scoped_refptr.
//
// The SystemInfoProvider is designed to query system information on the worker
// pool. It also maintains a queue of callbacks on the UI thread which are
// waiting for the completion of querying operation. Once the query operation
// is completed, all pending callbacks in the queue get called on the UI
// thread. In this way, it avoids frequent querying operation in case of lots
// of query requests, e.g. calling systemInfo.cpu.get repeatedly in an
// extension process.
//
// Each kind of SystemInfoProvider should satisfy an API query in a subclass on
// the blocking pool.
class SystemInfoProvider
    : public base::RefCountedThreadSafe<SystemInfoProvider> {
 public:
  // Callback type for completing to get information. The argument indicates
  // whether its contents are valid, for example, no error occurs in querying
  // the information.
  using QueryInfoCompletionCallback = base::OnceCallback<void(bool)>;
  using CallbackQueue = base::queue<QueryInfoCompletionCallback>;

  SystemInfoProvider();

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

  // Override to do any prepare work on UI thread before |QueryInfo()| gets
  // called.
  virtual void PrepareQueryOnUIThread();

  // The parameter |do_query_info_callback| is query info task which is posted
  // to SystemInfoProvider sequenced worker pool.
  //
  // You can do any initial things of *InfoProvider before start to query info.
  // While overriding this method, |do_query_info_callback| *must* be called
  // directly or indirectly.
  //
  // Sample usage please refer to StorageInfoProvider.
  virtual void InitializeProvider(base::OnceClosure do_query_info_callback);

  // Start to query the system information. Should be called on UI thread.
  // The |callback| will get called once the query is completed.
  //
  // If the parameter |callback| itself calls StartQueryInfo(callback2),
  // callback2 will be called immediately rather than triggering another call to
  // the system.
  void StartQueryInfo(QueryInfoCompletionCallback callback);

 protected:
  virtual ~SystemInfoProvider();

 private:
  friend class base::RefCountedThreadSafe<SystemInfoProvider>;

  // Interface to query the system information synchronously.
  // Return true if no error occurs.
  // Should be called in the blocking pool.
  virtual bool QueryInfo() = 0;

  // Called on UI thread. The |success| parameter means whether it succeeds
  // to get the information.
  void OnQueryCompleted(bool success);

  void StartQueryInfoPostInitialization();

  // The queue of callbacks waiting for the info querying completion. It is
  // maintained on the UI thread.
  CallbackQueue callbacks_;

  // Indicates if it is waiting for the querying completion.
  bool is_waiting_for_completion_;

  // Sequenced task runner to safely query system information.
  scoped_refptr<base::SequencedTaskRunner> task_runner_;
};

}  // namespace extensions

#endif  // EXTENSIONS_BROWSER_API_SYSTEM_INFO_SYSTEM_INFO_PROVIDER_H_


text:
package de.mirkosertic.mavensonarsputnik.processor.sonar;

import pl.touk.sputnik.configuration.Configuration;
import pl.touk.sputnik.processor.ReviewProcessorFactory;

public class SonarProcessorFactory implements ReviewProcessorFactory<SonarProcessor> {

    @Override
    public boolean isEnabled(Configuration aConfiguration) {
        return Boolean.valueOf(aConfiguration.getProperty(SonarProcessor.SONAR_ENABLED));
    }

    @Override
    public SonarProcessor create(Configuration aConfiguration) {
        return new SonarProcessor(aConfiguration);
    }
}


text:
"""Unit tests for wx.SpinCtrl

TODO:
    should it be legal for min value to be greater than max value?

Methods yet to test:
__init__, Create, SetSelection"""

import unittest
import wx

import wxtest
import testControl

class SpinCtrlTest(testControl.ControlTest):
    def setUp(self):
        self.app = wx.PySimpleApp()
        self.frame = wx.Frame(parent=None, id=wx.ID_ANY)
        self.testControl = wx.SpinCtrl(parent=self.frame)
        self.min = -1000
        self.max = 1000
        self.initial = 42

    # TODO: crashes interpreter on Windows for some reason
    def testAllControlsNeedParents(self):
        """__init__"""
        if wxtest.PlatformIsNotWindows():
            super(SpinCtrlTest,self).testAllControlsNeedParents()

    # TODO: expand tests for constructor; multiple tests, at least one for each option
    def testConstructor(self):
        """__init__"""
        # 'Nearly all of the complexity of the spin ontrol is in the constructor'
        #    - pg.209, 1st paragraph, 'wxPython in Action'
        self.testControl = wx.SpinCtrl(parent=self.frame,
                            min=self.min, max=self.max,
                            initial=self.initial)
        self.assertEquals(self.min, self.testControl.GetMin())
        self.assertEquals(self.max, self.testControl.GetMax())
        self.assertEquals(self.initial, self.testControl.GetValue())

    def testMinMaxRange(self):
        """SetRange, GetMin, GetMax"""
        for min,max in ((1,10),(-100,-10),(100,1000)):
            self.testControl.SetRange(min,max)
            self.assertEquals(min, self.testControl.GetMin())
            self.assertEquals(max, self.testControl.GetMax())

    def testValue(self):
        """SetValue, GetValue"""
        min = self.testControl.GetMin()
        max = self.testControl.GetMax()
        for i in range(min,max+1):
            self.testControl.SetValue(i)
            self.assertEquals(i, self.testControl.GetValue())
        for j in range(min-100,min):
            self.testControl.SetValue(j)
            self.assertEquals(min, self.testControl.GetValue())
        for k in range(max,max+100):
            self.testControl.SetValue(k)
            self.assertEquals(max, self.testControl.GetValue())

    def testValueString(self):
        """SetValueString"""
        min = self.testControl.GetMin()
        max = self.testControl.GetMax()
        for i in range(min,max+1):
            si = str(i)
            self.testControl.SetValueString(si)
            self.assertEquals(i, self.testControl.GetValue())
        for j in range(min-100,min):
            sj = str(j)
            self.testControl.SetValueString(sj)
            self.assertEquals(min, self.testControl.GetValue())
        for k in range(max,max+100):
            sk = str(k)
            self.testControl.SetValueString(sk)
            self.assertEquals(max, self.testControl.GetValue())

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


text:
Left to do
----------

In the order of importance.

1. Write a test suite and verify if everything is working right.
2. Out-of-design optional optimizations for special use plans.
3. Write a property test suite.

Further plans
-------------

1. Native version, through NIFs.


text:
.class Landroid/support/v13/app/f;
.super Ljava/lang/Object;

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static a(Landroid/app/Fragment;Z)V
    .locals 0

    invoke-virtual {p0, p1}, Landroid/app/Fragment;->setUserVisibleHint(Z)V

    return-void
.end method


text:
<?xml version="1.0" encoding="UTF-8"?>
<schema version='0.1.0'>
<model name='example' description='' version='0.1.0'>
	<!-- Start of "missing" categories. -->
	<category term='exampleprocci' scheme='http://scheme.compatibleone.fr/scheme/compatible#' class='kind' location='/exampleprocci/' rel='http://schemas.ogf.org/occi/core#resource' structname='exampleprocci'>
	    <attributes>
	        <attribute name='name' type='string' required='false' immutable='false'/>
	        <attribute name='flavor' type='string' required='false' immutable='false'/>
	        <attribute name='original' type='string' required='false' immutable='false'/>
	        <attribute name='image' type='string' required='false' immutable='false'/>
	        <attribute name='profile' type='string' required='false' immutable='false'/>
	        <attribute name='node' type='string' required='false' immutable='false'/>
	        <attribute name='price' type='string' required='false' immutable='false'/>
	        <attribute name='account' type='string' required='false' immutable='false'/>
	        <attribute name='number' type='string' required='false' immutable='false'/>
	        <attribute name='rootpass' type='string' required='false' immutable='false'/>
	        <attribute name='reference' type='string' required='false' immutable='false'/>
	        <attribute name='network' type='string' required='false' immutable='false'/>
	        <attribute name='access' type='string' required='false' immutable='false'/>
	        <attribute name='accessip' type='string' required='false' immutable='false'/>
	        <attribute name='floating' type='string' required='false' immutable='false'/>
	        <attribute name='floatingid' type='string' required='false' immutable='false'/>
	        <attribute name='publicaddr' type='string' required='false' immutable='false'/>
	        <attribute name='privateaddr' type='string' required='false' immutable='false'/>
	        <attribute name='firewall' type='string' required='false' immutable='false'/>
	        <attribute name='group' type='string' required='false' immutable='false'/>
	        <attribute name='zone' type='string' required='false' immutable='false'/>
	        <attribute name='hostname' type='string' required='false' immutable='false'/>
	        <attribute name='stamp' type='int' required='false' immutable='false'/>
	        <attribute name='state' type='int' required='false' immutable='false'/>
	    </attributes>
	    <actions>
	      <!-- TODO Actions -->
	    </actions>
	</category>
	<!-- End of "missing" categories. -->
</model>
</schema>


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>tyrael-commons</groupId>
    <artifactId>tyrael-commons</artifactId>
    <version>1.0</version>
  </parent>
  <artifactId>tyrael-commons-data</artifactId>
  <name>Tyrael Commons :: Data</name>

  <dependencies>
    <dependency>
      <groupId>baldy.commons</groupId>
      <artifactId>baldy-commons-data-mysql</artifactId>
    </dependency>
  </dependencies>
</project>


text:
import isObservable from 'frint-component-utils/lib/isObservable';

export default isObservable;


text:
In our EE461L Software Design Lab, we have put together Movie Matcher.

Still a work in progress. Check out our [project proposal](docs/Proposal.md) in the meantime.


text:
module ApplicationHelper
  include Spree::PagesHelper
end


text:
package org.project.openbaton.nubomedia.api.messages;

/**
 * Created by maa on 21.10.15.
 */
public class NubomediaAppNotFoundMessage {

    private String id;
    private String token;
    private final String message = "Application not found";

    public NubomediaAppNotFoundMessage() {
    }

    public NubomediaAppNotFoundMessage(String id, String token) {
        this.id = id;
        this.token = token;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getMessage() {
        return message;
    }
}


text:
def array_concat(array_1, array_2)
  array_3 = array_1 + array_2
  return array_3
end


text:
'use strict';

/**
 * @ngdoc service
 * @name itsFrontendApp.userFactoryHttp
 * @description
 * # userFactoryHttp
 * Factory in the itsFrontendApp.
 */
angular.module('itsFrontendApp')
  .factory('userFactoryHttp', function ($http) {
    var serviceUrlBase = 'http://localhost:8080/its-webservice/';

    var usersInTeam101ServiceUrl = serviceUrlBase + 'teams/101/users/';
    var usersServiceUrl = serviceUrlBase + 'users/';

    return {
      getAllUsers: function () {
        return $http.get(usersInTeam101ServiceUrl);
      },

      removeWorkItemFromUser: function (userNumber, workItemNumber) {
        return $http.delete(usersServiceUrl + userNumber + '/work-items/' + workItemNumber);
      },
      addUserToWorkItem: function (userNumber, workItemNumber) {
        return $http.put(usersServiceUrl + userNumber + '/work-items/', workItemNumber);
      }
    };

  });


text:
'use strict';

var grunt = require('grunt');

module.exports = {

    queryString: function(test) {
        test.expect(3);

        var markup = grunt.file.read('tmp/queryString/queryString.html');
        var css = grunt.file.read('tmp/queryString/css/test.css');

        test.ok(markup.match(/css\/test\.css\?123456789/), 'testing css/test.css');
        test.ok(markup.match(/imgs\/background\.jpg\?123456789/), 'testing imgs/background.jpg in markup');
        test.ok(css.match(/imgs\/background\.jpg\?123456789/), 'testing imgs/background.jpg in css');

        test.done();
    }

};


text:
namespace chrome {

void ShowAboutIPCDialog() {
  // TODO(beng):
  NOTIMPLEMENTED();
}

}  // namespace chrome

#if !defined(OS_CHROMEOS) && !defined(OS_WIN)
// static
void ExternalProtocolHandler::RunExternalProtocolDialog(
    const GURL& url,
    int render_process_host_id,
    int routing_id) {
}
#endif


text:
\begin{ManPage}{\label{man-stork-list-cred}\Stork{list\_cred}}{1}
{list all credentials of a user stored on the \Stork{credd} daemon on behalf of Stork}
\Synopsis \SynProg{\Stork{list\_cred}}
\ToolArgsBase

\SynProg{\Stork{list\_cred}}
\oOpt{-debug}
\OptArg{-n}{hostname:portnumber}

\index{Condor commands!stork\_list\_cred}
\index{Stork commands!stork\_list\_cred}
\index{stork\_list\_cred command}

\Description

\Stork{list\_cred} lists all credentials stored on the \Stork{credd} daemon
of the user issuing the \Stork{list\_cred} command.
Two fields appear for each item listed:
the unique name for the credential,
and the string "X.509".
As more credential types are handled by the \Stork{credd} daemon,
this second field with identify the credential type.

\begin{Options}
  \ToolArgsBaseDesc
  \OptItem{\Opt{-debug}}{Show extra debugging information.}
  \OptItem{\OptArg{-n}{hostname:portnumber}}
    {Identify the \Stork{credd} daemon by host name and port number.}
\end{Options}

\ExitStatus

\Stork{list\_cred} will exit with a status value of 0 (zero) upon success,
and it will exit with the value 1 (one) upon failure.

\end{ManPage}


text:
slug: ordering-unit-tests
title: Ordering NUnit Tests
description: In this post, Chris shows you how you can run tests in a specified order using NUnit.  While this should not be used for regular unit testing, it is an invaluable technique for your end-to-end testing.
createdAt: 2014-11-19
author: Chris Plowman
tags: Testing, NUnit
image: /images/for-posts/numbering.jpg
headerTextColor: white
backgroundColor: rgba(0,0,0,.5)

---

Hello all! In this blog post I'm going to shows how you can create ordered tests in NUnit. Now before you start screaming that unit tests should not have any order dependencies, let me assure you that I know and agree wholeheartedly. So why create this project and bother with showing how to do this? Simple: there are other kinds of tests besides unit tests, and they often DO have order dependencies.

For example, if you are running database integration tests, a basic CRUD test might look like this:

1.  Perform initial get and assure empty.
2.  Add an item.
3.  Get new item back.
4.  Delete item.
5.  Get empty list again.

Since we want to run this integration all the way through on a real database (hopefully NOT production!), this should be run in order. Without ensuring the order, we would have to do complex, wasteful, and time consuming setup for each step of our tests.

Of course, we have a couple options for doing this ordered test, including not using a testing framework at all. However, NUnit is a great testing framework that many developers are already very familiar with and are likely using for their actual unit tests, so why not leverage this knowledge to make our lives a little easier? Alas, NUnit has been built for unit tests, so it doesn't have any built in mechanisms for running tests in order, but with a little ingenuity it can absolutely be accomplished.

A simple way to run an ordered test would just be to build up one test method with multiple steps and assertions along the way. That might look something like this:

	[TestFixture]
    public class Test
    {
        public void LongTest()
        {
            // arrange for read
            // act for read
            // assert for read

            // arrange for insert
            // act for insert
            // assert for insert

            // on and on and on...
        }
    }

I have done this in the past for some simple tests like the example above. The nice thing with this approach is that if an assertion fails early on, the test will fail without continuing execution. Often this is exactly what you want with ordered tests since if your preconditions are not met, your later tests may not be valid. However, as your tests become more complicated, this single test becomes long and difficult to work with. Also, if you do want to continue after an initial assertion fails, you can't. So this is not a great option for real world development on big projects.

Another option is to prepend an alpha character to your tests. NUnit orders tests alphabetically, so this way you can control the running order. It's obviously a bit of a hack, can be difficult to maintain, and makes for some ugly method names. The other problem is that it could break at any time if NUnit decides to order their tests differently.

I recently stumbled across a very cool approach on [this StackOverflow question](http://stackoverflow.com/questions/1078658/nunit-test-run-order).  There are 2 great code samples provided that I have copied into [the project repository for this post](https://github.com/JC-Chris/Ordering-NUnit-Tests) to make it easier to view them side by side and test.  Let's take a quick look at the posted code to see what they are doing.

The original post, which I have called Example 1 in the repo, uses NUnit's `TestCaseSource` in a very clever way to generate the ordered tests. I won't repost the entire code here since you can see it in the repo and the original SO article, but here's the main clever bit:

	public IEnumerable<TestCaseData> TestSource
    {
        get
        {
            yield return new TestCaseData(
                new TestStructure
                {
                    Test = () =>
                    {
                        Console.WriteLine("This is test one");
                        MyInt.I++;
                        Assert.That(MyInt.I, Is.EqualTo(1));
                    }
                })
                .SetName(@"Test One");

            yield return new TestCaseData(
                new TestStructure
                {
                    Test = () =>
                    {
                        Console.WriteLine("This is test two");
                        MyInt.I++;
                        Assert.That(MyInt.I, Is.EqualTo(2));
                    }
                }).SetName(@"Test Two");
            yield return new TestCaseData(
                new TestStructure
                {
                    Test = () =>
                    {
                        Console.WriteLine("This is test three");
                        MyInt.I++;
                        Assert.That(MyInt.I, Is.EqualTo(3));
                    }
                }).SetName(@"Test Three");
        }
    }

Notice that where you would normally be returning data for your test, he's created a lambda expression that provides the test implementation. The source method then just calls this `Test` method for each iteration and since test data is always run in the provided order, you can ensure your tests are run the way you want! Super clever approach and kudos to the author.

![Example 1 successfully ordered test run output](/images/for-posts/OrderedNUnitTests/Example1Run.PNG)

The next code block from the answers, which I have called Example 2 in the repo, extends this approach to be a little more developer friendly by utilizing an attribute called `OrderedTest` that has a single `int` property to specify the order. This way you can write your test methods as usual and just decorate them with the new attribute to control the order they will run in. Much nicer syntax and I loved the idea. The main bit of code here is again building the list of "data".

	public IEnumerable<TestCaseData> TestSource
    {
        get
        {
            var assembly =Assembly.GetExecutingAssembly();
            Dictionary<int, List<MethodInfo>> methods = assembly
                .GetTypes()
                .SelectMany(x => x.GetMethods())
                .Where(y => y.GetCustomAttributes().OfType<OrderedTestAttribute>().Any())
                .GroupBy(z => z.GetCustomAttribute<OrderedTestAttribute>().Order)
                .ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
            foreach (var order in methods.Keys.OrderBy(x => x))
            {
                foreach (var methodInfo in methods[order])
                {
                    MethodInfo info = methodInfo;
                    yield return new TestCaseData(
                        new TestStructure
                            {
                                Test = () =>
                                    {
                                        object classInstance = Activator.CreateInstance(info.DeclaringType, null);
                                        info.Invoke(classInstance, null);
                                    }
                            }).SetName(methodInfo.Name);
                }
            }
        }
    }

As you can see, the author uses reflection and his attribute to pull out the test methods. Pretty smart right?! Yeah, I like this approach and it makes for a very clean class. However, there's a bit of a problem, or at least I viewed it as a problem. His reflection is pulling methods for every class in the assembly, not just the current class. This could end up with you running more tests than you actually thought you were going to. I added in the `Example2b` class in the repo to show this. The image below shows the output when I run tests for the `Example2` class. Notice that the 2b tests were run as well, even though they were out of context.

![Example 2 successfully ordered test run output with unintended tests run as well](/images/for-posts/OrderedNUnitTests/Example2Run.PNG)

Finally, for Example 3, I put my own spin on the approach making it even easier to use, at least in my opinion, and resolving the issue of running more tests than you might have intended. By pushing this into its own class, your test class can now inherit from `OrderedTestFixture` and be a bit cleaner. I also removed the `Int` class from the code because I felt it was ugly and unnecessary.

	public class OrderedTestFixture
    {
        public IEnumerable<TestCaseData> TestSource
        {
            get
            {
                var assembly = Assembly.GetExecutingAssembly();
                Dictionary<int, List<MethodInfo>> methods = assembly
                    .GetType(this.GetType().FullName)
                    .GetMethods()
                    .Where(y => y.GetCustomAttributes().OfType<OrderedTestAttribute>().Any())
                    .GroupBy(z => z.GetCustomAttribute<OrderedTestAttribute>().Order)
                    .ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());
                foreach (var order in methods.Keys.OrderBy(x => x))
                {
                    foreach (var methodInfo in methods[order])
                    {
                        MethodInfo info = methodInfo;
                        yield return new TestCaseData(
                            new TestStructure
                            {
                                Test = () =>
                                {
                                    object classInstance = Activator.CreateInstance(info.DeclaringType, null);
                                    info.Invoke(classInstance, null);
                                }
                            }).SetName(methodInfo.Name);
                    }
                }
            }
        }
    }

As you can see in the screenshot below, you can run tests from 3A or 3B and only the corresponding tests will run.

![Example 3 successfully ordered test run](/images/for-posts/OrderedNUnitTests/Example3Run.PNG)

![Example 3B successfully ordered test run](/images/for-posts/OrderedNUnitTests/Example3bRun.PNG)

I think this makes for some lovely code and should be pretty easy for you to extend further to fit your needs. For example, you could probably add in some logic to short circuit the tests on an error if you like.

Hope that helps my fellow devs. Have a look at the repo and have fun testing! Happy coding!