text:
import {
    types,
    getSnapshot,
    unprotect,
    cast,
    detach,
    clone,
    SnapshotIn,
    getNodeId
} from "../../src"

describe("snapshotProcessor", () => {
    describe("over a model type", () => {
        const M = types.model({
            x: types.string
        })

        test("no processors", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {})
            })
            const model = Model.create({ m: { x: "hi" } })
            unprotect(model)
            expect(model.m.x).toBe("hi")
            expect(getSnapshot(model).m.x).toBe("hi")
            // reconciliation
            model.m = { x: "ho" }
            expect(model.m.x).toBe("ho")
            expect(getSnapshot(model).m.x).toBe("ho")
        })

        test("pre processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    preProcessor(sn: { x: number }) {
                        return {
                            ...sn,
                            x: String(sn.x)
                        }
                    }
                })
            })
            const model = Model.create({ m: { x: 5 } })
            unprotect(model)
            expect(model.m.x).toBe("5")
            expect(getSnapshot(model).m.x).toBe("5")
            // reconciliation
            model.m = cast({ x: 6 })
            expect(model.m.x).toBe("6")
            expect(getSnapshot(model).m.x).toBe("6")
        })

        test("post processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    postProcessor(sn): { x: number } {
                        return {
                            ...sn,
                            x: Number(sn.x)
                        }
                    }
                })
            })
            const model = Model.create({
                m: { x: "5" }
            })
            unprotect(model)
            expect(model.m.x).toBe("5")
            expect(getSnapshot(model).m.x).toBe(5)
            // reconciliation
            model.m = cast({ x: "6" })
            expect(model.m.x).toBe("6")
            expect(getSnapshot(model).m.x).toBe(6)
        })

        test("pre and post processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    preProcessor(sn: { x: number }) {
                        return {
                            ...sn,
                            x: String(sn.x)
                        }
                    },
                    postProcessor(sn): { x: number } {
                        return {
                            ...sn,
                            x: Number(sn.x)
                        }
                    }
                })
            })
            const model = Model.create({
                m: { x: 5 }
            })
            unprotect(model)
            expect(model.m.x).toBe("5")
            expect(getSnapshot(model).m.x).toBe(5)
            // reconciliation
            model.m = cast({ x: 6 })
            expect(model.m.x).toBe("6")
            expect(getSnapshot(model).m.x).toBe(6)
            // cloning
            expect(getSnapshot(clone(model.m)).x).toBe(6)
        })
    })

    describe("over a literal type", () => {
        const M = types.string

        test("no processors", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {})
            })
            const model = Model.create({ m: "hi" })
            unprotect(model)
            expect(model.m).toBe("hi")
            expect(getSnapshot(model).m).toBe("hi")
            // reconciliation
            model.m = "ho"
            expect(model.m).toBe("ho")
            expect(getSnapshot(model).m).toBe("ho")
        })

        test("pre processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    preProcessor(sn: number) {
                        return String(sn)
                    }
                })
            })
            const model = Model.create({ m: 5 })
            unprotect(model)
            expect(model.m).toBe("5")
            expect(getSnapshot(model).m).toBe("5")
            // reconciliation
            model.m = 6 as any
            expect(model.m).toBe("6")
            expect(getSnapshot(model).m).toBe("6")
        })

        test("post processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    postProcessor(sn): number {
                        return Number(sn)
                    }
                })
            })
            const model = Model.create({
                m: "5"
            })
            unprotect(model)
            expect(model.m).toBe("5")
            expect(getSnapshot(model).m).toBe(5)
            // reconciliation
            model.m = "6"
            expect(model.m).toBe("6")
            expect(getSnapshot(model).m).toBe(6)
        })

        test("pre and post processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    preProcessor(sn: number) {
                        return String(sn)
                    },
                    postProcessor(sn): number {
                        return Number(sn)
                    }
                })
            })
            const model = Model.create({
                m: 5
            })
            unprotect(model)
            expect(model.m).toBe("5")
            expect(getSnapshot(model).m).toBe(5)
            // reconciliation
            model.m = "6"
            expect(model.m).toBe("6")
            expect(getSnapshot(model).m).toBe(6)
            // cloning
            expect(getSnapshot(clone(model)).m).toBe(6)
        })
    })

    describe("over an array type", () => {
        const M = types.array(types.string)

        test("no processors", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {})
            })
            const model = Model.create({ m: ["hi"] })
            unprotect(model)
            expect(model.m[0]).toBe("hi")
            expect(getSnapshot(model).m[0]).toBe("hi")
            // reconciliation
            model.m = cast(["ho"])
            expect(model.m[0]).toBe("ho")
            expect(getSnapshot(model).m[0]).toBe("ho")
        })

        test("pre processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    preProcessor(sn: number[]) {
                        return sn.map((n) => String(n))
                    }
                })
            })
            const model = Model.create({ m: [5] })
            unprotect(model)
            expect(model.m[0]).toBe("5")
            expect(getSnapshot(model).m[0]).toBe("5")
            // reconciliation
            model.m = cast([6])
            expect(model.m[0]).toBe("6")
            expect(getSnapshot(model).m[0]).toBe("6")
        })

        test("post processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    postProcessor(sn): number[] {
                        return sn.map((n) => Number(n))
                    }
                })
            })
            const model = Model.create({
                m: ["5"]
            })
            unprotect(model)
            expect(model.m[0]).toBe("5")
            expect(getSnapshot(model).m[0]).toBe(5)
            // reconciliation
            model.m = cast(["6"])
            expect(model.m[0]).toBe("6")
            expect(getSnapshot(model).m[0]).toBe(6)
        })

        test("pre and post processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    preProcessor(sn: number[]) {
                        return sn.map((n) => String(n))
                    },
                    postProcessor(sn): number[] {
                        return sn.map((n) => Number(n))
                    }
                })
            })
            const model = Model.create({
                m: [5]
            })
            unprotect(model)
            expect(model.m[0]).toBe("5")
            expect(getSnapshot(model).m[0]).toBe(5)
            // reconciliation
            model.m = cast([6])
            expect(model.m[0]).toBe("6")
            expect(getSnapshot(model).m[0]).toBe(6)
            // cloning
            expect(getSnapshot(clone(model.m))[0]).toBe(6)
        })
    })

    describe("over a map type", () => {
        const M = types.map(types.string)

        test("no processors", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {})
            })
            const model = Model.create({ m: { x: "hi" } })
            unprotect(model)
            expect(model.m.get("x")).toBe("hi")
            expect(getSnapshot(model).m.x).toBe("hi")
            // reconciliation
            model.m.set("x", "ho")
            expect(model.m.get("x")).toBe("ho")
            expect(getSnapshot(model).m.x).toBe("ho")
        })

        test("pre processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    preProcessor(sn: { x: number }) {
                        return {
                            ...sn,
                            x: String(sn.x)
                        }
                    }
                })
            })
            const model = Model.create({ m: { x: 5 } })
            unprotect(model)
            expect(model.m.get("x")).toBe("5")
            expect(getSnapshot(model).m.x).toBe("5")
            // reconciliation
            model.m = cast({ x: 6 })
            expect(model.m.get("x")).toBe("6")
            expect(getSnapshot(model).m.x).toBe("6")
        })

        test("post processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    postProcessor(sn): { x: number } {
                        return {
                            ...sn,
                            x: Number(sn.x)
                        }
                    }
                })
            })
            const model = Model.create({
                m: { x: "5" }
            })
            unprotect(model)
            expect(model.m.get("x")).toBe("5")
            expect(getSnapshot(model).m.x).toBe(5)
            // reconciliation
            model.m = cast({ x: "6" })
            expect(model.m.get("x")).toBe("6")
            expect(getSnapshot(model).m.x).toBe(6)
        })

        test("pre and post processor", () => {
            const Model = types.model({
                m: types.snapshotProcessor(M, {
                    preProcessor(sn: { x: number }) {
                        return {
                            ...sn,
                            x: String(sn.x)
                        }
                    },
                    postProcessor(sn): { x: number } {
                        return {
                            ...sn,
                            x: Number(sn.x)
                        }
                    }
                })
            })
            const model = Model.create({
                m: { x: 5 }
            })
            unprotect(model)
            expect(model.m.get("x")).toBe("5")
            expect(getSnapshot(model).m.x).toBe(5)
            // reconciliation
            model.m = cast({ x: 6 })
            expect(model.m.get("x")).toBe("6")
            expect(getSnapshot(model).m.x).toBe(6)
            // cloning
            expect(getSnapshot(clone(model.m)).x).toBe(6)
        })
    })

    test("chained transforms", () => {
        const TL = types.snapshotProcessor(types.string, {
            preProcessor(sn: string) {
                return sn.trimLeft()
            },
            postProcessor(sn): string {
                return "_" + sn
            }
        })
        const TB = types.snapshotProcessor(TL, {
            preProcessor(sn: string) {
                return sn.trimRight()
            },
            postProcessor(sn): string {
                return sn + "_"
            }
        })
        const M = types.model({
            name: TB
        })

        const t = TB.create(" hello ")
        expect(t).toBe("hello")

        const m = M.create({
            name: " hello "
        })
        expect(m.name).toBe("hello")
        expect(getSnapshot(m).name).toBe("_hello_")
    })

    describe("moving nodes around with a pre-processor", () => {
        const Task = types.model("Task", { x: types.number })
        const Store = types.model({
            a: types.array(
                types.snapshotProcessor(
                    Task,
                    {
                        preProcessor(sn: { x: string }) {
                            return {
                                x: Number(sn.x)
                            }
                        }
                    },
                    "PTask"
                )
            ),
            b: types.array(Task)
        })

        test("moving from a to b", () => {
            const s = Store.create({
                a: [{ x: "1" }]
            })
            unprotect(s)
            const n = s.a[0]
            detach(n)
            expect(s.a.length).toBe(0)
            expect(getSnapshot(n)).toEqual({ x: 1 })

            s.b.push(n)
            expect(s.b.length).toBe(1)
            expect(getSnapshot(s.b)).toEqual([{ x: 1 }])
        })

        test("moving from b to a", () => {
            const s = Store.create({
                b: [{ x: 1 }]
            })
            unprotect(s)
            const n = s.b[0]
            detach(n)
            expect(s.b.length).toBe(0)
            expect(getSnapshot(n)).toEqual({ x: 1 })

            s.a.push(n)
            expect(s.a.length).toBe(1)
            expect(getSnapshot(s.a)).toEqual([{ x: 1 }])
        })
    })

    describe("moving nodes around with a post-processor", () => {
        const Task = types.model({ x: types.number })
        const Store = types.model({
            a: types.array(
                types.snapshotProcessor(Task, {
                    postProcessor(sn): { x: string } {
                        return {
                            x: String(sn.x)
                        }
                    }
                })
            ),
            b: types.array(Task)
        })

        test("moving from a to b", () => {
            const s = Store.create({
                a: [{ x: 1 }]
            })
            unprotect(s)
            const n = s.a[0]
            detach(n)
            expect(s.a.length).toBe(0)
            expect(getSnapshot(n)).toEqual({ x: "1" })

            s.b.push(n)
            expect(s.b.length).toBe(1)
            expect(getSnapshot(s.b)).toEqual([{ x: "1" }])
        })

        test("moving from b to a", () => {
            const s = Store.create({
                b: [{ x: 1 }]
            })
            unprotect(s)
            const n = s.b[0]
            detach(n)
            expect(s.b.length).toBe(0)
            expect(getSnapshot(n)).toEqual({ x: 1 })

            s.a.push(n)
            expect(s.a.length).toBe(1)
            expect(getSnapshot(s.a)).toEqual([{ x: "1" }])
        })
    })

    describe("assigning instances works", () => {
        const Todo = types.model("Todo", {
            id: types.identifier
        })

        const TodoWithProcessor = types.snapshotProcessor(Todo, {
            preProcessor(snapshot: { id: string }) {
                return snapshot
            }
        })

        const Store = types
            .model("TodoStore", {
                todos: types.map(TodoWithProcessor),
                instance: types.optional(TodoWithProcessor, { id: "new" })
            })
            .actions((self) => ({
                addTodo(todo: { id: string }) {
                    self.todos.put(todo)
                },
                setInstance(next: { id: string }) {
                    self.instance = next
                }
            }))

        test("using instances in maps work", () => {
            const store = Store.create()
            const todo = TodoWithProcessor.create({ id: "map" })

            store.addTodo(todo)

            expect(store.todos.size).toBe(1)
            expect(getSnapshot(store.todos)).toEqual({ map: { id: "map" } })
        })

        test("using instances as values works", () => {
            const store = Store.create()
            const todo = TodoWithProcessor.create({ id: "map" })

            store.setInstance(todo)

            expect(store.instance).toBe(todo)
        })

        test("using the non processed type in place of the processed one works", () => {
            const store = Store.create()
            const todo = Todo.create({ id: "map" })

            store.setInstance(todo)

            expect(store.instance).toBe(todo)
        })

        test("using the processed type in place of the non processed one works", () => {
            const store = types
                .model("Store", { instance: Todo })
                .actions((self) => ({
                    setInstance(next: { id: string }) {
                        self.instance = next
                    }
                }))
                .create({ instance: { id: "new" } })

            const todo = TodoWithProcessor.create({ id: "map" })

            store.setInstance(todo)

            expect(store.instance).toBe(todo)
        })
    })

    test("cached initial snapshots are ok", () => {
        const M2 = types.snapshotProcessor(types.model({ x: types.number }), {
            preProcessor(sn: { x: number }) {
                return { ...sn, x: 0 }
            }
        })
        const M1 = types.model({ m2: M2 })
        const M = types.model({ m1: M1 })

        const m = M.create({ m1: { m2: { x: 10 } } })
        expect(getSnapshot(m)).toEqual({
            m1: { m2: { x: 0 } }
        })
    })

    test("works with IType.is", () => {
        const Model = types.model({ x: types.number })
        const model = Model.create({ x: 1 })
        expect(Model.is(model)).toBe(true)
        expect(Model.is({ x: 1 })).toBe(true)

        const ProcessedModel = types.snapshotProcessor(Model, {
            preProcessor(sn: { y: number }) {
                const copy = { ...sn, x: sn.y }
                // @ts-ignore
                delete copy.y
                return copy
            },
            postProcessor(sn: { x: number }) {
                const copy = { ...sn, y: sn.x }
                // @ts-ignore
                delete copy.x
                return copy
            }
        })

        const processedModel = ProcessedModel.create({ y: 1 })
        expect(ProcessedModel.is(processedModel)).toBe(true)
        expect(ProcessedModel.is({ y: 1 })).toBe(true)
        expect(ProcessedModel.is(Model)).toBe(false)
    })

    describe("1776 - reconciliation in an array", () => {
        test("model with transformed property is reconciled", () => {
            const SP = types.snapshotProcessor(
                types.model({
                    id: types.identifier,
                    x: types.number
                }),
                {
                    preProcessor(sn: { id: string; y: number }) {
                        if ("x" in sn) {
                            // Ensure snapshot don't run through preprocessor twice
                            throw new Error("sn has already been preprocessed")
                        }
                        return { id: sn.id, x: sn.y }
                    }
                }
            )
            const Store = types.model({ items: types.array(SP) }).actions((self) => ({
                setItems(items: SnapshotIn<typeof SP>[]) {
                    self.items = cast(items)
                }
            }))
            const store = Store.create({ items: [{ id: "1", y: 0 }] })
            const oldNodeId = getNodeId(store.items[0])
            store.setItems([{ id: "1", y: 1 }])
            expect(getNodeId(store.items[0])).toBe(oldNodeId)
        })

        test("model with transformed identifier attribute is reconciled", () => {
            const SP = types.snapshotProcessor(
                types.model({
                    id: types.identifier
                }),
                {
                    preProcessor(sn: { foo: string }) {
                        return { id: sn.foo }
                    }
                }
            )
            const Store = types.model({ items: types.array(SP) }).actions((self) => ({
                setItems(items: SnapshotIn<typeof SP>[]) {
                    self.items = cast(items)
                }
            }))
            const store = Store.create({ items: [{ foo: "1" }] })
            const oldNodeId = getNodeId(store.items[0])
            store.setItems([{ foo: "1" }])
            expect(getNodeId(store.items[0])).toBe(oldNodeId)
        })
    })

    describe("single node reconcilication", () => {
        test("model with transformed property is reconciled", () => {
            const SP = types.snapshotProcessor(
                types.model({
                    id: types.identifier,
                    x: types.number
                }),
                {
                    preProcessor(sn: { id: string; y: number }) {
                        if ("x" in sn) {
                            // Ensure snapshot don't run through preprocessor twice
                            throw new Error("sn has already been preprocessed")
                        }
                        return { id: sn.id, x: sn.y }
                    }
                }
            )
            const Store = types.model({ item: SP }).actions((self) => ({
                setItem(item: SnapshotIn<typeof SP>) {
                    self.item = cast(item)
                }
            }))
            const store = Store.create({ item: { id: "1", y: 0 } })
            const oldNodeId = getNodeId(store.item)
            store.setItem({ id: "1", y: 1 })
            expect(getNodeId(store.item)).toBe(oldNodeId)
            expect(store.item.x).toBe(1)
        })

        test("model with transformed identifier property is reconciled", () => {
            const SP = types.snapshotProcessor(
                types.model({
                    id: types.identifier
                }),
                {
                    preProcessor(sn: { foo: string }) {
                        return { id: sn.foo }
                    }
                }
            )
            const Store = types.model({ item: SP }).actions((self) => ({
                setItem(item: SnapshotIn<typeof SP>) {
                    self.item = cast(item)
                }
            }))
            const store = Store.create({ item: { foo: "1" } })
            const oldNodeId = getNodeId(store.item)
            store.setItem({ foo: "1" })
            expect(getNodeId(store.item)).toBe(oldNodeId)
            expect(store.item.id).toBe("1")
        })

        test("1791 - model wrapped with maybe is reconciled", () => {
            const SP = types.snapshotProcessor(
                types.model({
                    id: types.identifier,
                    x: types.number
                }),
                {
                    preProcessor(sn: { id: string; y: number }) {
                        return { id: sn.id, x: sn.y }
                    }
                }
            )
            const Store = types.model({ item: types.maybe(SP) }).actions((self) => ({
                setItem(item: SnapshotIn<typeof SP>) {
                    self.item = cast(item)
                }
            }))
            const store = Store.create({ item: { id: "1", y: 0 } })
            const oldNodeId = getNodeId(store.item!)
            store.setItem({ id: "1", y: 1 })
            expect(getNodeId(store.item!)).toBe(oldNodeId)
            expect(store.item?.x).toBe(1)
        })

        test("model wrapped with optional is reconciled", () => {
            const SP = types.snapshotProcessor(
                types.model({
                    id: types.identifier,
                    x: types.number
                }),
                {
                    preProcessor(sn: { id: string; y: number }) {
                        return { id: sn.id, x: sn.y }
                    }
                }
            )
            const Store = types
                .model({ item: types.optional(SP, { id: "1", y: 0 }) })
                .actions((self) => ({
                    setItem(item?: SnapshotIn<typeof SP>) {
                        self.item = cast(item)
                    }
                }))
            const store = Store.create()
            const oldNodeId = getNodeId(store.item!)
            expect(store.item?.x).toBe(0)
            store.setItem({ id: "1", y: 1 })
            expect(getNodeId(store.item!)).toBe(oldNodeId)
            expect(store.item?.x).toBe(1)
            store.setItem(undefined)
            expect(getNodeId(store.item!)).toBe(oldNodeId)
            expect(store.item?.x).toBe(0)
        })
    })

    test("1777 - preProcessor wrapped in maybe accepts undefined", () => {
        const SP = types.snapshotProcessor(
            types.model({
                id: types.identifier,
                x: types.number
            }),
            {
                preProcessor(sn: { id: string; y: number }) {
                    return { id: sn.id, x: sn.y }
                }
            }
        )
        const Store = types.model({ item: types.maybe(SP) }).actions((self) => ({
            setItem(item?: SnapshotIn<typeof SP>) {
                self.item = cast(item)
            }
        }))
        const store = Store.create()
        expect(store.item).toBeUndefined()
        store.setItem({ id: "1", y: 1 })
        expect(store.item?.x).toBe(1)
        store.setItem(undefined)
        expect(store.item).toBeUndefined()
    })

    test("1849 - Wrapped unions don't cause infinite recursion", () => {
        const Store = types
            .model({
                prop: types.optional(
                    types.snapshotProcessor(
                        types.union(types.literal("a"), types.literal("b")),
                        {}
                    ),
                    "a"
                )
            })
            .actions((self) => ({
                setProp(prop: typeof self.prop) {
                    self.prop = prop
                }
            }))

        const store = Store.create()
        expect(store.prop).toBe("a")
        expect(() => store.setProp("b")).not.toThrow()
        expect(store.prop).toBe("b")
    })
})


text:
namespace ArgentPonyWarcraftClient;

/// <summary>
///     A client for the World of Warcraft Connected Realm API.
/// </summary>
public interface IConnectedRealmApi
{
    /// <summary>
    ///     Gets an index of connected realms.
    /// </summary>
    /// <param name="namespace">The namespace to use to locate this document.</param>
    /// <returns>
    ///     The connected realms index.
    /// </returns>
    Task<RequestResult<ConnectedRealmsIndex>> GetConnectedRealmsIndexAsync(string @namespace);

    /// <summary>
    ///     Gets an index of connected realms.
    /// </summary>
    /// <param name="namespace">The namespace to use to locate this document.</param>
    /// <param name="region">Specifies the region that the API will retrieve its data from.</param>
    /// <param name="locale">Specifies the language that the result will be in.</param>
    /// <returns>
    ///     The connected realms index.
    /// </returns>
    Task<RequestResult<ConnectedRealmsIndex>> GetConnectedRealmsIndexAsync(string @namespace, Region region, Locale locale);

    /// <summary>
    ///     Get the specified connected realm.
    /// </summary>
    /// <param name="connectedRealmId">The ID of the connected realm.</param>
    /// <param name="namespace">The namespace to use to locate this document.</param>
    /// <returns>
    ///     The specified connected realm.
    /// </returns>
    Task<RequestResult<ConnectedRealm>> GetConnectedRealmAsync(int connectedRealmId, string @namespace);

    /// <summary>
    ///     Get the specified connected realm.
    /// </summary>
    /// <param name="connectedRealmId">The ID of the connected realm.</param>
    /// <param name="namespace">The namespace to use to locate this document.</param>
    /// <param name="region">Specifies the region that the API will retrieve its data from.</param>
    /// <param name="locale">Specifies the language that the result will be in.</param>
    /// <returns>
    ///     The specified connected realm.
    /// </returns>
    Task<RequestResult<ConnectedRealm>> GetConnectedRealmAsync(int connectedRealmId, string @namespace, Region region, Locale locale);
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Delete completeResponsesCount in Photo as it is an ambigious duplicate of priority
 */
class Version20130115233042 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is autogenerated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

        $this->addSql("ALTER TABLE Photo DROP completeResponsesCount");
    }

    public function down(Schema $schema)
    {
        // this down() migration is autogenerated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

        $this->addSql("ALTER TABLE Photo ADD completeResponsesCount INT NOT NULL");
    }
}


text:
void *generate_pointer(bool);

@interface CTNullAssertionTestBase : CTAssertionTestBase

@property (nonatomic, assign) void *testVariable;
@property (nonatomic, assign) bool useRealPointer;

@end


text:
define([
	'backbone',
	'model/contact'
], function (Backbone, Contact) {
	return Backbone.Collection.extend({
		model: Contact
	})
})


text:
#region License

#endregion

#region Authors
/*
 * Authors:
 * - Gonzalo Paniagua Javier <gonzalo@novell.com>
 */
#endregion

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace CustomWebSocketSharp.Net
{
  /// <summary>
  /// Provides the access to a request to the <see cref="HttpListener"/>.
  /// </summary>
  /// <remarks>
  /// The HttpListenerRequest class cannot be inherited.
  /// </remarks>
  public sealed class HttpListenerRequest
  {
    #region Private Fields

    private static readonly byte[] _100continue;
    private string[]               _acceptTypes;
    private bool                   _chunked;
    private Encoding               _contentEncoding;
    private long                   _contentLength;
    private bool                   _contentLengthSet;
    private HttpListenerContext    _context;
    private CookieCollection       _cookies;
    private WebHeaderCollection    _headers;
    private Guid                   _identifier;
    private Stream                 _inputStream;
    private bool                   _keepAlive;
    private bool                   _keepAliveSet;
    private string                 _method;
    private NameValueCollection    _queryString;
    private Uri                    _referer;
    private string                 _uri;
    private Uri                    _url;
    private string[]               _userLanguages;
    private Version                _version;
    private bool                   _websocketRequest;
    private bool                   _websocketRequestSet;

    #endregion

    #region Static Constructor

    static HttpListenerRequest ()
    {
      _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
    }

    #endregion

    #region Internal Constructors

    internal HttpListenerRequest (HttpListenerContext context)
    {
      _context = context;
      _contentLength = -1;
      _headers = new WebHeaderCollection ();
      _identifier = Guid.NewGuid ();
    }

    #endregion

    #region Public Properties

    /// <summary>
    /// Gets the media types which are acceptable for the response.
    /// </summary>
    /// <value>
    /// An array of <see cref="string"/> that contains the media type names in
    /// the Accept request-header, or <see langword="null"/> if the request didn't include
    /// the Accept header.
    /// </value>
    public string[] AcceptTypes {
      get {
        return _acceptTypes;
      }
    }

    /// <summary>
    /// Gets an error code that identifies a problem with the client's certificate.
    /// </summary>
    /// <value>
    /// Always returns <c>0</c>.
    /// </value>
    public int ClientCertificateError {
      get {
        return 0; // TODO: Always returns 0.
      }
    }

    /// <summary>
    /// Gets the encoding for the entity body data included in the request.
    /// </summary>
    /// <value>
    /// A <see cref="Encoding"/> that represents the encoding for the entity body data,
    /// or <see cref="Encoding.Default"/> if the request didn't include the information about
    /// the encoding.
    /// </value>
    public Encoding ContentEncoding {
      get {
        return _contentEncoding ?? (_contentEncoding = Encoding.Default);
      }
    }

    /// <summary>
    /// Gets the number of bytes in the entity body data included in the request.
    /// </summary>
    /// <value>
    /// A <see cref="long"/> that represents the value of the Content-Length entity-header,
    /// or <c>-1</c> if the value isn't known.
    /// </value>
    public long ContentLength64 {
      get {
        return _contentLength;
      }
    }

    /// <summary>
    /// Gets the media type of the entity body included in the request.
    /// </summary>
    /// <value>
    /// A <see cref="string"/> that represents the value of the Content-Type entity-header.
    /// </value>
    public string ContentType {
      get {
        return _headers["Content-Type"];
      }
    }

    /// <summary>
    /// Gets the cookies included in the request.
    /// </summary>
    /// <value>
    /// A <see cref="CookieCollection"/> that contains the cookies included in the request.
    /// </value>
    public CookieCollection Cookies {
      get {
        return _cookies ?? (_cookies = _headers.GetCookies (false));
      }
    }

    /// <summary>
    /// Gets a value indicating whether the request has the entity body.
    /// </summary>
    /// <value>
    /// <c>true</c> if the request has the entity body; otherwise, <c>false</c>.
    /// </value>
    public bool HasEntityBody {
      get {
        return _contentLength > 0 || _chunked;
      }
    }

    /// <summary>
    /// Gets the HTTP headers used in the request.
    /// </summary>
    /// <value>
    /// A <see cref="NameValueCollection"/> that contains the HTTP headers used in the request.
    /// </value>
    public NameValueCollection Headers {
      get {
        return _headers;
      }
    }

    /// <summary>
    /// Gets the HTTP method used in the request.
    /// </summary>
    /// <value>
    /// A <see cref="string"/> that represents the HTTP method used in the request.
    /// </value>
    public string HttpMethod {
      get {
        return _method;
      }
    }

    /// <summary>
    /// Gets a <see cref="Stream"/> that contains the entity body data included in the request.
    /// </summary>
    /// <value>
    /// A <see cref="Stream"/> that contains the entity body data included in the request.
    /// </value>
    public Stream InputStream {
      get {
        return _inputStream ??
               (_inputStream = HasEntityBody
                               ? _context.Connection.GetRequestStream (_contentLength, _chunked)
                               : Stream.Null);
      }
    }

    /// <summary>
    /// Gets a value indicating whether the client that sent the request is authenticated.
    /// </summary>
    /// <value>
    /// <c>true</c> if the client is authenticated; otherwise, <c>false</c>.
    /// </value>
    public bool IsAuthenticated {
      get {
        return _context.User != null;
      }
    }

    /// <summary>
    /// Gets a value indicating whether the request is sent from the local computer.
    /// </summary>
    /// <value>
    /// <c>true</c> if the request is sent from the local computer; otherwise, <c>false</c>.
    /// </value>
    public bool IsLocal {
      get {
        return RemoteEndPoint.Address.IsLocal ();
      }
    }

    /// <summary>
    /// Gets a value indicating whether the HTTP connection is secured using the SSL protocol.
    /// </summary>
    /// <value>
    /// <c>true</c> if the HTTP connection is secured; otherwise, <c>false</c>.
    /// </value>
    public bool IsSecureConnection {
      get {
        return _context.Connection.IsSecure;
      }
    }

    /// <summary>
    /// Gets a value indicating whether the request is a WebSocket connection request.
    /// </summary>
    /// <value>
    /// <c>true</c> if the request is a WebSocket connection request; otherwise, <c>false</c>.
    /// </value>
    public bool IsWebSocketRequest {
      get {
        if (!_websocketRequestSet) {
          _websocketRequest = _method == "GET" &&
                              _version > HttpVersion.Version10 &&
                              _headers.Contains ("Upgrade", "websocket") &&
                              _headers.Contains ("Connection", "Upgrade");

          _websocketRequestSet = true;
        }

        return _websocketRequest;
      }
    }

    /// <summary>
    /// Gets a value indicating whether the client requests a persistent connection.
    /// </summary>
    /// <value>
    /// <c>true</c> if the client requests a persistent connection; otherwise, <c>false</c>.
    /// </value>
    public bool KeepAlive {
      get {
        if (!_keepAliveSet) {
          string keepAlive;
          _keepAlive = _version > HttpVersion.Version10 ||
                       _headers.Contains ("Connection", "keep-alive") ||
                       ((keepAlive = _headers["Keep-Alive"]) != null && keepAlive != "closed");

          _keepAliveSet = true;
        }

        return _keepAlive;
      }
    }

    /// <summary>
    /// Gets the server endpoint as an IP address and a port number.
    /// </summary>
    /// <value>
    /// A <see cref="System.Net.IPEndPoint"/> that represents the server endpoint.
    /// </value>
    public System.Net.IPEndPoint LocalEndPoint {
      get {
        return _context.Connection.LocalEndPoint;
      }
    }

    /// <summary>
    /// Gets the HTTP version used in the request.
    /// </summary>
    /// <value>
    /// A <see cref="Version"/> that represents the HTTP version used in the request.
    /// </value>
    public Version ProtocolVersion {
      get {
        return _version;
      }
    }

    /// <summary>
    /// Gets the query string included in the request.
    /// </summary>
    /// <value>
    /// A <see cref="NameValueCollection"/> that contains the query string parameters.
    /// </value>
    public NameValueCollection QueryString {
      get {
        return _queryString ??
               (_queryString = HttpUtility.InternalParseQueryString (_url.Query, Encoding.UTF8));
      }
    }

    /// <summary>
    /// Gets the raw URL (without the scheme, host, and port) requested by the client.
    /// </summary>
    /// <value>
    /// A <see cref="string"/> that represents the raw URL requested by the client.
    /// </value>
    public string RawUrl {
      get {
        return _url.PathAndQuery; // TODO: Should decode?
      }
    }

    /// <summary>
    /// Gets the client endpoint as an IP address and a port number.
    /// </summary>
    /// <value>
    /// A <see cref="System.Net.IPEndPoint"/> that represents the client endpoint.
    /// </value>
    public System.Net.IPEndPoint RemoteEndPoint {
      get {
        return _context.Connection.RemoteEndPoint;
      }
    }

    /// <summary>
    /// Gets the request identifier of a incoming HTTP request.
    /// </summary>
    /// <value>
    /// A <see cref="Guid"/> that represents the identifier of a request.
    /// </value>
    public Guid RequestTraceIdentifier {
      get {
        return _identifier;
      }
    }

    /// <summary>
    /// Gets the URL requested by the client.
    /// </summary>
    /// <value>
    /// A <see cref="Uri"/> that represents the URL requested by the client.
    /// </value>
    public Uri Url {
      get {
        return _url;
      }
    }

    /// <summary>
    /// Gets the URL of the resource from which the requested URL was obtained.
    /// </summary>
    /// <value>
    /// A <see cref="Uri"/> that represents the value of the Referer request-header,
    /// or <see langword="null"/> if the request didn't include an Referer header.
    /// </value>
    public Uri UrlReferrer {
      get {
        return _referer;
      }
    }

    /// <summary>
    /// Gets the information about the user agent originating the request.
    /// </summary>
    /// <value>
    /// A <see cref="string"/> that represents the value of the User-Agent request-header.
    /// </value>
    public string UserAgent {
      get {
        return _headers["User-Agent"];
      }
    }

    /// <summary>
    /// Gets the server endpoint as an IP address and a port number.
    /// </summary>
    /// <value>
    /// A <see cref="string"/> that represents the server endpoint.
    /// </value>
    public string UserHostAddress {
      get {
        return LocalEndPoint.ToString ();
      }
    }

    /// <summary>
    /// Gets the internet host name and port number (if present) specified by the client.
    /// </summary>
    /// <value>
    /// A <see cref="string"/> that represents the value of the Host request-header.
    /// </value>
    public string UserHostName {
      get {
        return _headers["Host"];
      }
    }

    /// <summary>
    /// Gets the natural languages which are preferred for the response.
    /// </summary>
    /// <value>
    /// An array of <see cref="string"/> that contains the natural language names in
    /// the Accept-Language request-header, or <see langword="null"/> if the request
    /// didn't include an Accept-Language header.
    /// </value>
    public string[] UserLanguages {
      get {
        return _userLanguages;
      }
    }

    #endregion

    #region Private Methods

    private static bool tryCreateVersion (string version, out Version result)
    {
      try {
        result = new Version (version);
        return true;
      }
      catch {
        result = null;
        return false;
      }
    }

    #endregion

    #region Internal Methods

    internal void AddHeader (string header)
    {
      var colon = header.IndexOf (':');
      if (colon == -1) {
        _context.ErrorMessage = "Invalid header";
        return;
      }

      var name = header.Substring (0, colon).Trim ();
      var val = header.Substring (colon + 1).Trim ();
      _headers.InternalSet (name, val, false);

      var lower = name.ToLower (CultureInfo.InvariantCulture);
      if (lower == "accept") {
        _acceptTypes = new List<string> (val.SplitHeaderValue (',')).ToArray ();
        return;
      }

      if (lower == "accept-language") {
        _userLanguages = val.Split (',');
        return;
      }

      if (lower == "content-length") {
        long len;
        if (Int64.TryParse (val, out len) && len >= 0) {
          _contentLength = len;
          _contentLengthSet = true;
        }
        else {
          _context.ErrorMessage = "Invalid Content-Length header";
        }

        return;
      }

      if (lower == "content-type") {
        try {
          _contentEncoding = HttpUtility.GetEncoding (val);
        }
        catch {
          _context.ErrorMessage = "Invalid Content-Type header";
        }

        return;
      }

      if (lower == "referer")
        _referer = val.ToUri ();
    }

    internal void FinishInitialization ()
    {
      var host = _headers["Host"];
      var nohost = host == null || host.Length == 0;
      if (_version > HttpVersion.Version10 && nohost) {
        _context.ErrorMessage = "Invalid Host header";
        return;
      }

      if (nohost)
        host = UserHostAddress;

      _url = HttpUtility.CreateRequestUrl (_uri, host, IsWebSocketRequest, IsSecureConnection);
      if (_url == null) {
        _context.ErrorMessage = "Invalid request url";
        return;
      }

      var enc = Headers["Transfer-Encoding"];
      if (_version > HttpVersion.Version10 && enc != null && enc.Length > 0) {
        _chunked = enc.ToLower () == "chunked";
        if (!_chunked) {
          _context.ErrorMessage = String.Empty;
          _context.ErrorStatus = 501;

          return;
        }
      }

      if (!_chunked && !_contentLengthSet) {
        var method = _method.ToLower ();
        if (method == "post" || method == "put") {
          _context.ErrorMessage = String.Empty;
          _context.ErrorStatus = 411;

          return;
        }
      }

      var expect = Headers["Expect"];
      if (expect != null && expect.Length > 0 && expect.ToLower () == "100-continue") {
        var output = _context.Connection.GetResponseStream ();
        output.InternalWrite (_100continue, 0, _100continue.Length);
      }
    }

    // Returns true is the stream could be reused.
    internal bool FlushInput ()
    {
      if (!HasEntityBody)
        return true;

      var len = 2048;
      if (_contentLength > 0)
        len = (int) Math.Min (_contentLength, (long) len);

      var buff = new byte[len];
      while (true) {
        // TODO: Test if MS has a timeout when doing this.
        try {
          var ares = InputStream.BeginRead (buff, 0, len, null, null);
          if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100))
            return false;

          if (InputStream.EndRead (ares) <= 0)
            return true;
        }
        catch {
          return false;
        }
      }
    }

    internal void SetRequestLine (string requestLine)
    {
      var parts = requestLine.Split (new[] { ' ' }, 3);
      if (parts.Length != 3) {
        _context.ErrorMessage = "Invalid request line (parts)";
        return;
      }

      _method = parts[0];
      if (!_method.IsToken ()) {
        _context.ErrorMessage = "Invalid request line (method)";
        return;
      }

      _uri = parts[1];

      var ver = parts[2];
      if (ver.Length != 8 ||
          !ver.StartsWith ("HTTP/") ||
          !tryCreateVersion (ver.Substring (5), out _version) ||
          _version.Major < 1)
        _context.ErrorMessage = "Invalid request line (version)";
    }

    #endregion

    #region Public Methods

    /// <summary>
    /// Begins getting the client's X.509 v.3 certificate asynchronously.
    /// </summary>
    /// <remarks>
    /// This asynchronous operation must be completed by calling
    /// the <see cref="EndGetClientCertificate"/> method. Typically,
    /// that method is invoked by the <paramref name="requestCallback"/> delegate.
    /// </remarks>
    /// <returns>
    /// An <see cref="IAsyncResult"/> that contains the status of the asynchronous operation.
    /// </returns>
    /// <param name="requestCallback">
    /// An <see cref="AsyncCallback"/> delegate that references the method(s) called when
    /// the asynchronous operation completes.
    /// </param>
    /// <param name="state">
    /// An <see cref="object"/> that contains a user defined object to pass to
    /// the <paramref name="requestCallback"/> delegate.
    /// </param>
    /// <exception cref="NotImplementedException">
    /// This method isn't implemented.
    /// </exception>
    public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state)
    {
      // TODO: Not implemented.
      throw new NotImplementedException ();
    }

    /// <summary>
    /// Ends an asynchronous operation to get the client's X.509 v.3 certificate.
    /// </summary>
    /// <remarks>
    /// This method completes an asynchronous operation started by calling
    /// the <see cref="BeginGetClientCertificate"/> method.
    /// </remarks>
    /// <returns>
    /// A <see cref="X509Certificate2"/> that contains the client's X.509 v.3 certificate.
    /// </returns>
    /// <param name="asyncResult">
    /// An <see cref="IAsyncResult"/> obtained by calling
    /// the <see cref="BeginGetClientCertificate"/> method.
    /// </param>
    /// <exception cref="NotImplementedException">
    /// This method isn't implemented.
    /// </exception>
    public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
    {
      // TODO: Not implemented.
      throw new NotImplementedException ();
    }

    /// <summary>
    /// Gets the client's X.509 v.3 certificate.
    /// </summary>
    /// <returns>
    /// A <see cref="X509Certificate2"/> that contains the client's X.509 v.3 certificate.
    /// </returns>
    /// <exception cref="NotImplementedException">
    /// This method isn't implemented.
    /// </exception>
    public X509Certificate2 GetClientCertificate ()
    {
      // TODO: Not implemented.
      throw new NotImplementedException ();
    }

    /// <summary>
    /// Returns a <see cref="string"/> that represents
    /// the current <see cref="HttpListenerRequest"/>.
    /// </summary>
    /// <returns>
    /// A <see cref="string"/> that represents the current <see cref="HttpListenerRequest"/>.
    /// </returns>
    public override string ToString ()
    {
      var buff = new StringBuilder (64);
      buff.AppendFormat ("{0} {1} HTTP/{2}\r\n", _method, _uri, _version);
      buff.Append (_headers.ToString ());

      return buff.ToString ();
    }

    #endregion
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="line">
    <solid android:color="@color/indicate_tab_color_selector"/>
    <size
        android:width="@dimen/tab_width"
        android:height="2dp"/>
</shape>


text:
. "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/scriptLib"

start validation "RUNNING FRAMEWORK VALIDATION"
sbt headerCheck Test/headerCheck javafmtCheckAll scalafmtCheckAll scalafmtSbtCheck
start validation "FRAMEWORK VALIDATION DONE"

pushd "$DOCUMENTATION"
start doc-validation "RUNNING DOCUMENTATION VALIDATION"
sbt headerCheck Test/headerCheck javafmtCheckAll scalafmtCheckAll scalafmtSbtCheck || (
  echo "WARN: Format and/or license headers validaton failed."
  echo "You need to run in sbt ';headerCreate ;Test/headerCreate ;javafmtAll ;scalafmtAll ;scalafmtSbt'"
  echo "then commit the new changes or amend the existing commit."
  echo "See more information about amending commits in our docs:"
  echo "https://playframework.com/documentation/latest/WorkingWithGit"
  false
)

popd

end doc-validation "ALL VALIDATIONS DONE"


text:
Consul-Imex is a simple import/export tool for [Consul](https://www.consul.io/) key/value storage over Consul HTTP API.

* Export all the keys in a prefix, save it as a json file.
* Import the keys from a json file to Consul under a specified prefix.
* Copy keys:
  - from a prefix to another prefix.
  - from a server to another server under a specified prefix.

## Installation

You can install Consul Imex in several ways:

* Executable phar file (requires PHP >=5.5.9)
* Docker image (requires [Docker](https://www.docker.com/) engine)
* Composer dependency (requires [Git](https://git-scm.com/), [Composer](https://getcomposer.org/) and PHP >=5.5.9)
* Single PHP project (requires [Git](https://git-scm.com/), [Composer](https://getcomposer.org/) and PHP >=5.5.9)

### Install as an executable phar file

Download the phar file from `https://github.com/gamegos/consul-imex/releases/download/1.0.0-rc1/consul-imex.phar`, then assign execute permission for it.

Example:

    wget -O /usr/local/bin/consul-imex https://github.com/gamegos/consul-imex/releases/download/1.0.0-rc1/consul-imex.phar
    chmod +x /usr/local/bin/consul-imex

### Install as a docker image

    docker pull sozpinar/consul-imex

### Install as a Composer dependency

    composer require gamegos/consul-imex

### Install as a PHP project

Install via `composer`:

    composer create-project gamegos/consul-imex

Or clone/download and install manually:

    git clone https://github.com/gamegos/consul-imex.git
    cd consul-imex
    composer install

## Usage

#### Run as an executable phar file:

    consul-imex <command> [options] [arguments]

#### Run as a docker container:

See [Notices for Docker Usage](#notices-for-docker-usage) for detailed information of docker usage.

    docker run -t -v `pwd`:/consul-imex sozpinar/consul-imex <command> [options] [arguments]

#### Run as a composer vendor binary:

    composer exec -- consul-imex <command> [options] [arguments]

#### Run as a PHP script:

    php scripts/consul-imex.php <command> [options] [arguments]

### Export

#### Usage:

    consul-imex export [options] <file>

#### Arguments:

* **file:** Output data file.

#### Options:

* **--url (-u):** Consul server url.
* **--prefix (-p):** Path prefix.
* **--token (-c):** Consul token.

### Import

#### Usage:

    consul-imex import [options] <file>

#### Arguments:

* **file:** Input data file.

#### Options:

* **--url (-u):** Consul server url.
* **--prefix (-p):** Path prefix.
* **--token (-c):** Consul token.

### Copy

#### Usage:

    consul-imex copy [options] <source> <target>

#### Arguments:

* **source:** Source prefix.
* **target:** Target prefix.

#### Options:

* **--source-server (-s):** Source server URL.
* **--target-server (-t):** Target server URL. If omitted, source server is used as target server.
* **--source-server-token (-c):** Source server Consul token.
* **--target-server-token:** Target server Consul token. If omitted, source server token is used as target server token.

## Examples

### Export

    $ consul-imex export -u http://localhost:8500 -p /old/prefix my-data.json
    93 keys are fetched.

Export using token key:

    $ consul-imex export -c 4874874a-2a3s-7892-123e-597a4e1v87e1 -u http://localhost:8500 -p /old/prefix my-data.json
    93 keys are fetched.

### Import

    $ consul-imex import -u http://localhost:8500 -p /new/prefix my-data.json
    93 keys are stored. (25 new directories are created.)

Import using token key:

    $ consul-imex import -c 4874874a-2a3s-7892-123e-597a4e1v87e1 -u http://localhost:8500 -p /new/prefix my-data.json
    93 keys are stored. (25 new directories are created.)

### Copy

Copy keys from `/old/prefix` to `/new/prefix`:

    $ consul-imex copy -s http://localhost:8500 /old/prefix /new/prefix
    93 keys are fetched.
    93 keys are stored. (25 new directories are created.)
    Operation completed.

Copy keys from `/old/prefix` to `/new/prefix` using token:

    $ consul-imex copy -s http://localhost:8500 -c 4874874a-2a3s-7892-123e-597a4e1v87e1 /old/prefix /new/prefix
    93 keys are fetched.
    93 keys are stored. (25 new directories are created.)
    Operation completed.

Copy keys under `/my/prefix` to another server:

    $ consul-imex copy -s http://localhost:8500 -t http://anotherhost:8500 /my/prefix /my/prefix
    93 keys are fetched.
    93 keys are stored. (25 new directories are created.)
    Operation completed.

Copy keys under `/my/prefix` to another server using token:

    $ consul-imex copy -s http://localhost:8500 -c 4874874a-2a3s-7892-123e-597a4e1v87e1 -t http://anotherhost:8500 --target-server-token 6242c15a-9w4x-2318-61a2-8as8c47317 /my/prefix /my/prefix
    93 keys are fetched.
    93 keys are stored. (25 new directories are created.)
    Operation completed.

Copy all keys to another server:

    $ consul-imex copy -s http://localhost:8500 -t http://anotherhost:8500
    492 keys are fetched.
    492 keys are stored. (108 new directories are created.)
    Operation completed.

## Notices for Docker Usage

### Input/Output File Location

To use `import` and `export` commands with docker, the input/output files must be accessible by the container. The default working directory of the image is `/consul-imex` and input/output files are placed under this directory by default.

#### Examples for `export` command:

**Example 1:** Mount a host directory to the container for `export` operation, then the container will create `my-data.json` file in the host directory.

    $ docker run -it -v `pwd`:/consul-imex sozpinar/consul-imex export -u 192.168.1.20:8500 -p /foo/bar my-data.json
    93 keys are fetched.

**Example 2:** Copy the output file to your working directory after `export` operation.

    $ docker run -it sozpinar/consul-imex export -u 192.168.1.20:8500 -p /foo/bar my-data.json
    93 keys are fetched.
    $ docker cp `docker ps -ql`:/consul-imex/my-data.json .

#### Examples for `import` command:

**Example 1:** Mount a host directory to the container for `import` operation, then the container will read `my-data.json` file from the host directory.

    $ docker run -it -v `pwd`:/consul-imex sozpinar/consul-imex import -u 192.168.1.20:8500 -p /new/prefix my-data.json
    93 keys are stored. (25 new directories are created.)

**Example 2:** Mount a file to the container and use it for `import` operation. This method does not require the input file to be placed in the default working directory.

    $ docker run -it -v `pwd`/my-data.json:/my-data.json sozpinar/consul-imex import -u 192.168.1.20:8500 -p /new/prefix -v /my-data.json
    93 keys are stored. (25 new directories are created.)

### Network Configuration

If your Consul service is in a private network or does not have a public URL, you may have to set up a custom network configuration for the docker container.

#### Example

    docker run -it --net=host sozpinar/consul-imex copy -s http://localhost:8500 -t http://anotherhost:8500

If the default docker network type is `bridge` then the running container does not recognize 'localhost'. So we simply add `--net=host` argument to make the container to use the network of the host machine.

## Known Issues

### Directories with values

Consul key/value storage allows a directory to have a value like an ordinary key.
If a directory has a value, Consul Imex will ignore the value or the sub-keys;
this depends how the keys are ordered.


text:
class BaseContainer(object):
    def __str__(self):
        raise NotImplementedError('Implemented by yourself')

    def __setitem__(self, key, value):
        raise NotImplementedError('Implemented by yourself')

    def __getitem__(self, key):
        raise NotImplementedError('Implemented by yourself')

    def __delitem__(self, key):
        raise NotImplementedError('Implemented by yourself')

    def __len__(self):
        raise NotImplementedError('Implemented by yourself')

    def __contains__(self, k):
        raise NotImplementedError('Implemented by yourself')

    def clear(self):
        raise NotImplementedError('Implemented by yourself')

    def get(self, k, d=None):
        raise NotImplementedError('Implemented by yourself')

    def setdefault(self, key, default=None):
        raise NotImplementedError('Implemented by yourself')

    def raw_data(self):
        """
        获取原始数据
        :return:
        :rtype:
        """
        raise NotImplementedError('Implemented by yourself')


text:
require 'rdialogs'

d = RDialogs.new

# Simple yes/no box.
bacon = d.yesno_box('Do you like bacon?')

puts bacon ? 'You like bacon.' : 'Really?'

# Yes/No box with default value and some optional parameters.
hamlet = d.yesno_box('To be or not to be?', title: 'This is title.', default_no: true)

if hamlet
  puts 'To be.'
else
  puts 'Not to be :('
end


text:
<?php

namespace MarvinLabs\SetupWizard\Steps;

use Exception;

class DatabaseStep extends BaseStep
{
    public function __construct($id)
    {
        parent::__construct($id);
    }

    public function apply($formData)
    {
        try {
            if ($this->isChecked($formData, 'refresh_db')) {
                \Artisan::call('migrate:refresh');
            } else {
                \Artisan::call('migrate');
            }

            if ($this->isChecked($formData, 'enable_seeding')) {
                \Artisan::call('db:seed');
            }
        } catch (Exception $e) {
            $this->addError('exception', $e->getMessage());

            return false;
        }

        return true;
    }

    public function undo()
    {
        try {
            \Artisan::call('migrate:rollback');
        } catch (Exception $e) {
            $this->addError('exception', $e->getMessage());

            return false;
        }

        return true;
    }

    protected function isChecked($formData, $optionName) {
        return isset($formData[$optionName]) && $formData[$optionName] == 1;
    }
}


text:
<?php

namespace CMS\Controller\Administration;

use Symfony\Component\HttpFoundation\Request;

interface AdminControllerInterface
{
public function indexAction();
public function addAction(Request $request);
public function editAction(Request $request);
public function deleteAction(Request $request);
}


text:
namespace llvm {
  class ARMSubtarget;
  class ARMBaseInstrInfo;

struct ARMRegisterInfo : public ARMBaseRegisterInfo {
  virtual void anchor();
public:
  ARMRegisterInfo(const ARMBaseInstrInfo &tii, const ARMSubtarget &STI);
};

} // end namespace llvm

#endif


text:
RP_MySQLConfig = {} -- Ignore this line
--[[
Welcome to MySQL for DarkRP!
In this file you can find a manual for MySQL configuration and the MySQL config settings.
 ]]

RP_MySQLConfig.EnableMySQL = false -- Set to true if you want to use an external MySQL database, false if you want to use the built in SQLite database (garrysmod/sv.db) of Garry's mod.
RP_MySQLConfig.Host = "127.0.0.1" -- This is the IP address of the MySQL host. Make sure the IP address is correct and in quotation marks (" ")
RP_MySQLConfig.Username = "user" -- This is the username to log in on the MySQL server.
                                -- contact the owner of the server about the username and password. Make sure it's in quotation marks! (" ")
RP_MySQLConfig.Password = "password" -- This is the Password to log in on the MySQL server,
                                    -- Everyone who has access to FTP on the server can read this password.
                                    -- Make sure you know who to trust. Make sure it's in quotation marks (" ")
RP_MySQLConfig.Database_name = "DarkRP" -- This is the name of the Database on the MySQL server. Contact the MySQL server host to find out what this is
RP_MySQLConfig.Database_port = 3306 -- This is the port of the MySQL server. Again, contact the MySQL server host if you don't know this.
RP_MySQLConfig.Preferred_module = "tmysql4" -- Preferred module, case sensitive, must be either "mysqloo" or "tmysql4". Only applies when both are installed.
RP_MySQLConfig.MultiStatements = false -- Only available in tmysql4: allow multiple SQL statements per query. Has no effect if no scripts use it.

--[[
MANUAL!
HOW TO USE MySQL FOR DARKRP!
Download tmysql4 and read the guide here:
https://facepunch.com/showthread.php?t=1442438

WHAT TO DO IF YOU CAN'T GET IT TO WORK!
    - There are always errors on the server, try if you can see those (with HLDS/server logs)
    - the same errors are also in the logs if you can't find the errors on the server.
        the logs are at garrysmod/data/DarkRP_logs/ on the SERVER!
        The MySQL lines in the log always precede with "MySQL Error:" (without the quotation marks)
    - make sure the settings in this file (mysql.lua) are correct
    - make sure the MySQL server is accessible from the servers IP
]]


text:
.FilterView > .time-filters {
  white-space: nowrap;
  padding-bottom: 8px;
  font-size: 15px;
}

@media (--narrow-window) {
  .FilterView > .time-filters > select {
    padding-left: 0;
    padding-right: 0;
    text-align: center;
  }
}

@-moz-document url-prefix() {
  .FilterView > .time-filters > select {
    width: 65px;
  }
}

.FilterView > .time-filters > label {
  color: var(--light-blue);
  font-weight: var(--font-weight);
  margin-bottom: 3px;
}

.FilterView > .mode-filters {
  display: inline-block;
}

.FilterView > .mode-filters > button {
  box-shadow: none;
  background-color: var(--green);
  color: var(--button-green);
  padding: 0;
  width: 44px;
  height: 44px;
  font-size: 28px;
  transition-property: background;
  transition-duration: 0.1s;
  text-shadow: none;
  position: relative;
}

.mode-filters i {
  font-size: 16px;
  position: absolute;
  top: 23px;
  left: 27px;
  color: var(--lightgreen);
  text-shadow: 0px 1px 3px rgba(75, 106, 32, 0.4);
  visibility: hidden;
}

.mode-filters > button.active.btn-default {
  background-color: var(--green);
  color: var(--button-green);

  text-shadow: 0px 1px 0px rgba(255, 255, 255, 0.3);
}

.mode-filters > button:hover.btn-default,
.mode-filters > button:focus.btn-default {
  background-color: var(--mgreen);
  color: var(--button-green);

  text-shadow: 0px 1px 0px rgba(255, 255, 255, 0.3);
}

.mode-filters > button.active > i {
  visibility: visible;
}

.submit {
  margin-left: 4px;
  width: 84px;
  height: 44px;
  font-size: 20px;
  border: none;
}

.show-settings {
  width: 100%;
  margin-top: 10px;
  height: 44px;
}

.hide-settings {
  width: 100%;
  margin-top: 10px;
  height: 44px;
}

.settings-form .icon-bike {
  margin-top: 5px;
  color: var(--lightest-blue);
  font-size: 32px;
  display: inline-block;
}

.measurements {
  display: inline-block;
  color: var(--lightest-blue);
  font-weight: bold;
  font-size: 14px;
}


text:
title: Wahlpflichtmodul
modulverantwortlich: all
modulniveau: bachelor
kuerzel: WPF
untertitel:
studiensemester: 5
kategorie:
sprache: deutsch
kreditpunkte: 5
voraussetzungenNachPruefungsordnung: keine
empfohleneVoraussetzungen:
published: true
infourl:
layout: modulbeschreibung
typ: pm
veranstaltungsform:
infourl:
studienleistungen:
  Einzelleistung:
    art: abhängig vom jeweiligen WPF
    erstpruefer: all
    zweitpruefer: all
---

## Arbeitsaufwand
150 Stunden

## Angestrebte Lernergebnisse
Fachliche Vertiefung oder Verbreiterung, nach persönlichem Interesse. Es kann eines der Module aus dem Katalog aller Module der Informatik Bachelorstudiengänge gewählt werden. Auch Pflichtmodule anderer Informatik Studiengänge am Campus können als Wahlpflichtmodule in der Medieninformatik belegt werden.


text:
local clientChatModules = script.Parent.Parent
local ChatSettings = require(clientChatModules:WaitForChild("ChatSettings"))
local ChatConstants = require(clientChatModules:WaitForChild("ChatConstants"))
local util = require(script.Parent:WaitForChild("Util"))

function CreateMeCommandMessageLabel(messageData, channelName)
	local message = messageData.Message
	local extraData = messageData.ExtraData or {}
	local useFont = extraData.Font or Enum.Font.SourceSansItalic
	local useTextSize = extraData.TextSize or ChatSettings.ChatWindowTextSize
	local useChatColor = Color3.new(1, 1, 1)
	local useChannelColor = extraData.ChannelColor or useChatColor
	local numNeededSpaces = 0

	local BaseFrame, BaseMessage = util:CreateBaseMessage("", useFont, useTextSize, useChatColor)
	local ChannelButton = nil

	if channelName ~= messageData.OriginalChannel then
		local formatChannelName = string.format("{%s}", messageData.OriginalChannel)
		ChannelButton = util:AddChannelButtonToBaseMessage(BaseMessage, useChannelColor, formatChannelName, messageData.OriginalChannel)
		numNeededSpaces = util:GetNumberOfSpaces(formatChannelName, useFont, useTextSize) + 1
	end

	local function UpdateTextFunction(messageObject)
		if messageData.IsFiltered then
			BaseMessage.Text = string.rep(" ", numNeededSpaces) .. messageObject.FromSpeaker .. " " .. string.sub(messageObject.Message, 5)
		else
			local messageLength = string.len(messageObject.FromSpeaker) + messageObject.MessageLength - 4
			BaseMessage.Text = string.rep(" ", numNeededSpaces) .. string.rep("_", messageLength)
		end
	end

	UpdateTextFunction(messageData)

	local function GetHeightFunction(xSize)
		return util:GetMessageHeight(BaseMessage, BaseFrame, xSize)
	end

	local FadeParmaters = {}
	FadeParmaters[BaseMessage] = {
		TextTransparency = {FadedIn = 0, FadedOut = 1},
		TextStrokeTransparency = {FadedIn = 0.75, FadedOut = 1}
	}

	if ChannelButton then
		FadeParmaters[ChannelButton] = {
			TextTransparency = {FadedIn = 0, FadedOut = 1},
			TextStrokeTransparency = {FadedIn = 0.75, FadedOut = 1}
		}
	end

	local FadeInFunction, FadeOutFunction, UpdateAnimFunction = util:CreateFadeFunctions(FadeParmaters)

	return {
		[util.KEY_BASE_FRAME] = BaseFrame,
		[util.KEY_BASE_MESSAGE] = BaseMessage,
		[util.KEY_UPDATE_TEXT_FUNC] = UpdateTextFunction,
		[util.KEY_GET_HEIGHT] = GetHeightFunction,
		[util.KEY_FADE_IN] = FadeInFunction,
		[util.KEY_FADE_OUT] = FadeOutFunction,
		[util.KEY_UPDATE_ANIMATION] = UpdateAnimFunction
	}
end

return {
	[util.KEY_MESSAGE_TYPE] = ChatConstants.MessageTypeMeCommand,
	[util.KEY_CREATOR_FUNCTION] = CreateMeCommandMessageLabel
}


text:
package br.edu.utfpr.recominer.batch.dataset;

import br.edu.utfpr.recominer.core.model.Commit;
import br.edu.utfpr.recominer.core.model.Project;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.inject.Named;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Rodrigo T. Kuroda <rodrigokuroda at alunos.utfpr.edu.br>
 */
@Named
public class FileSystemDatasetOutput implements DatasetOutput {

    private final Logger log = LoggerFactory.getLogger(FileSystemDatasetOutput.class);

    @Override
    public void write(File workingDir, Project project, Commit commit, Dataset dataset, String datasetName) {

        if (!workingDir.exists()) {
            throw new IllegalArgumentException("Working directory " + workingDir.getAbsolutePath() + " does not exist.");
        }
        // Structure of folder: PROJECT/COMMIT/FILE/COCHANGE/train.csv
        //                      PROJECT/COMMIT/FILE/test.csv
        // Using toString() method to force error when attribute is null.
        StringBuilder path = new StringBuilder();
        path.append(project.getProjectName().toString())
                .append("/").append(commit.getId().toString())
                .append("/").append(dataset.getFile().getId().toString());

        // Test dataset does not have a "cochange"
        if (dataset.getCochange() != null) {
            path.append("/").append(dataset.getCochange().getId().toString());
        }

        File dir = new File(workingDir, path.toString());

        if (!dir.exists()) {
            dir.mkdirs();
        }

        File datasetFile = new File(dir, datasetName + ".csv");

        try (FileWriter fw = new FileWriter(datasetFile)) {
            log.info("Writting dataset file to {}.", datasetFile.getAbsolutePath());
            fw.append(dataset.toString());
            fw.flush();
        } catch (IOException ex) {
            log.error("Error to write dataset to file system.", ex);
        }
    }

}


text:
<?php

// No direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.controllerform');

/**
 * @package     Joomla.Administrator
 * @subpackage  com_content
 * @since       1.6
 */
class ContentControllerArticle extends JControllerForm
{
	/**
	 * Class constructor.
	 *
	 * @param   array  $config  A named array of configuration variables.
	 *
	 * @since	1.6
	 */
	function __construct($config = array())
	{
		// An article edit form can come from the articles or featured view.
		// Adjust the redirect view on the value of 'return' in the request.
		if (JRequest::getCmd('return') == 'featured')
		{
			$this->view_list = 'featured';
			$this->view_item = 'article&return=featured';
		}

		parent::__construct($config);
	}

	/**
	 * Method override to check if you can add a new record.
	 *
	 * @param   array  $data  An array of input data.
	 *
	 * @return  boolean
	 *
	 * @since   1.6
	 */
	protected function allowAdd($data = array())
	{
		// Initialise variables.
		$user = JFactory::getUser();
		$categoryId = JArrayHelper::getValue($data, 'catid', JRequest::getInt('filter_category_id'), 'int');
		$allow = null;

		if ($categoryId)
		{
			// If the category has been passed in the data or URL check it.
			$allow = $user->authorise('core.create', 'com_content.category.' . $categoryId);
		}

		if ($allow === null)
		{
			// In the absense of better information, revert to the component permissions.
			return parent::allowAdd();
		}
		else
		{
			return $allow;
		}
	}

	/**
	 * Method override to check if you can edit an existing record.
	 *
	 * @param   array   $data  An array of input data.
	 * @param   string  $key   The name of the key for the primary key.
	 *
	 * @return  boolean
	 *
	 * @since   1.6
	 */
	protected function allowEdit($data = array(), $key = 'id')
	{
		// Initialise variables.
		$recordId = (int) isset($data[$key]) ? $data[$key] : 0;
		$user = JFactory::getUser();
		$userId = $user->get('id');

		// Check general edit permission first.
		if ($user->authorise('core.edit', 'com_content.article.' . $recordId))
		{
			return true;
		}

		// Fallback on edit.own.
		// First test if the permission is available.
		if ($user->authorise('core.edit.own', 'com_content.article.' . $recordId))
		{
			// Now test the owner is the user.
			$ownerId = (int) isset($data['created_by']) ? $data['created_by'] : 0;
			if (empty($ownerId) && $recordId)
			{
				// Need to do a lookup from the model.
				$record = $this->getModel()->getItem($recordId);

				if (empty($record))
				{
					return false;
				}

				$ownerId = $record->created_by;
			}

			// If the owner matches 'me' then do the test.
			if ($ownerId == $userId)
			{
				return true;
			}
		}

		// Since there is no asset tracking, revert to the component permissions.
		return parent::allowEdit($data, $key);
	}

	/**
	 * Method to run batch operations.
	 *
	 * @param   object  $model  The model.
	 *
	 * @return  boolean	 True if successful, false otherwise and internal error is set.
	 *
	 * @since   1.6
	 */
	public function batch($model = null)
	{
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		// Set the model
		$model = $this->getModel('Article', '', array());

		// Preset the redirect
		$this->setRedirect(JRoute::_('index.php?option=com_content&view=articles' . $this->getRedirectToListAppend(), false));

		return parent::batch($model);
	}
}


text:
/// @file xed-operand-action-enum.h

// This file was automatically generated.
// Do not edit this file.

#if !defined(_XED_OPERAND_ACTION_ENUM_H_)
# define _XED_OPERAND_ACTION_ENUM_H_
#include "xed-common-hdrs.h"
typedef enum {
  XED_OPERAND_ACTION_INVALID,
  XED_OPERAND_ACTION_RW, ///< Read and written (must write)
  XED_OPERAND_ACTION_R, ///< Read-only
  XED_OPERAND_ACTION_W, ///< Write-only (must write)
  XED_OPERAND_ACTION_RCW, ///< Read and conditionlly written (may write)
  XED_OPERAND_ACTION_CW, ///< Conditionlly written (may write)
  XED_OPERAND_ACTION_CRW, ///< Conditionlly read, always written (must write)
  XED_OPERAND_ACTION_CR, ///< Conditional read
  XED_OPERAND_ACTION_LAST
} xed_operand_action_enum_t;

/// This converts strings to #xed_operand_action_enum_t types.
/// @param s A C-string.
/// @return #xed_operand_action_enum_t
/// @ingroup ENUM
XED_DLL_EXPORT xed_operand_action_enum_t str2xed_operand_action_enum_t(const char* s);
/// This converts strings to #xed_operand_action_enum_t types.
/// @param p An enumeration element of type xed_operand_action_enum_t.
/// @return string
/// @ingroup ENUM
XED_DLL_EXPORT const char* xed_operand_action_enum_t2str(const xed_operand_action_enum_t p);

/// Returns the last element of the enumeration
/// @return xed_operand_action_enum_t The last element of the enumeration.
/// @ingroup ENUM
XED_DLL_EXPORT xed_operand_action_enum_t xed_operand_action_enum_t_last(void);
#endif


text:
"""Test cases for anyconfig.parser.parse_list.
"""
import anyconfig.parser as TT

from . import common

class TestCase(common.TestCase):
    kind = 'list'
    pattern = '*.*'

    def test_parse_list(self):
        for data in self.each_data():
            self.assertEqual(
                TT.parse_list(data.inp, **data.opts),
                data.exp,
                data
            )

# vim:sw=4:ts=4:et:


text:
package org.seasar.doma.jdbc.type;

import java.sql.*;

/** A JDBC type for {@link Types#FLOAT} and {@link Float}. */
public class FloatType extends AbstractJdbcType<Float> {

  public FloatType() {
    super(Types.FLOAT);
  }

  @Override
  public Float doGetValue(ResultSet resultSet, int index) throws SQLException {
    return resultSet.getFloat(index);
  }

  @Override
  protected void doSetValue(PreparedStatement preparedStatement, int index, Float value)
      throws SQLException {
    preparedStatement.setDouble(index, value);
  }

  @Override
  protected Float doGetValue(CallableStatement callableStatement, int index) throws SQLException {
    return callableStatement.getFloat(index);
  }

  @Override
  protected String doConvertToLogFormat(Float value) {
    return String.valueOf(value);
  }
}


text:
namespace cc {
namespace {
int kSendTimingIntervalMS = 200;
}

FrameTimingTracker::CompositeTimingEvent::CompositeTimingEvent(
    int _frame_id,
    base::TimeTicks _timestamp)
    : frame_id(_frame_id), timestamp(_timestamp) {
}

FrameTimingTracker::CompositeTimingEvent::~CompositeTimingEvent() {
}

FrameTimingTracker::MainFrameTimingEvent::MainFrameTimingEvent(
    int frame_id,
    base::TimeTicks timestamp,
    base::TimeTicks end_time)
    : frame_id(frame_id), timestamp(timestamp), end_time(end_time) {
}

FrameTimingTracker::MainFrameTimingEvent::~MainFrameTimingEvent() {
}

// static
scoped_ptr<FrameTimingTracker> FrameTimingTracker::Create(
    LayerTreeHostImpl* layer_tree_host_impl) {
  return make_scoped_ptr(new FrameTimingTracker(layer_tree_host_impl));
}

FrameTimingTracker::FrameTimingTracker(LayerTreeHostImpl* layer_tree_host_impl)
    : layer_tree_host_impl_(layer_tree_host_impl),
      post_events_notifier_(
          layer_tree_host_impl_->GetTaskRunner(),
          base::Bind(&FrameTimingTracker::PostEvents, base::Unretained(this)),
          base::TimeDelta::FromMilliseconds(kSendTimingIntervalMS)) {}

FrameTimingTracker::~FrameTimingTracker() {
}

void FrameTimingTracker::SaveTimeStamps(
    base::TimeTicks timestamp,
    const std::vector<FrameAndRectIds>& frame_ids) {
  if (!composite_events_)
    composite_events_.reset(new CompositeTimingSet);
  for (const auto& pair : frame_ids) {
    (*composite_events_)[pair.second].push_back(
        CompositeTimingEvent(pair.first, timestamp));
  }
  if (!post_events_notifier_.HasPendingNotification())
    post_events_notifier_.Schedule();
}

void FrameTimingTracker::SaveMainFrameTimeStamps(
    const std::vector<int64_t>& request_ids,
    base::TimeTicks main_frame_time,
    base::TimeTicks end_time,
    int source_frame_number) {
  if (!main_frame_events_)
    main_frame_events_.reset(new MainFrameTimingSet);
  for (const auto& request : request_ids) {
    std::vector<MainFrameTimingEvent>& events = (*main_frame_events_)[request];
    events.push_back(
        MainFrameTimingEvent(source_frame_number, main_frame_time, end_time));
  }
  if (!post_events_notifier_.HasPendingNotification())
    post_events_notifier_.Schedule();
}

scoped_ptr<FrameTimingTracker::CompositeTimingSet>
FrameTimingTracker::GroupCompositeCountsByRectId() {
  if (!composite_events_)
    return make_scoped_ptr(new CompositeTimingSet);
  for (auto& infos : *composite_events_) {
    std::sort(
        infos.second.begin(), infos.second.end(),
        [](const CompositeTimingEvent& lhs, const CompositeTimingEvent& rhs) {
          return lhs.timestamp < rhs.timestamp;
        });
  }
  return std::move(composite_events_);
}

scoped_ptr<FrameTimingTracker::MainFrameTimingSet>
FrameTimingTracker::GroupMainFrameCountsByRectId() {
  if (!main_frame_events_)
    return make_scoped_ptr(new MainFrameTimingSet);
  for (auto& infos : *main_frame_events_) {
    std::sort(
        infos.second.begin(), infos.second.end(),
        [](const MainFrameTimingEvent& lhs, const MainFrameTimingEvent& rhs) {
          return lhs.timestamp < rhs.timestamp;
        });
  }
  return std::move(main_frame_events_);
}

void FrameTimingTracker::PostEvents() {
  layer_tree_host_impl_->PostFrameTimingEvents(GroupCompositeCountsByRectId(),
                                               GroupMainFrameCountsByRectId());
}

}  // namespace cc


text:
module VirtualMonkey
  module Runner
    class ELB
      include VirtualMonkey::Mixin::DeploymentBase
      include VirtualMonkey::Mixin::ELB

      def initialize(*args)
        super(*args)
        raise "FATAL: ELBRunner must run on a single-cloud AWS deployment" unless @deployment.cloud_id
        endpoint_url = ELBS[@deployment.cloud_id][:endpoint]
        puts "USING EP: #{endpoint_url}"
        @elb = RightAws::ElbInterface.new(AWS_ID, AWS_KEY, { :endpoint_url => endpoint_url } )
        @elb_name = "#{ELB_PREFIX}-#{resource_id(@deployment)}"
      end
    end
  end
end


text:
function logger = detachfiles(logger, files)
%DETACHFILES Detachs the logger from some added files
%
% $ Syntax $
%   - logger = detachfiles(logger, file)
%   - logger = detachfiles(logger, files)
%
% $ Argument $
%   - logger:       the logger to be processed
%   - file:         the filename of the file to be detached
%   - files:        the cell array of filenames to be detached
%
% $ Description $
%   - logger = detachfiles(logger, file) detach a file from the logger
%     list.
%
%   - logger = detachfiles(logger, files) detach a set of filenames from
%     the logger list.
%
% $ History $
%   - Created by Dahua Lin, on Aug 12nd, 2006
%

if ischar(files)

    [tf, idx] = isattached(logger, files);
    if ~tf
        error('sltoolbox:invalidarg', ...
            'The file %s has not been added to the file list', fp);
    end

    fclose(files(idx).fid);

elseif iscell(files)

    n = numel(files);
    for i = 1 : n
        logger = detachfiles(logger, files{i});
    end

else
    error('sltoolbox:invalidarg', ...
        'The files should be either a filename or a cell array of filenames');
end


text:
test
====

my test repository


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Berp.BerpGrammar;
using CommandLine;
using CommandLine.Text;

namespace Berp
{
    public class Options
    {
        [Option('t', "template", Required = true, HelpText = "Template (.razor) file for generation.")]
        public string Template { get; set; }

        [Option('g', "grammar", Required = true, HelpText = "Grammar (.berp) file for generation.")]
        public string Grammar { get; set; }
        [Option('o', "output", Required = true, HelpText = "Generated parser class file.")]
        public string OutputFile { get; set; }
        [Option('d', "details", HelpText = "Print details during execution.")]
        public bool DiagnosticsMode { get; set; }
        [Option("settings", Required = false, HelpText = "Extends/overrides settings in grammar file, use 'key1=value1,key2=value2,key3=!file-path-to-load-setting-from' format")]
        public string SettingsOverride { get; set; }
        [Option("noBOM", Required = false, HelpText = "Does not include UTF-8 BOM in the generated file")]
        public bool NoBom { get; set; }

        public HelpText GetHeader()
        {
            var help = new HelpText
            {
                Heading = HeadingInfo.Default,
                Copyright = CopyrightInfo.Default,
                AdditionalNewLineAfterOption = false,
                AddDashesToOption = true
            };
            help.AddPreOptionsLine(string.Empty);

            help.AddPreOptionsLine("Licensed under the Apache License, Version 2.0 (the \"License\")");
            help.AddPreOptionsLine("    http://www.apache.org/licenses/LICENSE-2.0");
            return help;
        }
    }

    class Program
    {
        static int Main(string[] args)
        {
            var commandLineParseResult = CommandLine.Parser.Default.ParseArguments<Options>(args);

            int result = 2;

            commandLineParseResult.WithParsed<Options>(options =>
            {
                try
                {
                    GenerateParserInternal(options);
                    result = 0;
                }
                catch (Exception thrownEx)
                {
                    Console.WriteLine();
                    Console.WriteLine("Generation failed.");
                    var ex = thrownEx;
                    while (ex != null)
                    {
                        Console.WriteLine(ex.Message);
                        ex = ex.InnerException;
                    }

                    if (options.DiagnosticsMode)
                    {
                        Console.WriteLine(thrownEx);
                    }

                    result = 1;
                }
            });

            return result;
        }

        private static void GenerateParserInternal(Options options)
        {
            Console.WriteLine(options.GetHeader());
            Console.WriteLine();
            Console.WriteLine("Generating parser for grammar '{0}' using template '{1}'.", Path.GetFileName(options.Grammar), Path.GetFileName(options.Template));

            Console.WriteLine("Loading grammar...");
            var grammarDefinition = File.ReadAllText(options.Grammar);
            var parser = new BerpGrammar.Parser();
            var ruleSet = parser.Parse(new TokenScanner(new StringReader(grammarDefinition)));

            if (!string.IsNullOrWhiteSpace(options.SettingsOverride))
            {
                var overrides = options.SettingsOverride.Split(',');
                foreach (var settingSpec in overrides)
                {
                    var parts = settingSpec.Split('=');
                    var settingValue = parts[1].Trim();
                    if (settingValue.StartsWith("!"))
                    {
                        settingValue = File.ReadAllText(settingValue.TrimStart('!'));
                    }
                    ruleSet.Settings[parts[0].Trim()] = settingValue;
                }
            }

            int tokenCount = ruleSet.Count(r => r is TokenRule);
            Console.WriteLine("The grammar was loaded with {0} tokens and {1} rules.", tokenCount, ruleSet.Count() - tokenCount);

            if (options.DiagnosticsMode)
            {
                Console.WriteLine(ruleSet.ToString(true));
                Console.WriteLine("---------------");
            }

            Console.WriteLine("Calculating parser states...");
            var states = StateCalculator.CalculateStates(ruleSet);

            Console.WriteLine("{0} states calculated for the parser.", states.Count);

            if (options.DiagnosticsMode)
            {
                foreach (var state in states.Values)
                {
                    PrintStateTransitions(state);
                    PrintStateBranches(state.Branches, state.Id);
                }
            }

            Console.WriteLine("Generating parser class...");
            var generator = new Generator(ruleSet.Settings);
            generator.Generate(options.Template, ruleSet, states, options.OutputFile, options.NoBom);
        }
        private static void PrintStateTransitions(State state)
        {
            Console.WriteLine("{0}: {1}", state.Id, state.Comment);
            foreach (var transition in state.Transitions)
            {
                Console.WriteLine("    {0} -> {1}", transition.TokenType, transition.TargetState);
            }
        }

        private static void PrintStateBranches(List<Branch> branches, int state)
        {
//            Console.WriteLine("{0}:", state);
            Console.WriteLine();
            foreach (var branch in branches.OrderBy(b => b.TokenType))
            {
                Console.WriteLine("    {0}", branch);
                Console.WriteLine("    \t{0}", branch.GetProductionsText());
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

<TITLE>Accelerating the new SCIARA-fv3 numerical model by different GPGPU strategies</TITLE>
<META NAME="author" CONTENT="Davide Spataro">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=utf-8">
<LINK REL="Start" HREF="index.html">
<LINK REL="Contents" HREF="toc.html">
<LINK REL="Prev" HREF="Memoryclassification.html">
<LINK REL="Next" HREF="Busbasednetworks.html">
<link rel="stylesheet" href="github-pandoc.css">
<link rel="stylesheet" href="http://cdn.jsdelivr.net/highlight.js/9.1.0/styles/default.min.css">

Contents
Previous
Next

Network Topologies

An important role is played, as seen before, by the interconnection
 network because provide mechanisms for data transfer between processing
 nodes. Typically they consist of n inputs and m
 outputs and are built in by switches and links (set of wires or fibers
 capable of carrying information
6).

 [fig:starMesh]

A first classification can be done considering only if the nodes are
 connected directly to each others or not. In the first case the entire
 network consist of point-to-point links and they are called
 static or direct networks. On
 the other hand when the nodes are connected to each others using
 switches we talk about indirect networks.
 Because communication is an important task in parallel computing, the
 way the nodes are connected to each other is important and can
 influence the overall performance of the system that is determined by
 the capabilities of the network access devices, the level of control or
 fault tolerance desired, and the cost associated with cabling or
 telecommunications circuits. Networks topologies try to trade off cost
 and scalability with performance

Contents
Previous
Next


text:
<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://jboss.org/schema/arquillian"
  xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

  <container qualifier="jboss" default="true">
    <configuration>
      <property name="jbossHome">${env.JBOSS_HOME}</property>
    </configuration>
  </container>

</arquillian>


text:
package org.docksidestage.compatible10x.dbflute.exbhv.pmbean;

import org.docksidestage.compatible10x.dbflute.bsbhv.pmbean.BsPmCommentOrderByIfPmb;

/**
 *
 * The typed parameter-bean of PmCommentOrderByIf. (typed to list, entity)

 * This is related to "whitebox:pmcomment:selectPmCommentOrderByIf" on MemberBhv.

 *
 *

 * You can implement your original methods here.
 * This class remains when re-generating.
 *

 * @author DBFlute(AutoGenerator)
 */
public class PmCommentOrderByIfPmb extends BsPmCommentOrderByIfPmb {
}


text:
using System;
using System.Reflection;
using System.Threading;

namespace Es.Upd
{
    public static class Program
    {
        internal static string _id;

        public static void Main(string[] args)
        {
            // internal:
            //  curl http://upd.es/upd/install?key=key&name=name&version=version[&label=label]"
            //    e.g. curl http://upd.es/upd/install?key=ASDF&install=MyServer&version=v1.0.2-f1p1-2" // no label
            //    e.g. curl http://upd.es/upd/install?key=ASDF&install=MyServer&version=v1.0.2-p1&label=lime" // one label
            //    e.g. curl http://upd.es/upd/install?key=ASDF&install=MyServer&version=v1.0.2-p1&label=lime,p1.lime" // two labels
            //  curl http://upd.es/upd/enable?key=key&name=name&version=version" // turn on
            //  curl http://upd.es/upd/disable?key=key&nane=name&version=version" // turn off
            //  curl http://upd.es/upd/default?key=key&name=name&version=version" // assign as default (for locate w/o label)
            //  curl http://upd.es/upd/addlabel?key=key&name=name&verison=version&label=label" // set label to point to this version
            //  curl http://upd.es/upd/rmlabel?key=key&name=name&label=label" // remove label
            //  curl http://upd.es/upd/ls?key=key[&name=name]" // list all or for given name (include # times located bucketed by days, hours?)
            //   -> { all installed packages, enabled|disable, labels pointing to this version ('default' is a special label) }
            //   -> { versions installed for named package, enabled|disable, labels pointing to this version ('default' is a special label) }
            //  curl http://upd.es/upd/cfg?key=key" // dump config info
            //
            // external:
            //  curl "http://upd.es/upd/locate?name=name"
            //  curl "http://upd.es/upd/locate?name=name&label=label" // only one label can be given here.
            //   -> {
            //        "loc": "http://vz...host/name/",
            //        "sx": signed(expiry in seconds from epoch)
            //      }
            //
            // restrictions
            //  - no labels starting with _ allowed.
            //  - labels and version restricted to /^((?:_v_)?[0-9a-zA-Z\._-]+|_default_)$/

            _id = Assembly.GetExecutingAssembly().GetName().Name;
            Console.WriteLine("{0} {1}", _id, BuildInfo.Version);
            var host = Environment.GetEnvironmentVariable("UPD_HOST") ?? "upd.es";
            var dpohost = Environment.GetEnvironmentVariable("DPO_HOST") ?? "dpo.es";
            var dir = Environment.GetEnvironmentVariable("UPD_DIR") ?? "./upd";
            var key = Environment.GetEnvironmentVariable("UPD_KEY") ?? "ASDF";

            Console.WriteLine($"{_id} server started.");
            var cts = new CancellationTokenSource();
            var updServer = new UpdServer(
                host,
                dir,
                key,
                dpohost,
                s =>
                {
                    Console.WriteLine($"FATAL ERROR: {_id} {s}");
                    Environment.Exit(-1);
                }, s =>
                {
                    Console.WriteLine($"{_id} {s}");
                });

            var updTask = updServer.Run(cts.Token);
            Console.WriteLine("Press Q + ENTER to quit");
            while (Console.Read() != 'q') { }

            cts.Cancel();
            updServer.Stop();
            try
            {
                updTask.Wait();
            }
            catch
            {
                // ingored.
            }

            Console.WriteLine($"{_id} service stopped.");
        }
    }
}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/account_manager/account_manager_util.h"

#include <utility>

#include "ash/components/account_manager/account_manager_factory.h"
#include "chrome/browser/ash/account_manager/account_manager_ui_impl.h"
#include "chrome/browser/ash/net/delay_network_call.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/net/system_network_context_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profiles_state.h"
#include "components/account_manager_core/chromeos/account_manager.h"
#include "components/account_manager_core/chromeos/account_manager_mojo_service.h"
#include "components/account_manager_core/chromeos/account_manager_ui.h"
#include "components/user_manager/user_manager.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"

namespace ash {

bool IsAccountManagerAvailable(const Profile* const profile) {
  // Signin Profile does not have any accounts associated with it,
  // LockScreenAppProfile and LockScreenProfile do not link to the user's
  // cryptohome.
  if (!ProfileHelper::IsRegularProfile(profile))
    return false;

  // Account Manager is unavailable on Guest (Incognito) Sessions.
  if (profile->IsGuestSession() || profile->IsOffTheRecord())
    return false;

  // In Web kiosk mode, we should not enable account manager since we use robot
  // accounts.
  if (user_manager::UserManager::IsInitialized() &&
      user_manager::UserManager::Get()->IsLoggedInAsWebKioskApp()) {
    return false;
  }

  // Account Manager is unavailable on Managed Guest Sessions / Public Sessions.
  if (profiles::IsPublicSession())
    return false;

  // Available in all other cases.
  return true;
}

void InitializeAccountManager(const base::FilePath& cryptohome_root_dir,
                              base::OnceClosure initialization_callback) {
  account_manager::AccountManager* account_manager =
      g_browser_process->platform_part()
          ->GetAccountManagerFactory()
          ->GetAccountManager(/*profile_path=*/cryptohome_root_dir.value());

  account_manager->Initialize(
      cryptohome_root_dir,
      g_browser_process->system_network_context_manager()
          ->GetSharedURLLoaderFactory(),
      base::BindRepeating(&DelayNetworkCall,
                          base::Milliseconds(kDefaultNetworkRetryDelayMS)),
      std::move(initialization_callback));

  crosapi::AccountManagerMojoService* account_manager_mojo_service =
      g_browser_process->platform_part()
          ->GetAccountManagerFactory()
          ->GetAccountManagerMojoService(
              /*profile_path=*/cryptohome_root_dir.value());

  account_manager_mojo_service->SetAccountManagerUI(
      std::make_unique<ash::AccountManagerUIImpl>());
}

}  // namespace ash


text:
#pragma once

#include <aws/sqs/SQS_EXPORTS.h>
#include <aws/core/client/AWSErrorMarshaller.h>

namespace Aws
{
namespace Client
{

class AWS_SQS_API SQSErrorMarshaller : public Client::AWSErrorMarshaller
{
public:
  SQSErrorMarshaller() {}
  virtual ~SQSErrorMarshaller() {}

  virtual Client::AWSError<Client::CoreErrors> FindErrorByName(const char* exceptionName) const;
};

} // namespace SQS
} // namespace Aws


text:
<polymer-element name="noflo-project-inspector" class="modal-content" on-click="{{ close }}">
  <template>

{{ project.name }} settings

      <template if="{{ errorText }}">

{{ errorText }}

      </template>
      <form>
        <template if="{{ !$NOFLO_OFFLINE_MODE }}">

            GitHub repository
            <input type="text" value="{{ repo }}" placeholder="username/my-project" autocapitalize="off" autocorrect="off" required>

        </template>

          Project label
          <input type="text" value="{{ name }}" placeholder="My Cool Project" required>

          Main graph
          <select name="type" value="{{ main }}">
            <template repeat="{{ graph in project.graphs }}">
            <option value="{{ graph.properties.id }}">{{ graph.name }}</option>
            </template>
          </select>

          <button on-click="{{ send }}">Save</button>
          Cancel
          <template if="{{ !$NOFLO_OFFLINE_MODE }}">
            New Repository
          </template>
          <button class="delete" on-click="{{ delete }}">Delete</button>

    </form>
  </template>

</polymer-element>