text:
/* eslint-disable prefer-spread */
/* eslint-disable no-mixed-operators */
/* eslint-disable no-restricted-properties */
/* eslint-disable radix */
/* eslint-disable prefer-destructuring */
/* eslint-disable no-restricted-globals */
/* eslint-disable no-bitwise */
/* eslint-disable no-plusplus */
/* eslint-disable func-names */
(function (root) {
    // A list of regular expressions that match arbitrary IPv4 addresses,
    // for which a number of weird notations exist.
    // Note that an address like 0010.0xa5.1.1 is considered legal.
    const ipv4Part = "(0?\\d+|0x[a-f0-9]+)";
    const ipv4Regexes = {
        fourOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}$`, "i"),
        threeOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}$`, "i"),
        twoOctet: new RegExp(`^${ipv4Part}\\.${ipv4Part}$`, "i"),
        longValue: new RegExp(`^${ipv4Part}$`, "i")
    };

    // Regular Expression for checking Octal numbers
    const octalRegex = new RegExp(`^0[0-7]+$`, "i");
    const hexRegex = new RegExp(`^0x[a-f0-9]+$`, "i");

    const zoneIndex = "%[0-9a-z]{1,}";

    // IPv6-matching regular expressions.
    // For IPv6, the task is simpler: it is enough to match the colon-delimited
    // hexadecimal IPv6 and a transitional variant with dotted-decimal IPv4 at
    // the end.
    const ipv6Part = "(?:[0-9a-f]+::?)+";
    const ipv6Regexes = {
        zoneIndex: new RegExp(zoneIndex, "i"),
        native: new RegExp(`^(::)?(${ipv6Part})?([0-9a-f]+)?(::)?(${zoneIndex})?$`, "i"),
        deprecatedTransitional: new RegExp(`^(?:::)(${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}(${zoneIndex})?)$`, "i"),
        transitional: new RegExp(`^((?:${ipv6Part})|(?:::)(?:${ipv6Part})?)${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}(${zoneIndex})?$`, "i")
    };

    // Expand :: in an IPv6 address or address part consisting of `parts` groups.
    function expandIPv6(string, parts) {
        // More than one '::' means invalid adddress
        if (string.indexOf("::") !== string.lastIndexOf("::")) {
            return null;
        }

        let colonCount = 0;
        let lastColon = -1;
        let zoneId = (string.match(ipv6Regexes.zoneIndex) || [])[0];
        let replacement;
        let
            replacementCount;

        // Remove zone index and save it for later
        if (zoneId) {
            zoneId = zoneId.substring(1);
            string = string.replace(/%.+$/, "");
        }

        // How many parts do we already have?
        while ((lastColon = string.indexOf(":", lastColon + 1)) >= 0) {
            colonCount++;
        }

        // 0::0 is two parts more than ::
        if (string.substr(0, 2) === "::") {
            colonCount--;
        }

        if (string.substr(-2, 2) === "::") {
            colonCount--;
        }

        // The following loop would hang if colonCount > parts
        if (colonCount > parts) {
            return null;
        }

        // replacement = ':' + '0:' * (parts - colonCount)
        replacementCount = parts - colonCount;
        replacement = ":";
        while (replacementCount--) {
            replacement += "0:";
        }

        // Insert the missing zeroes
        string = string.replace("::", replacement);

        // Trim any garbage which may be hanging around if :: was at the edge in
        // the source strin
        if (string[0] === ":") {
            string = string.slice(1);
        }

        if (string[string.length - 1] === ":") {
            string = string.slice(0, -1);
        }

        parts = (function () {
            const ref = string.split(":");
            const results = [];

            for (let i = 0; i < ref.length; i++) {
                results.push(parseInt(ref[i], 16));
            }

            return results;
        }());

        return {
            parts,
            zoneId
        };
    }

    // A generic CIDR (Classless Inter-Domain Routing) RFC1518 range matcher.
    function matchCIDR(first, second, partSize, cidrBits) {
        if (first.length !== second.length) {
            throw new Error("ipaddr: cannot match CIDR for objects with different lengths");
        }

        let part = 0;
        let shift;

        while (cidrBits > 0) {
            shift = partSize - cidrBits;
            if (shift < 0) {
                shift = 0;
            }

            if (first[part] >> shift !== second[part] >> shift) {
                return false;
            }

            cidrBits -= partSize;
            part += 1;
        }

        return true;
    }

    function parseIntAuto(string) {
        // Hexadedimal base 16 (0x#)
        if (hexRegex.test(string)) {
            return parseInt(string, 16);
        }
        // While octal representation is discouraged by ECMAScript 3
        // and forbidden by ECMAScript 5, we silently allow it to
        // work only if the rest of the string has numbers less than 8.
        if (string[0] === "0" && !isNaN(parseInt(string[1], 10))) {
            if (octalRegex.test(string)) {
                return parseInt(string, 8);
            }
            throw new Error(`ipaddr: cannot parse ${string} as octal`);
        }
        // Always include the base 10 radix!
        return parseInt(string, 10);
    }

    function padPart(part, length) {
        while (part.length < length) {
            part = `0${part}`;
        }

        return part;
    }

    const ipaddr = {};

    // An IPv4 address (RFC791).
    ipaddr.IPv4 = (function () {
        // Constructs a new IPv4 address from an array of four octets
        // in network order (MSB first)
        // Verifies the input.
        function IPv4(octets) {
            if (octets.length !== 4) {
                throw new Error("ipaddr: ipv4 octet count should be 4");
            }

            let i;
            let
                octet;

            for (i = 0; i < octets.length; i++) {
                octet = octets[i];
                if (!((octet >= 0 && octet <= 255))) {
                    throw new Error("ipaddr: ipv4 octet should fit in 8 bits");
                }
            }

            this.octets = octets;
        }

        // Special IPv4 address ranges.
        // See also https://en.wikipedia.org/wiki/Reserved_IP_addresses
        IPv4.prototype.SpecialRanges = {
            unspecified: [
                [new IPv4([0, 0, 0, 0]), 8]
            ],
            broadcast: [
                [new IPv4([255, 255, 255, 255]), 32]
            ],
            // RFC3171
            multicast: [
                [new IPv4([224, 0, 0, 0]), 4]
            ],
            // RFC3927
            linkLocal: [
                [new IPv4([169, 254, 0, 0]), 16]
            ],
            // RFC5735
            loopback: [
                [new IPv4([127, 0, 0, 0]), 8]
            ],
            // RFC6598
            carrierGradeNat: [
                [new IPv4([100, 64, 0, 0]), 10]
            ],
            // RFC1918
            private: [
                [new IPv4([10, 0, 0, 0]), 8],
                [new IPv4([172, 16, 0, 0]), 12],
                [new IPv4([192, 168, 0, 0]), 16]
            ],
            // Reserved and testing-only ranges; RFCs 5735, 5737, 2544, 1700
            reserved: [
                [new IPv4([192, 0, 0, 0]), 24],
                [new IPv4([192, 0, 2, 0]), 24],
                [new IPv4([192, 88, 99, 0]), 24],
                [new IPv4([198, 51, 100, 0]), 24],
                [new IPv4([203, 0, 113, 0]), 24],
                [new IPv4([240, 0, 0, 0]), 4]
            ]
        };

        // The 'kind' method exists on both IPv4 and IPv6 classes.
        IPv4.prototype.kind = function () {
            return "ipv4";
        };

        // Checks if this address matches other one within given CIDR range.
        IPv4.prototype.match = function (other, cidrRange) {
            let ref;
            if (cidrRange === undefined) {
                ref = other;
                other = ref[0];
                cidrRange = ref[1];
            }

            if (other.kind() !== "ipv4") {
                throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");
            }

            return matchCIDR(this.octets, other.octets, 8, cidrRange);
        };

        // returns a number of leading ones in IPv4 address, making sure that
        // the rest is a solid sequence of 0's (valid netmask)
        // returns either the CIDR length or null if mask is not valid
        IPv4.prototype.prefixLengthFromSubnetMask = function () {
            let cidr = 0;
            // non-zero encountered stop scanning for zeroes
            let stop = false;
            // number of zeroes in octet
            const zerotable = {
                0: 8,
                128: 7,
                192: 6,
                224: 5,
                240: 4,
                248: 3,
                252: 2,
                254: 1,
                255: 0
            };
            let i;
            let octet;
            let
                zeros;

            for (i = 3; i >= 0; i -= 1) {
                octet = this.octets[i];
                if (octet in zerotable) {
                    zeros = zerotable[octet];
                    if (stop && zeros !== 0) {
                        return null;
                    }

                    if (zeros !== 8) {
                        stop = true;
                    }

                    cidr += zeros;
                } else {
                    return null;
                }
            }

            return 32 - cidr;
        };

        // Checks if the address corresponds to one of the special ranges.
        IPv4.prototype.range = function () {
            return ipaddr.subnetMatch(this, this.SpecialRanges);
        };

        // Returns an array of byte-sized values in network order (MSB first)
        IPv4.prototype.toByteArray = function () {
            return this.octets.slice(0);
        };

        // Converts this IPv4 address to an IPv4-mapped IPv6 address.
        IPv4.prototype.toIPv4MappedAddress = function () {
            return ipaddr.IPv6.parse(`::ffff:${this.toString()}`);
        };

        // Symmetrical method strictly for aligning with the IPv6 methods.
        IPv4.prototype.toNormalizedString = function () {
            return this.toString();
        };

        // Returns the address in convenient, decimal-dotted format.
        IPv4.prototype.toString = function () {
            return this.octets.join(".");
        };

        return IPv4;
    }());

    // A utility function to return broadcast address given the IPv4 interface and prefix length in CIDR notation
    ipaddr.IPv4.broadcastAddressFromCIDR = function (string) {
        try {
            const cidr = this.parseCIDR(string);
            const ipInterfaceOctets = cidr[0].toByteArray();
            const subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
            const octets = [];
            let i = 0;
            while (i < 4) {
                // Broadcast address is bitwise OR between ip interface and inverted mask
                octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);
                i++;
            }

            return new this(octets);
        } catch (e) {
            throw new Error("ipaddr: the address does not have IPv4 CIDR format");
        }
    };

    // Checks if a given string is formatted like IPv4 address.
    ipaddr.IPv4.isIPv4 = function (string) {
        return this.parser(string) !== null;
    };

    // Checks if a given string is a valid IPv4 address.
    ipaddr.IPv4.isValid = function (string) {
        try {
            new this(this.parser(string));
            return true;
        } catch (e) {
            return false;
        }
    };

    // Checks if a given string is a full four-part IPv4 Address.
    ipaddr.IPv4.isValidFourPartDecimal = function (string) {
        if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) {
            return true;
        }
        return false;
    };

    // A utility function to return network address given the IPv4 interface and prefix length in CIDR notation
    ipaddr.IPv4.networkAddressFromCIDR = function (string) {
        let cidr;
        let i;
        let ipInterfaceOctets;
        let octets;
        let
            subnetMaskOctets;

        try {
            cidr = this.parseCIDR(string);
            ipInterfaceOctets = cidr[0].toByteArray();
            subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
            octets = [];
            i = 0;
            while (i < 4) {
                // Network address is bitwise AND between ip interface and mask
                octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
                i++;
            }

            return new this(octets);
        } catch (e) {
            throw new Error("ipaddr: the address does not have IPv4 CIDR format");
        }
    };

    // Tries to parse and validate a string with IPv4 address.
    // Throws an error if it fails.
    ipaddr.IPv4.parse = function (string) {
        const parts = this.parser(string);

        if (parts === null) {
            throw new Error("ipaddr: string is not formatted like an IPv4 Address");
        }

        return new this(parts);
    };

    // Parses the string as an IPv4 Address with CIDR Notation.
    ipaddr.IPv4.parseCIDR = function (string) {
        let match;

        if ((match = string.match(/^(.+)\/(\d+)$/))) {
            const maskLength = parseInt(match[2]);
            if (maskLength >= 0 && maskLength <= 32) {
                const parsed = [this.parse(match[1]), maskLength];
                Object.defineProperty(parsed, "toString", {
                    value() {
                        return this.join("/");
                    }
                });
                return parsed;
            }
        }

        throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range");
    };

    // Classful variants (like a.b, where a is an octet, and b is a 24-bit
    // value representing last three octets; this corresponds to a class C
    // address) are omitted due to classless nature of modern Internet.
    ipaddr.IPv4.parser = function (string) {
        let match;
        let part;
        let
            value;

        // parseInt recognizes all that octal & hexadecimal weirdness for us
        if ((match = string.match(ipv4Regexes.fourOctet))) {
            return (function () {
                const ref = match.slice(1, 6);
                const results = [];

                for (let i = 0; i < ref.length; i++) {
                    part = ref[i];
                    results.push(parseIntAuto(part));
                }

                return results;
            }());
        }
        if ((match = string.match(ipv4Regexes.longValue))) {
            value = parseIntAuto(match[1]);
            if (value > 0xffffffff || value < 0) {
                throw new Error("ipaddr: address outside defined range");
            }

            return ((function () {
                const results = [];
                let shift;

                for (shift = 0; shift <= 24; shift += 8) {
                    results.push((value >> shift) & 0xff);
                }

                return results;
            })()).reverse();
        }
        if ((match = string.match(ipv4Regexes.twoOctet))) {
            return (function () {
                const ref = match.slice(1, 4);
                const results = [];

                value = parseIntAuto(ref[1]);
                if (value > 0xffffff || value < 0) {
                    throw new Error("ipaddr: address outside defined range");
                }

                results.push(parseIntAuto(ref[0]));
                results.push((value >> 16) & 0xff);
                results.push((value >> 8) & 0xff);
                results.push(value & 0xff);

                return results;
            }());
        }
        if ((match = string.match(ipv4Regexes.threeOctet))) {
            return (function () {
                const ref = match.slice(1, 5);
                const results = [];

                value = parseIntAuto(ref[2]);
                if (value > 0xffff || value < 0) {
                    throw new Error("ipaddr: address outside defined range");
                }

                results.push(parseIntAuto(ref[0]));
                results.push(parseIntAuto(ref[1]));
                results.push((value >> 8) & 0xff);
                results.push(value & 0xff);

                return results;
            }());
        }
        return null;
    };

    // A utility function to return subnet mask in IPv4 format given the prefix length
    ipaddr.IPv4.subnetMaskFromPrefixLength = function (prefix) {
        prefix = parseInt(prefix);
        if (prefix < 0 || prefix > 32) {
            throw new Error("ipaddr: invalid IPv4 prefix length");
        }

        const octets = [0, 0, 0, 0];
        let j = 0;
        const filledOctetCount = Math.floor(prefix / 8);

        while (j < filledOctetCount) {
            octets[j] = 255;
            j++;
        }

        if (filledOctetCount < 4) {
            octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);
        }

        return new this(octets);
    };

    // An IPv6 address (RFC2460)
    ipaddr.IPv6 = (function () {
        // Constructs an IPv6 address from an array of eight 16 - bit parts
        // or sixteen 8 - bit parts in network order(MSB first).
        // Throws an error if the input is invalid.
        function IPv6(parts, zoneId) {
            let i;
            let
                part;

            if (parts.length === 16) {
                this.parts = [];
                for (i = 0; i <= 14; i += 2) {
                    this.parts.push((parts[i] << 8) | parts[i + 1]);
                }
            } else if (parts.length === 8) {
                this.parts = parts;
            } else {
                throw new Error("ipaddr: ipv6 part count should be 8 or 16");
            }

            for (i = 0; i < this.parts.length; i++) {
                part = this.parts[i];
                if (!((part >= 0 && part <= 0xffff))) {
                    throw new Error("ipaddr: ipv6 part should fit in 16 bits");
                }
            }

            if (zoneId) {
                this.zoneId = zoneId;
            }
        }

        // Special IPv6 ranges
        IPv6.prototype.SpecialRanges = {
            // RFC4291, here and after
            unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
            linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],
            multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],
            loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
            uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],
            ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],
            // RFC6145
            rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],
            // RFC6052
            rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],
            // RFC3056
            "6to4": [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],
            // RFC6052, RFC6146
            teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],
            // RFC4291
            reserved: [
                [new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]
            ]
        };

        // Checks if this address is an IPv4-mapped IPv6 address.
        IPv6.prototype.isIPv4MappedAddress = function () {
            return this.range() === "ipv4Mapped";
        };

        // The 'kind' method exists on both IPv4 and IPv6 classes.
        IPv6.prototype.kind = function () {
            return "ipv6";
        };

        // Checks if this address matches other one within given CIDR range.
        IPv6.prototype.match = function (other, cidrRange) {
            let ref;

            if (cidrRange === undefined) {
                ref = other;
                other = ref[0];
                cidrRange = ref[1];
            }

            if (other.kind() !== "ipv6") {
                throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");
            }

            return matchCIDR(this.parts, other.parts, 16, cidrRange);
        };

        // returns a number of leading ones in IPv6 address, making sure that
        // the rest is a solid sequence of 0's (valid netmask)
        // returns either the CIDR length or null if mask is not valid
        IPv6.prototype.prefixLengthFromSubnetMask = function () {
            let cidr = 0;
            // non-zero encountered stop scanning for zeroes
            let stop = false;
            // number of zeroes in octet
            const zerotable = {
                0: 16,
                32768: 15,
                49152: 14,
                57344: 13,
                61440: 12,
                63488: 11,
                64512: 10,
                65024: 9,
                65280: 8,
                65408: 7,
                65472: 6,
                65504: 5,
                65520: 4,
                65528: 3,
                65532: 2,
                65534: 1,
                65535: 0
            };
            let part;
            let
                zeros;

            for (let i = 7; i >= 0; i -= 1) {
                part = this.parts[i];
                if (part in zerotable) {
                    zeros = zerotable[part];
                    if (stop && zeros !== 0) {
                        return null;
                    }

                    if (zeros !== 16) {
                        stop = true;
                    }

                    cidr += zeros;
                } else {
                    return null;
                }
            }

            return 128 - cidr;
        };

        // Checks if the address corresponds to one of the special ranges.
        IPv6.prototype.range = function () {
            return ipaddr.subnetMatch(this, this.SpecialRanges);
        };

        // Returns an array of byte-sized values in network order (MSB first)
        IPv6.prototype.toByteArray = function () {
            let part;
            const bytes = [];
            const ref = this.parts;
            for (let i = 0; i < ref.length; i++) {
                part = ref[i];
                bytes.push(part >> 8);
                bytes.push(part & 0xff);
            }

            return bytes;
        };

        // Returns the address in expanded format with all zeroes included, like
        // 2001:0db8:0008:0066:0000:0000:0000:0001
        IPv6.prototype.toFixedLengthString = function () {
            const addr = ((function () {
                const results = [];
                for (let i = 0; i < this.parts.length; i++) {
                    results.push(padPart(this.parts[i].toString(16), 4));
                }

                return results;
            }).call(this)).join(":");

            let suffix = "";

            if (this.zoneId) {
                suffix = `%${this.zoneId}`;
            }

            return addr + suffix;
        };

        // Converts this address to IPv4 address if it is an IPv4-mapped IPv6 address.
        // Throws an error otherwise.
        IPv6.prototype.toIPv4Address = function () {
            if (!this.isIPv4MappedAddress()) {
                throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");
            }

            const ref = this.parts.slice(-2);
            const high = ref[0];
            const low = ref[1];

            return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
        };

        // Returns the address in expanded format with all zeroes included, like
        // 2001:db8:8:66:0:0:0:1
        //
        // Deprecated: use toFixedLengthString() instead.
        IPv6.prototype.toNormalizedString = function () {
            const addr = ((function () {
                const results = [];

                for (let i = 0; i < this.parts.length; i++) {
                    results.push(this.parts[i].toString(16));
                }

                return results;
            }).call(this)).join(":");

            let suffix = "";

            if (this.zoneId) {
                suffix = `%${this.zoneId}`;
            }

            return addr + suffix;
        };

        // Returns the address in compact, human-readable format like
        // 2001:db8:8:66::1
        // in line with RFC 5952 (see https://tools.ietf.org/html/rfc5952#section-4)
        IPv6.prototype.toRFC5952String = function () {
            const regex = /((^|:)(0(:|$)){2,})/g;
            const string = this.toNormalizedString();
            let bestMatchIndex = 0;
            let bestMatchLength = -1;
            let match;

            while ((match = regex.exec(string))) {
                if (match[0].length > bestMatchLength) {
                    bestMatchIndex = match.index;
                    bestMatchLength = match[0].length;
                }
            }

            if (bestMatchLength < 0) {
                return string;
            }

            return `${string.substring(0, bestMatchIndex)}::${string.substring(bestMatchIndex + bestMatchLength)}`;
        };

        // Returns the address in compact, human-readable format like
        // 2001:db8:8:66::1
        //
        // Deprecated: use toRFC5952String() instead.
        IPv6.prototype.toString = function () {
            // Replace the first sequence of 1 or more '0' parts with '::'
            return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, "::");
        };

        return IPv6;
    }());

    // Checks if a given string is formatted like IPv6 address.
    ipaddr.IPv6.isIPv6 = function (string) {
        return this.parser(string) !== null;
    };

    // Checks to see if string is a valid IPv6 Address
    ipaddr.IPv6.isValid = function (string) {
        // Since IPv6.isValid is always called first, this shortcut
        // provides a substantial performance gain.
        if (typeof string === "string" && string.indexOf(":") === -1) {
            return false;
        }

        try {
            const addr = this.parser(string);
            new this(addr.parts, addr.zoneId);
            return true;
        } catch (e) {
            return false;
        }
    };

    // Tries to parse and validate a string with IPv6 address.
    // Throws an error if it fails.
    ipaddr.IPv6.parse = function (string) {
        const addr = this.parser(string);

        if (addr.parts === null) {
            throw new Error("ipaddr: string is not formatted like an IPv6 Address");
        }

        return new this(addr.parts, addr.zoneId);
    };

    ipaddr.IPv6.parseCIDR = function (string) {
        let maskLength;
        let match;
        let
            parsed;

        if ((match = string.match(/^(.+)\/(\d+)$/))) {
            maskLength = parseInt(match[2]);
            if (maskLength >= 0 && maskLength <= 128) {
                parsed = [this.parse(match[1]), maskLength];
                Object.defineProperty(parsed, "toString", {
                    value() {
                        return this.join("/");
                    }
                });
                return parsed;
            }
        }

        throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range");
    };

    // Parse an IPv6 address.
    ipaddr.IPv6.parser = function (string) {
        let addr;
        let i;
        let match;
        let octet;
        let octets;
        let
            zoneId;

        if ((match = string.match(ipv6Regexes.deprecatedTransitional))) {
            return this.parser(`::ffff:${match[1]}`);
        }
        if (ipv6Regexes.native.test(string)) {
            return expandIPv6(string, 8);
        }
        if ((match = string.match(ipv6Regexes.transitional))) {
            zoneId = match[6] || "";
            addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6);
            if (addr.parts) {
                octets = [
                    parseInt(match[2]),
                    parseInt(match[3]),
                    parseInt(match[4]),
                    parseInt(match[5])
                ];
                for (i = 0; i < octets.length; i++) {
                    octet = octets[i];
                    if (!((octet >= 0 && octet <= 255))) {
                        return null;
                    }
                }

                addr.parts.push(octets[0] << 8 | octets[1]);
                addr.parts.push(octets[2] << 8 | octets[3]);
                return {
                    parts: addr.parts,
                    zoneId: addr.zoneId
                };
            }
        }

        return null;
    };

    // Try to parse an array in network order (MSB first) for IPv4 and IPv6
    ipaddr.fromByteArray = function (bytes) {
        const {
            length
        } = bytes;

        if (length === 4) {
            return new ipaddr.IPv4(bytes);
        }
        if (length === 16) {
            return new ipaddr.IPv6(bytes);
        }
        throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address");
    };

    // Checks if the address is valid IP address
    ipaddr.isValid = function (string) {
        return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
    };

    // Attempts to parse an IP Address, first through IPv6 then IPv4.
    // Throws an error if it could not be parsed.
    ipaddr.parse = function (string) {
        if (ipaddr.IPv6.isValid(string)) {
            return ipaddr.IPv6.parse(string);
        }
        if (ipaddr.IPv4.isValid(string)) {
            return ipaddr.IPv4.parse(string);
        }
        throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format");
    };

    // Attempt to parse CIDR notation, first through IPv6 then IPv4.
    // Throws an error if it could not be parsed.
    ipaddr.parseCIDR = function (string) {
        try {
            return ipaddr.IPv6.parseCIDR(string);
        } catch (e) {
            try {
                return ipaddr.IPv4.parseCIDR(string);
            } catch (e2) {
                throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format");
            }
        }
    };

    // Parse an address and return plain IPv4 address if it is an IPv4-mapped address
    ipaddr.process = function (string) {
        const addr = this.parse(string);

        if (addr.kind() === "ipv6" && addr.isIPv4MappedAddress()) {
            return addr.toIPv4Address();
        }
        return addr;
    };

    // An utility function to ease named range matching. See examples below.
    // rangeList can contain both IPv4 and IPv6 subnet entries and will not throw errors
    // on matching IPv4 addresses to IPv6 ranges or vice versa.
    ipaddr.subnetMatch = function (address, rangeList, defaultName) {
        let i;
        let rangeName;
        let rangeSubnets;
        let
            subnet;

        if (defaultName === undefined || defaultName === null) {
            defaultName = "unicast";
        }

        for (rangeName in rangeList) {
            if (Object.prototype.hasOwnProperty.call(rangeList, rangeName)) {
                rangeSubnets = rangeList[rangeName];
                // ECMA5 Array.isArray isn't available everywhere
                if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {
                    rangeSubnets = [rangeSubnets];
                }

                for (i = 0; i < rangeSubnets.length; i++) {
                    subnet = rangeSubnets[i];
                    if (address.kind() === subnet[0].kind() && address.match.apply(address, subnet)) {
                        return rangeName;
                    }
                }
            }
        }

        return defaultName;
    };

    // Export for both the CommonJS and browser-like environment
    if (typeof module !== "undefined" && module.exports) {
        module.exports = ipaddr;
    } else {
        root.ipaddr = ipaddr;
    }
}(this));


text:
var _ = require('underscore'),
    cluster = require('cluster'),
    redis = require('redis');

var redis_lock = "" +
    "local result = redis.call('set', KEYS[1], ARGV[1], 'nx', 'ex', ARGV[2])\n" +
    "if result then\n" +
    " return 1\n" +
    "else\n" +
    " if redis.call('get', KEYS[1]) == ARGV[1] then\n" +
    "  redis.call('expire', KEYS[1], ARGV[2])\n" +
    "  return 2\n" +
    " else\n" +
    "  return 0\n" +
    " end\n" +
    "end";

var redis_unlock = "" +
    "if redis.call('get', KEYS[1]) == ARGV[1]\n" +
    "then\n" +
    " return redis.call('del', KEYS[1])\n" +
    "else\n" +
    " return 0\n" +
    "end";

function ProducerBackend(frontend, options) {
    options = _.clone(options) || {};

    _.defaults(options, {
        host: "localhost",
        port: 6379,
        prefix: "workqueue:",
    });

    this.frontend = frontend;
    this.options = options;
    this.pending = {};
    this.active = {};
    this.queue = [];
    this.producerId = -1;
    this.isMaster = false;
    this.choked = false;

    var producerClient = this.producerClient = redis.createClient(options.port, options.host);
    var responseClient = this.responseClient = redis.createClient(options.port, options.host);

    producerClient.on('ready', _.bind(function () {
        if (this.producerId < 0) {
            producerClient.incr(options.prefix + "producers", _.bind(function (err, data) {
                this.producerId = data;
                this.scheduleResponse();
                this.processQueue();
            }, this));
        } else {
            this.processQueue();
        }
    }, this));
    producerClient.on('close', _.bind(function () {
        this.producerId = -1;
    }));
    producerClient.on('error', _.bind(function () {
        this.producerId = -1;
    }, this));
    producerClient.on('drain', _.bind(function () {
        this.choked = false;
        this.processQueue();
    }, this));
    responseClient.on('ready', _.bind(function () {
        this.scheduleResponse();
    }, this));
    responseClient.on('error', _.bind(function () {
    }));
}

_.extend(ProducerBackend.prototype, {
    setupWorker: function (worker) {
    },

    queueMessage: function (message) {
        message.timestamp = new Date();
        this.queue.push(message);
        this.processQueue();
    },

    processQueue: function () {
        if (this.queue.length == 0) {
            return;
        }

        if (this.choked) {
            if (this.producerClient.command_queue.length > 0) {
                return;
            }
            this.choked = false;
        }

        if (!this.producerClient.connected || (this.producerId < 0)) {
            return;
        }

        if (this.producerClient.command_queue.length > 200) {
            this.choked = true;
            return;
        }

        var run = _.bind(function () {
            this.pending[message.payload.index] = message;
            message.payload.sender = this.producerId;

            var jobQueue = this.options.prefix + "jobs";
            this.producerClient.multi().rpush(jobQueue, JSON.stringify(message.payload), _.bind(function (err) {
                if (err) {
                    if (message.payload.index) {
                        delete this.pending[message.payload.index];
                        this.queue.unshift(message);
                    }
                    delete message.payload.sender;

                    process.nextTick(_.bind(function () {
                        this.processQueue();
                    }, this));
                } else {
                    this.processQueue();
                }
            }, this)).expire(jobQueue, 20).exec();
        }, this);

        var message = this.queue.shift();
        if ("lock" in message.payload.options) {
            var lockName = this.options.prefix + "locks." + message.payload.options.lock;
            var lockData = this.producerId + '.' + message.payload.index;
            this.producerClient.eval(redis_lock, 1, lockName, lockData, Math.floor(message.lock_timeout * 2 / 1000), _.bind(function (err, response) {
                if (err) {
                    this.queue.unshift(message);
                    return;
                }

                if (response > 0) {
                    run();
                } else {
                    this.frontend.onResponse(message, { error: "locked" });
                    process.nextTick(_.bind(function () {
                        this.processQueue();
                    }, this));
                }
            }, this));
        } else {
            run();
        }
    },

    scheduleResponse: function () {
        if (this.producerId < 0) {
            return;
        }

        var responseQueue = this.options.prefix + "response." + this.producerId;
        this.responseClient.blpop(responseQueue, 5, _.bind(function (err, data) {
            if (!err && data) {
                var response = JSON.parse(data[1]);
                var message = this.pending[response.index];
                if (message) {
                    var complete = _.bind(function () {
                        delete this.pending[response.index];
                        this.frontend.onResponse(message, response);
                        delete message.payload.index;
                    }, this);

                    if ("lock" in message.payload.options) {
                        var lockName = this.options.prefix + "locks." + message.payload.options.lock;
                        var lockData = this.producerId + '.' + message.payload.index;
                        this.producerClient.eval(redis_unlock, 1, lockName, lockData, function (err) {
                            complete();
                        });
                    } else {
                        complete();
                    }
                }
            }

            process.nextTick(_.bind(function () {
                this.scheduleResponse();
            }, this));
        }, this));
    },

    onTimeout: function (id) {
        var pending = this.pending[id];
        if (pending) {
            delete this.pending[id];
            delete pending.payload.index;
        } else {
            this.queue = _.filter(this.queue, function (message) {
                return message.payload.index != id;
            });
        }
        this.processQueue();
    },

    acquireMaster: function (timeout, callback) {
        if (this.producerId < 0) {
            callback(false);
            return;
        }

        var masterLock = this.options.prefix + "master";
        this.producerClient.eval(redis_lock, 1, masterLock, this.producerId, Math.floor(timeout / 1000), _.bind(function (err, response) {
            if (err) {
                callback(false);
                return;
            }

            this.isMaster = response > 0;
            callback(this.isMaster);
        }, this));
    },

    releaseMaster: function () {
        this.isMaster = false;

        if (this.producerId < 0) {
            return;
        }

        var masterLock = this.options.prefix + "master";
        this.producerClient.eval(redis_unlock, 1, masterLock, this.producerId);
    }
});

function ConsumerBackend(frontend, options) {
    options = _.clone(options) || {};

    _.defaults(options, {
        host: "localhost",
        port: 6379,
        prefix: "workqueue:"
    });

    this.frontend = frontend;
    this.options = options;
}

_.extend(ConsumerBackend.prototype, {
    run: function () {
        var redisClient = this.redisClient = redis.createClient(this.options.port, this.options.host);
        redisClient.on('ready', _.bind(function () {
            this.reschedule();
        }, this));
        redisClient.on('error', _.bind(function () {
        }, this));
    },

    reschedule: function () {
        var jobQueue = this.options.prefix + "jobs";
        this.redisClient.blpop(jobQueue, 0, _.bind(function (err, data) {
            if (err || !data) {
                this.reschedule();
            }
            this.frontend.onPayload(JSON.parse(data[1]));
        }, this));
    },

    onResponse: function (message, response) {
        var responseQueue = this.options.prefix + "response." + message.sender;
        this.redisClient.multi().rpush(responseQueue, JSON.stringify({
            error: response,
            index: message.index
        })).expire(responseQueue, 20).exec();
        this.reschedule();
    }
});

exports.ProducerBackend = ProducerBackend;
exports.ConsumerBackend = ConsumerBackend;

redpajama_set_name: RedPajamaGithub


text:
package Class::Struct;

## See POD after __END__

use 5.006_001;

use strict;
use warnings::register;
our(@ISA, @EXPORT, $VERSION);

use Carp;

require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(struct);

$VERSION = '0.65';

my $print = 0;
sub printem {
    if (@_) { $print = shift }
    else    { $print++ }
}

{
    package Class::Struct::Tie_ISA;

    sub TIEARRAY {
        my $class = shift;
        return bless [], $class;
    }

    sub STORE {
        my ($self, $index, $value) = @_;
        Class::Struct::_subclass_error();
    }

    sub FETCH {
        my ($self, $index) = @_;
        $self->[$index];
    }

    sub FETCHSIZE {
        my $self = shift;
        return scalar(@$self);
    }

    sub DESTROY { }
}

sub import {
    my $self = shift;

    if ( @_ == 0 ) {
      $self->export_to_level( 1, $self, @EXPORT );
    } elsif ( @_ == 1 ) {
	# This is admittedly a little bit silly:
	# do we ever export anything else than 'struct'...?
      $self->export_to_level( 1, $self, @_ );
    } else {
      goto &struct;
    }
}

sub struct {

    # Determine parameter list structure, one of:
    #   struct( class => [ element-list ])
    #   struct( class => { element-list })
    #   struct( element-list )
    # Latter form assumes current package name as struct name.

    my ($class, @decls);
    my $base_type = ref $_[1];
    if ( $base_type eq 'HASH' ) {
        $class = shift;
        @decls = %{shift()};
        _usage_error() if @_;
    }
    elsif ( $base_type eq 'ARRAY' ) {
        $class = shift;
        @decls = @{shift()};
        _usage_error() if @_;
    }
    else {
        $base_type = 'ARRAY';
        $class = (caller())[0];
        @decls = @_;
    }

    _usage_error() if @decls % 2 == 1;

    # Ensure we are not, and will not be, a subclass.

    my $isa = do {
        no strict 'refs';
        \@{$class . '::ISA'};
    };
    _subclass_error() if @$isa;
    tie @$isa, 'Class::Struct::Tie_ISA';

    # Create constructor.

    croak "function 'new' already defined in package $class"
        if do { no strict 'refs'; defined &{$class . "::new"} };

    my @methods = ();
    my %refs = ();
    my %arrays = ();
    my %hashes = ();
    my %classes = ();
    my $got_class = 0;
    my $out = '';

    $out = "{\n  package $class;\n  use Carp;\n  sub new {\n";
    $out .= "    my (\$class, \%init) = \@_;\n";
    $out .= "    \$class = __PACKAGE__ unless \@_;\n";

    my $cnt = 0;
    my $idx = 0;
    my( $cmt, $name, $type, $elem );

    if( $base_type eq 'HASH' ){
        $out .= "    my(\$r) = {};\n";
        $cmt = '';
    }
    elsif( $base_type eq 'ARRAY' ){
        $out .= "    my(\$r) = [];\n";
    }

    $out .= " bless \$r, \$class;\n\n";

    while( $idx < @decls ){
        $name = $decls[$idx];
        $type = $decls[$idx+1];
        push( @methods, $name );
        if( $base_type eq 'HASH' ){
            $elem = "{'${class}::$name'}";
        }
        elsif( $base_type eq 'ARRAY' ){
            $elem = "[$cnt]";
            ++$cnt;
            $cmt = " # $name";
        }
        if( $type =~ /^\*(.)/ ){
            $refs{$name}++;
            $type = $1;
        }
        my $init = "defined(\$init{'$name'}) ? \$init{'$name'} :";
        if( $type eq '@' ){
            $out .= "    croak 'Initializer for $name must be array reference'\n";
            $out .= "        if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'ARRAY';\n";
            $out .= "    \$r->$name( $init [] );$cmt\n";
            $arrays{$name}++;
        }
        elsif( $type eq '%' ){
            $out .= "    croak 'Initializer for $name must be hash reference'\n";
            $out .= "        if defined(\$init{'$name'}) && ref(\$init{'$name'}) ne 'HASH';\n";
            $out .= "    \$r->$name( $init {} );$cmt\n";
            $hashes{$name}++;
        }
        elsif ( $type eq '$') {
            $out .= "    \$r->$name( $init undef );$cmt\n";
        }
        elsif( $type =~ /^\w+(?:::\w+)*$/ ){
            $out .= "    if (defined(\$init{'$name'})) {\n";
           $out .= "       if (ref \$init{'$name'} eq 'HASH')\n";
            $out .= "            { \$r->$name( $type->new(\%{\$init{'$name'}}) ) } $cmt\n";
           $out .= "       elsif (UNIVERSAL::isa(\$init{'$name'}, '$type'))\n";
            $out .= "            { \$r->$name( \$init{'$name'} ) } $cmt\n";
            $out .= "       else { croak 'Initializer for $name must be hash or $type reference' }\n";
            $out .= "    }\n";
            $classes{$name} = $type;
            $got_class = 1;
        }
        else{
            croak "'$type' is not a valid struct element type";
        }
        $idx += 2;
    }

    $out .= "\n \$r;\n}\n";

    # Create accessor methods.

    my( $pre, $pst, $sel );
    $cnt = 0;
    foreach $name (@methods){
        if ( do { no strict 'refs'; defined &{$class . "::$name"} } ) {
            warnings::warnif("function '$name' already defined, overrides struct accessor method");
        }
        else {
            $pre = $pst = $cmt = $sel = '';
            if( defined $refs{$name} ){
                $pre = "\\(";
                $pst = ")";
                $cmt = " # returns ref";
            }
            $out .= "  sub $name {$cmt\n    my \$r = shift;\n";
            if( $base_type eq 'ARRAY' ){
                $elem = "[$cnt]";
                ++$cnt;
            }
            elsif( $base_type eq 'HASH' ){
                $elem = "{'${class}::$name'}";
            }
            if( defined $arrays{$name} ){
                $out .= "    my \$i;\n";
                $out .= "    \@_ ? (\$i = shift) : return \$r->$elem;\n";
                $out .= "    if (ref(\$i) eq 'ARRAY' && !\@_) { \$r->$elem = \$i; return \$r }\n";
                $sel = "->[\$i]";
            }
            elsif( defined $hashes{$name} ){
                $out .= "    my \$i;\n";
                $out .= "    \@_ ? (\$i = shift) : return \$r->$elem;\n";
                $out .= "    if (ref(\$i) eq 'HASH' && !\@_) { \$r->$elem = \$i; return \$r }\n";
                $sel = "->{\$i}";
            }
            elsif( defined $classes{$name} ){
                $out .= "    croak '$name argument is wrong class' if \@_ && ! UNIVERSAL::isa(\$_[0], '$classes{$name}');\n";
            }
            $out .= "    croak 'Too many args to $name' if \@_ > 1;\n";
            $out .= "    \@_ ? ($pre\$r->$elem$sel = shift$pst) : $pre\$r->$elem$sel$pst;\n";
            $out .= "  }\n";
        }
    }
    $out .= "}\n1;\n";

    print $out if $print;
    my $result = eval $out;
    carp $@ if $@;
}

sub _usage_error {
    confess "struct usage error";
}

sub _subclass_error {
    croak 'struct class cannot be a subclass (@ISA not allowed)';
}

1; # for require

__END__

=head1 NAME

Class::Struct - declare struct-like datatypes as Perl classes

=head1 SYNOPSIS

    use Class::Struct;
            # declare struct, based on array:
    struct( CLASS_NAME => [ ELEMENT_NAME => ELEMENT_TYPE, ... ]);
            # declare struct, based on hash:
    struct( CLASS_NAME => { ELEMENT_NAME => ELEMENT_TYPE, ... });

    package CLASS_NAME;
    use Class::Struct;
            # declare struct, based on array, implicit class name:
    struct( ELEMENT_NAME => ELEMENT_TYPE, ... );

    # Declare struct at compile time
    use Class::Struct CLASS_NAME => [ELEMENT_NAME => ELEMENT_TYPE, ...];
    use Class::Struct CLASS_NAME => {ELEMENT_NAME => ELEMENT_TYPE, ...};

    # declare struct at compile time, based on array, implicit
    # class name:
    package CLASS_NAME;
    use Class::Struct ELEMENT_NAME => ELEMENT_TYPE, ... ;

    package Myobj;
    use Class::Struct;
            # declare struct with four types of elements:
    struct( s => '$', a => '@', h => '%', c => 'My_Other_Class' );

    $obj = new Myobj;               # constructor

                                    # scalar type accessor:
    $element_value = $obj->s;           # element value
    $obj->s('new value');               # assign to element

                                    # array type accessor:
    $ary_ref = $obj->a;                 # reference to whole array
    $ary_element_value = $obj->a(2);    # array element value
    $obj->a(2, 'new value');            # assign to array element

                                    # hash type accessor:
    $hash_ref = $obj->h;                # reference to whole hash
    $hash_element_value = $obj->h('x'); # hash element value
    $obj->h('x', 'new value');          # assign to hash element

                                    # class type accessor:
    $element_value = $obj->c;           # object reference
    $obj->c->method(...);               # call method of object
    $obj->c(new My_Other_Class);        # assign a new object

=head1 DESCRIPTION

C<Class::Struct> exports a single function, C<struct>.
Given a list of element names and types, and optionally
a class name, C<struct> creates a Perl 5 class that implements
a "struct-like" data structure.

The new class is given a constructor method, C<new>, for creating
struct objects.

Each element in the struct data has an accessor method, which is
used to assign to the element and to fetch its value.  The
default accessor can be overridden by declaring a C<sub> of the
same name in the package.  (See Example 2.)

Each element's type can be scalar, array, hash, or class.

=head2 The C<struct()> function

The C<struct> function has three forms of parameter-list.

    struct( CLASS_NAME => [ ELEMENT_LIST ]);
    struct( CLASS_NAME => { ELEMENT_LIST });
    struct( ELEMENT_LIST );

The first and second forms explicitly identify the name of the
class being created.  The third form assumes the current package
name as the class name.

An object of a class created by the first and third forms is
based on an array, whereas an object of a class created by the
second form is based on a hash. The array-based forms will be
somewhat faster and smaller; the hash-based forms are more
flexible.

The class created by C<struct> must not be a subclass of another
class other than C<UNIVERSAL>.

It can, however, be used as a superclass for other classes. To facilitate
this, the generated constructor method uses a two-argument blessing.
Furthermore, if the class is hash-based, the key of each element is
prefixed with the class name (see I<Perl Cookbook>, Recipe 13.12).

A function named C<new> must not be explicitly defined in a class
created by C<struct>.

The I<ELEMENT_LIST> has the form

    NAME => TYPE, ...

Each name-type pair declares one element of the struct. Each
element name will be defined as an accessor method unless a
method by that name is explicitly defined; in the latter case, a
warning is issued if the warning flag (B<-w>) is set.

=head2 Class Creation at Compile Time

C<Class::Struct> can create your class at compile time.  The main reason
for doing this is obvious, so your class acts like every other class in
Perl.  Creating your class at compile time will make the order of events
similar to using any other class ( or Perl module ).

There is no significant speed gain between compile time and run time
class creation, there is just a new, more standard order of events.

=head2 Element Types and Accessor Methods

The four element types -- scalar, array, hash, and class -- are
represented by strings -- C<'$'>, C<'@'>, C<'%'>, and a class name --
optionally preceded by a C<'*'>.

The accessor method provided by C<struct> for an element depends
on the declared type of the element.

=over 4

=item Scalar (C<'$'> or C<'*$'>)

The element is a scalar, and by default is initialized to C<undef>
(but see L<Initializing with new>).

The accessor's argument, if any, is assigned to the element.

If the element type is C<'$'>, the value of the element (after
assignment) is returned. If the element type is C<'*$'>, a reference
to the element is returned.

=item Array (C<'@'> or C<'*@'>)

The element is an array, initialized by default to C<()>.

With no argument, the accessor returns a reference to the
element's whole array (whether or not the element was
specified as C<'@'> or C<'*@'>).

With one or two arguments, the first argument is an index
specifying one element of the array; the second argument, if
present, is assigned to the array element.  If the element type
is C<'@'>, the accessor returns the array element value.  If the
element type is C<'*@'>, a reference to the array element is
returned.

As a special case, when the accessor is called with an array reference
as the sole argument, this causes an assignment of the whole array element.
The object reference is returned.

=item Hash (C<'%'> or C<'*%'>)

The element is a hash, initialized by default to C<()>.

With no argument, the accessor returns a reference to the
element's whole hash (whether or not the element was
specified as C<'%'> or C<'*%'>).

With one or two arguments, the first argument is a key specifying
one element of the hash; the second argument, if present, is
assigned to the hash element.  If the element type is C<'%'>, the
accessor returns the hash element value.  If the element type is
C<'*%'>, a reference to the hash element is returned.

As a special case, when the accessor is called with a hash reference
as the sole argument, this causes an assignment of the whole hash element.
The object reference is returned.

=item Class (C<'Class_Name'> or C<'*Class_Name'>)

The element's value must be a reference blessed to the named
class or to one of its subclasses. The element is not initialized
by default.

The accessor's argument, if any, is assigned to the element. The
accessor will C<croak> if this is not an appropriate object
reference.

If the element type does not start with a C<'*'>, the accessor
returns the element value (after assignment). If the element type
starts with a C<'*'>, a reference to the element itself is returned.

=back

=head2 Initializing with C<new>

C<struct> always creates a constructor called C<new>. That constructor
may take a list of initializers for the various elements of the new
struct.

Each initializer is a pair of values: I<element name>C< =E<gt> >I<value>.
The initializer value for a scalar element is just a scalar value. The
initializer for an array element is an array reference. The initializer
for a hash is a hash reference.

The initializer for a class element is an object of the corresponding class,
or of one of it's subclasses, or a reference to a hash containing named
arguments to be passed to the element's constructor.

See Example 3 below for an example of initialization.

=head1 EXAMPLES

=over 4

=item Example 1

Giving a struct element a class type that is also a struct is how
structs are nested.  Here, C<Timeval> represents a time (seconds and
microseconds), and C<Rusage> has two elements, each of which is of
type C<Timeval>.

    use Class::Struct;

    struct( Rusage => {
        ru_utime => 'Timeval',  # user time used
        ru_stime => 'Timeval',  # system time used
    });

    struct( Timeval => [
        tv_secs  => '$',        # seconds
        tv_usecs => '$',        # microseconds
    ]);

    # create an object:
    my $t = Rusage->new(ru_utime=>Timeval->new(),
        ru_stime=>Timeval->new());

    # $t->ru_utime and $t->ru_stime are objects of type Timeval.
    # set $t->ru_utime to 100.0 sec and $t->ru_stime to 5.0 sec.
    $t->ru_utime->tv_secs(100);
    $t->ru_utime->tv_usecs(0);
    $t->ru_stime->tv_secs(5);
    $t->ru_stime->tv_usecs(0);

=item Example 2

An accessor function can be redefined in order to provide
additional checking of values, etc.  Here, we want the C<count>
element always to be nonnegative, so we redefine the C<count>
accessor accordingly.

    package MyObj;
    use Class::Struct;

    # declare the struct
    struct ( 'MyObj', { count => '$', stuff => '%' } );

    # override the default accessor method for 'count'
    sub count {
        my $self = shift;
        if ( @_ ) {
            die 'count must be nonnegative' if $_[0] < 0;
            $self->{'MyObj::count'} = shift;
            warn "Too many args to count" if @_;
        }
        return $self->{'MyObj::count'};
    }

    package main;
    $x = new MyObj;
    print "\$x->count(5) = ", $x->count(5), "\n";
                            # prints '$x->count(5) = 5'

    print "\$x->count = ", $x->count, "\n";
                            # prints '$x->count = 5'

    print "\$x->count(-5) = ", $x->count(-5), "\n";
                            # dies due to negative argument!

=item Example 3

The constructor of a generated class can be passed a list
of I<element>=>I<value> pairs, with which to initialize the struct.
If no initializer is specified for a particular element, its default
initialization is performed instead. Initializers for non-existent
elements are silently ignored.

Note that the initializer for a nested class may be specified as
an object of that class, or as a reference to a hash of initializers
that are passed on to the nested struct's constructor.

    use Class::Struct;

    struct Breed =>
    {
        name  => '$',
        cross => '$',
    };

    struct Cat =>
    [
        name     => '$',
        kittens  => '@',
        markings => '%',
        breed    => 'Breed',
    ];

    my $cat = Cat->new( name => 'Socks',
               kittens  => ['Monica', 'Kenneth'],
               markings => { socks=>1, blaze=>"white" },
               breed    => Breed->new(name=>'short-hair', cross=>1),
          or:  breed    => {name=>'short-hair', cross=>1},
                      );

    print "Once a cat called ", $cat->name, "\n";
    print "(which was a ", $cat->breed->name, ")\n";
    print "had 2 kittens: ", join(' and ', @{$cat->kittens}), "\n";

=back

=head1 Author and Modification History

Modified by Damian Conway, 2001-09-10, v0.62.

   Modified implicit construction of nested objects.
   Now will also take an object ref instead of requiring a hash ref.
   Also default initializes nested object attributes to undef, rather
   than calling object constructor without args
   Original over-helpfulness was fraught with problems:
       * the class's constructor might not be called 'new'
       * the class might not have a hash-like-arguments constructor
       * the class might not have a no-argument constructor
       * "recursive" data structures didn't work well:
                 package Person;
                 struct { mother => 'Person', father => 'Person'};

Modified by Casey West, 2000-11-08, v0.59.

    Added the ability for compile time class creation.

Modified by Damian Conway, 1999-03-05, v0.58.

    Added handling of hash-like arg list to class ctor.

    Changed to two-argument blessing in ctor to support
    derivation from created classes.

    Added classname prefixes to keys in hash-based classes
    (refer to "Perl Cookbook", Recipe 13.12 for rationale).

    Corrected behaviour of accessors for '*@' and '*%' struct
    elements.  Package now implements documented behaviour when
    returning a reference to an entire hash or array element.
    Previously these were returned as a reference to a reference
    to the element.

Renamed to C<Class::Struct> and modified by Jim Miner, 1997-04-02.

    members() function removed.
    Documentation corrected and extended.
    Use of struct() in a subclass prohibited.
    User definition of accessor allowed.
    Treatment of '*' in element types corrected.
    Treatment of classes as element types corrected.
    Class name to struct() made optional.
    Diagnostic checks added.

Originally C<Class::Template> by Dean Roehrich.

    # Template.pm   --- struct/member template builder
    #   12mar95
    #   Dean Roehrich
    #
    # changes/bugs fixed since 28nov94 version:
    #  - podified
    # changes/bugs fixed since 21nov94 version:
    #  - Fixed examples.
    # changes/bugs fixed since 02sep94 version:
    #  - Moved to Class::Template.
    # changes/bugs fixed since 20feb94 version:
    #  - Updated to be a more proper module.
    #  - Added "use strict".
    #  - Bug in build_methods, was using @var when @$var needed.
    #  - Now using my() rather than local().
    #
    # Uses perl5 classes to create nested data types.
    # This is offered as one implementation of Tom Christiansen's
    # "structs.pl" idea.

=cut


text:
<?php

class SolrSearch_Helpers_Facet_Test extends SolrSearch_Case_Default
{

    public function testMakeUrlEncode()
    {
        $facets = array(
            array('49_s', 'Buildings, Cities & towns, Streets')
        );
        $this->assertEquals(
            '/solr-search?q=&facet=' .
            '49_s%3A%22Buildings%2C+Cities+%26+towns%2C+Streets%22',
            SolrSearch_Helpers_Facet::makeUrl($facets)
        );
    }
}


text:
#ifndef INCLUDE_revwalk_h__
#define INCLUDE_revwalk_h__

#include "common.h"

#include "git2/revwalk.h"
#include "oidmap.h"
#include "commit_list.h"
#include "pqueue.h"
#include "pool.h"
#include "vector.h"

#include "oidmap.h"

struct git_revwalk {
	git_repository *repo;
	git_odb *odb;

	git_oidmap *commits;
	git_pool commit_pool;

	git_commit_list *iterator_topo;
	git_commit_list *iterator_rand;
	git_commit_list *iterator_reverse;
	git_pqueue iterator_time;

	int (*get_next)(git_commit_list_node **, git_revwalk *);
	int (*enqueue)(git_revwalk *, git_commit_list_node *);

	unsigned walking:1,
		first_parent: 1,
		did_hide: 1,
		did_push: 1;
	unsigned int sorting;

	/* the pushes and hides */
	git_commit_list *user_input;

	/* hide callback */
	git_revwalk_hide_cb hide_cb;
	void *hide_cb_payload;
};

git_commit_list_node *git_revwalk__commit_lookup(git_revwalk *walk, const git_oid *oid);

#endif


text:
#!/usr/bin/env node
/* eslint-disable no-fallthrough */

import {
  readFileSync,
  writeFileSync,
  readdirSync,
  existsSync,
  lstatSync,
  realpathSync,
} from "fs";
import { resolve } from "path";

import extract from "./extract.js";

const cwd = process.cwd();

function resolveOptions(args) {
  const options = {};
  const rest = [];

  for (const arg of args) {
    if (arg.startsWith("--")) {
      const [key, value] = arg.slice(2).split("=");
      options[key] = value !== undefined ? value : true;
    } else if (arg.startsWith("-")) {
      arg
        .slice(1)
        .split("")
        .forEach((c) => (options[c] = true));
    } else {
      rest.push(arg);
    }
  }

  return { rest, options };
}

function resolveFileOrDir(path, cb) {
  if (!existsSync(path)) {
    console.error(`'${path}' path does not exist`);
    process.exit(1);
  }

  path = realpathSync(path);
  const stats = lstatSync(path);

  if (stats.isDirectory()) {
    readdirSync(path).forEach((file) =>
      resolveFileOrDir(resolve(path, file), cb),
    );
  } else if (path.endsWith(".js") || path.endsWith(".ts")) {
    cb(readFileSync(path, "utf8"), path.replace(cwd, ""));
  }
}

function extractCommand(args) {
  const { rest, options } = resolveOptions(args);

  if (rest[0]) {
    const fileOrDirPath = resolve(cwd, rest[0]);
    const targetPath = rest[1] && resolve(cwd, rest[1]);

    const messages = [];
    resolveFileOrDir(fileOrDirPath, (content, path) => {
      messages.push(
        ...extract(content, options.format).map((m) => ({ ...m, path })),
      );
    });

    const getDesc = (text, path) => {
      return `${
        (options.p || options["include-path"]) && path ? `${path}:\n` : ""
      }${text}`;
    };

    const touched = new Set();
    const body = messages.reduce(
      (acc, m) => {
        const c = acc[m.key];
        let description = m.description && getDesc(m.description, m.path);

        if (m.description) {
          if (touched.has(m.key)) {
            description = `${c.description}\n${getDesc(m.description, m.path)}`;
          } else {
            touched.add(m.key);
            description = m.description;
          }
        }

        acc[m.key] = {
          message: options.e || options["empty-message"] ? "" : m.message,
          ...c,
          description,
        };

        return acc;
      },
      !(options.f || options.force) && targetPath && existsSync(targetPath)
        ? JSON.parse(readFileSync(targetPath, "utf8"))
        : {},
    );

    const targetContent = JSON.stringify(
      Object.fromEntries(
        Object.entries(body).sort(([a], [b]) =>
          a.localeCompare(b, "en", { sensitivity: "base" }),
        ),
      ),
      null,
      2,
    );

    if (targetPath) {
      writeFileSync(targetPath, targetContent);
    } else {
      console.log(targetContent);
    }
  } else if (!args.length || options.h || options.help) {
    console.log(
      `hybrids - message extractor from source files

Pass a single file or a directory, which will be recursively scanned
for .js and .ts files with messages. If no output file is specified, the output
will be pushed to stdout.

Usage:
hybrids extract [options] <file or directory> [<output file>]

Options:
-e, --empty-message\t Set default message body to empty string
-f, --force\t\t Overwrite output file instead of merge it with existing messages
-p, --include-path\t Include path in message description
-h, --help\t\t Show this help

--format=type\t\t Transform messages to the desired format; supported types: chrome.i18n
`,
    );

    process.exit(1);
  }
}

function helpCommand() {
  console.log(
    `Usage: hybrids <command> [options]

Commands:
extract\t Extract messages from file or directory
help\t\t Show this help

Run command without arguments to see usage.`,
  );

  process.exit(1);
}

const [, , command, ...args] = process.argv;

switch (command) {
  case "extract":
    extractCommand(args);
    break;
  default:
    helpCommand();
}


text:
module Sirportly
  class TwitterAccount < DataObject
    self.collection_path = 'objects/twitter_accounts'
  end
end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.compute.model;

/**
 * A Managed Instance resource.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Compute Engine API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class ManagedInstance extends com.google.api.client.json.GenericJson {

  /**
   * [Output Only] The current action that the managed instance group has scheduled for the
   * instance. Possible values: - NONE The instance is running, and the managed instance group does
   * not have any scheduled actions for this instance.  - CREATING The managed instance group is
   * creating this instance. If the group fails to create this instance, it will try again until it
   * is successful.  - CREATING_WITHOUT_RETRIES The managed instance group is attempting to create
   * this instance only once. If the group fails to create this instance, it does not try again and
   * the group's targetSize value is decreased instead.  - RECREATING The managed instance group is
   * recreating this instance.  - DELETING The managed instance group is permanently deleting this
   * instance.  - ABANDONING The managed instance group is abandoning this instance. The instance
   * will be removed from the instance group and from any target pools that are associated with this
   * group.  - RESTARTING The managed instance group is restarting the instance.  - REFRESHING The
   * managed instance group is applying configuration changes to the instance without stopping it.
   * For example, the group can update the target pool list for an instance without stopping that
   * instance.  - VERIFYING The managed instance group has created the instance and it is in the
   * process of being verified.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String currentAction;

  /**
   * [Output only] The unique identifier for this resource. This field is empty when instance does
   * not exist.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key @com.google.api.client.json.JsonString
  private java.math.BigInteger id;

  /**
   * [Output Only] The URL of the instance. The URL can exist even if the instance has not yet been
   * created.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String instance;

  /**
   * [Output Only] The status of the instance. This field is empty when the instance does not exist.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String instanceStatus;

  /**
   * [Output Only] Information about the last attempt to create or delete the instance.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private ManagedInstanceLastAttempt lastAttempt;

  /**
   * [Output Only] Intended version of this instance.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private ManagedInstanceVersion version;

  /**
   * [Output Only] The current action that the managed instance group has scheduled for the
   * instance. Possible values: - NONE The instance is running, and the managed instance group does
   * not have any scheduled actions for this instance.  - CREATING The managed instance group is
   * creating this instance. If the group fails to create this instance, it will try again until it
   * is successful.  - CREATING_WITHOUT_RETRIES The managed instance group is attempting to create
   * this instance only once. If the group fails to create this instance, it does not try again and
   * the group's targetSize value is decreased instead.  - RECREATING The managed instance group is
   * recreating this instance.  - DELETING The managed instance group is permanently deleting this
   * instance.  - ABANDONING The managed instance group is abandoning this instance. The instance
   * will be removed from the instance group and from any target pools that are associated with this
   * group.  - RESTARTING The managed instance group is restarting the instance.  - REFRESHING The
   * managed instance group is applying configuration changes to the instance without stopping it.
   * For example, the group can update the target pool list for an instance without stopping that
   * instance.  - VERIFYING The managed instance group has created the instance and it is in the
   * process of being verified.
   * @return value or {@code null} for none
   */
  public java.lang.String getCurrentAction() {
    return currentAction;
  }

  /**
   * [Output Only] The current action that the managed instance group has scheduled for the
   * instance. Possible values: - NONE The instance is running, and the managed instance group does
   * not have any scheduled actions for this instance.  - CREATING The managed instance group is
   * creating this instance. If the group fails to create this instance, it will try again until it
   * is successful.  - CREATING_WITHOUT_RETRIES The managed instance group is attempting to create
   * this instance only once. If the group fails to create this instance, it does not try again and
   * the group's targetSize value is decreased instead.  - RECREATING The managed instance group is
   * recreating this instance.  - DELETING The managed instance group is permanently deleting this
   * instance.  - ABANDONING The managed instance group is abandoning this instance. The instance
   * will be removed from the instance group and from any target pools that are associated with this
   * group.  - RESTARTING The managed instance group is restarting the instance.  - REFRESHING The
   * managed instance group is applying configuration changes to the instance without stopping it.
   * For example, the group can update the target pool list for an instance without stopping that
   * instance.  - VERIFYING The managed instance group has created the instance and it is in the
   * process of being verified.
   * @param currentAction currentAction or {@code null} for none
   */
  public ManagedInstance setCurrentAction(java.lang.String currentAction) {
    this.currentAction = currentAction;
    return this;
  }

  /**
   * [Output only] The unique identifier for this resource. This field is empty when instance does
   * not exist.
   * @return value or {@code null} for none
   */
  public java.math.BigInteger getId() {
    return id;
  }

  /**
   * [Output only] The unique identifier for this resource. This field is empty when instance does
   * not exist.
   * @param id id or {@code null} for none
   */
  public ManagedInstance setId(java.math.BigInteger id) {
    this.id = id;
    return this;
  }

  /**
   * [Output Only] The URL of the instance. The URL can exist even if the instance has not yet been
   * created.
   * @return value or {@code null} for none
   */
  public java.lang.String getInstance() {
    return instance;
  }

  /**
   * [Output Only] The URL of the instance. The URL can exist even if the instance has not yet been
   * created.
   * @param instance instance or {@code null} for none
   */
  public ManagedInstance setInstance(java.lang.String instance) {
    this.instance = instance;
    return this;
  }

  /**
   * [Output Only] The status of the instance. This field is empty when the instance does not exist.
   * @return value or {@code null} for none
   */
  public java.lang.String getInstanceStatus() {
    return instanceStatus;
  }

  /**
   * [Output Only] The status of the instance. This field is empty when the instance does not exist.
   * @param instanceStatus instanceStatus or {@code null} for none
   */
  public ManagedInstance setInstanceStatus(java.lang.String instanceStatus) {
    this.instanceStatus = instanceStatus;
    return this;
  }

  /**
   * [Output Only] Information about the last attempt to create or delete the instance.
   * @return value or {@code null} for none
   */
  public ManagedInstanceLastAttempt getLastAttempt() {
    return lastAttempt;
  }

  /**
   * [Output Only] Information about the last attempt to create or delete the instance.
   * @param lastAttempt lastAttempt or {@code null} for none
   */
  public ManagedInstance setLastAttempt(ManagedInstanceLastAttempt lastAttempt) {
    this.lastAttempt = lastAttempt;
    return this;
  }

  /**
   * [Output Only] Intended version of this instance.
   * @return value or {@code null} for none
   */
  public ManagedInstanceVersion getVersion() {
    return version;
  }

  /**
   * [Output Only] Intended version of this instance.
   * @param version version or {@code null} for none
   */
  public ManagedInstance setVersion(ManagedInstanceVersion version) {
    this.version = version;
    return this;
  }

  @Override
  public ManagedInstance set(String fieldName, Object value) {
    return (ManagedInstance) super.set(fieldName, value);
  }

  @Override
  public ManagedInstance clone() {
    return (ManagedInstance) super.clone();
  }

}


text:
/*
 *
 * SelectCharacterService
 *
 * path --> selectCharacterService
 */

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import pallete from 'styles/colors';
import { browserHistory } from 'react-router';

import { NavBar, Icon, Accordion, List, Radio } from 'antd-mobile';

import { loadPublishParams, fetchCharacterService } from 'containers/BusinessPage/actions';
import { makeSelectPublishParams, makeSelectBusinessCharacterService } from 'containers/BusinessPage/selectors';

const RadioItem = Radio.RadioItem;
export class SelectCharacterService extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    const { publishParams } = this.props;

    this.state = {
      selected: publishParams.character ? publishParams.character : {},
    };
  }

  componentWillMount() {
    const { serviceList, getService } = this.props;

    if (!serviceList) {
      getService();
    }
  }

  handleSelect = (item) => {
    this.props.setService({
      character: item,
    });
    browserHistory.goBack();
  }

  render() {
    const { selected } = this.state;
    const { serviceList } = this.props;
    return (
      <div>
        <NavBar
          mode="light"
          iconName={false}
          leftContent={<Icon type={require('icons/ali/返回.svg')} size="sm" color={pallete.theme} />}
          onLeftClick={() => browserHistory.goBack()}
        >
          选择特色服务
        </NavBar>
        <List>
          {serviceList && serviceList.map((i, index) => (
            <RadioItem key={i.id} checked={selected.id ? selected.id === i.id : index === 0} onChange={() => this.handleSelect(i)}>
              {i.name}
            </RadioItem>
          ))}
        </List>
      </div>
    );
  }
}

SelectCharacterService.propTypes = {
  /**
   * action: get the service info
   */
  getService: PropTypes.func,
  /**
   * action: set the service info
   */
  setService: PropTypes.func,
  /**
   * reducer: the publish params
   */
  publishParams: PropTypes.object,
  /**
   * reducer: the service list info
   */
  serviceList: PropTypes.oneOfType([
    PropTypes.bool,
    PropTypes.array,
  ]),
};

const mapStateToProps = createStructuredSelector({
  serviceList: makeSelectBusinessCharacterService(),
  publishParams: makeSelectPublishParams(),
});

function mapDispatchToProps(dispatch) {
  return {
    getService: () => dispatch(fetchCharacterService()),
    setService: (params) => dispatch(loadPublishParams(params)),
  };
}

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


text:
A response has been submitted for the survey entitled {{survey.label}}. Please see below the questions and the submitted answer(s):

---

{{#responses}}
{{{q}}}
{{{a}}}

{{/responses}}


text:
<?php

namespace Sabre\VObject\Recur\EventIterator;

use PHPUnit\Framework\TestCase;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\InvalidDataException;
use Sabre\VObject\Reader;
use Sabre\VObject\Recur\EventIterator;

class Issue26Test extends TestCase
{
    public function testExpand(): void
    {
        $this->expectException(InvalidDataException::class);
        $input = <<<ICS
BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
UID:bae5d57a98
RRULE:FREQ=MONTHLY;BYDAY=0MO,0TU,0WE,0TH,0FR;INTERVAL=1
DTSTART;VALUE=DATE:20130401
DTEND;VALUE=DATE:20130402
END:VEVENT
END:VCALENDAR
ICS;

        $vcal = Reader::read($input);
        $this->assertInstanceOf(VCalendar::class, $vcal);

        new EventIterator($vcal, 'bae5d57a98');
    }
}


text:
Search

<md-navbar>
    <form slot="content">

            <input id="search" type="search" required>
            <md-icon>search</md-icon>
            close

    </form>
</md-navbar>


text:
![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png) 0

To use the animalquiz skill, try saying...

* *Alexa start animal quiz*

* *start new game*

* *the answer is three*

Presents the user with a 5 question quiz about animals. Keeps score and reports the correct answer if the user gets it wrong.

***

### Skill Details

* **Invocation Name:** animal quiz
* **Category:** null
* **ID:** amzn1.ask.skill.c9637d92-b323-4718-b2e8-763dd2c00bb2
* **ASIN:** B01JDMKPQY
* **Author:** Erin Sullivan
* **Release Date:** August 5, 2016 @ 04:07:31
* **In-App Purchasing:** No


text:
package org.apache.geronimo.st.ui.refactoring;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;

/**
 *
 */
public class DeploymentPlanEditHelper {
	private String fileName;
	private DeploymentPlanHandler handler;

	public DeploymentPlanEditHelper(String fileName){
		this.fileName=fileName;
		this.handler=new DeploymentPlanHandler(fileName);
		init();
	}

	public DeploymentPlanEditHelper(DeploymentPlanHandler deploymentPlanHandler){
		this.fileName=deploymentPlanHandler.file;
		this.handler=deploymentPlanHandler;
		//parse the deployment plan, generate info
		init();
	}

	private void init(){
		SAXParserFactory factory=SAXParserFactory.newInstance();
		try {
			factory.setFeature("http://xml.org/sax/features/namespaces", true);
			SAXParser p = factory.newSAXParser();
			File file =new File(fileName);
			p.parse(file, handler);
		} catch (SAXNotRecognizedException e) {
			e.printStackTrace();
		} catch (SAXNotSupportedException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
	}

	public int getNodeOffset(String nodeName){
		return handler.getNodeOffset(nodeName);
	}

	public String getNodeValue(String nodeName){
		return handler.getNodeValue(nodeName);
	}

}


text:
<?php

namespace axelitus\Base\Comparison;

use axelitus\Base\Arr;
use axelitus\Base\BigNum;
use axelitus\Base\Comparer;
use Closure;

/**
 * Class BigNumComparer
 *
 * BigNum comparer implementation.
 *
 * @package axelitus\Base
 * @SuppressWarnings(PHPMD.StaticAccess)
 */
class BigNumComparer extends Comparer
{
    /**
     * Constructor
     *
     * @param null|int $scale This optional parameter is used to set the number of digits after the decimal place in the result.
     *                        If no scale is given the global default scale will be used.
     * @throws \InvalidArgumentException
     */
    public function __construct($scale = null)
    {
        parent::__construct(
            function ($item1, $item2) {
                if (!BigNum::is($item1) || !BigNum::is($item2)) {
                    throw new \InvalidArgumentException(
                        "The \$item1 and \$item2 parameters must be numeric (or string representing a big number)."
                    );
                }

                return BigNum::compare($item1, $item2, $this->options['scale']);
            }
        );
        $this->options = new Arr(['scale' => $scale]);
    }

    /**
     * This comparer does not allow to set the callback outside this class.
     *
     * @param Closure $callback The new callback.
     *
     * @throws \RuntimeException
     */
    public function setCallback(Closure $callback = null)
    {
        if ($this->callback !== null || $callback === null) {
            throw new \RuntimeException("Cannot redeclare this comparer callback.");
        }

        $this->callback = Closure::bind($callback, $this, get_called_class());
    }
}


text:
#ifndef _H_PATHNAME
#define _H_PATHNAME

#include "Collect.h"
#include "Thunks.h"
#include "ObjSets.h"

enum path_flags { rooted_path = 1, wild_card_path = 2 };

visible_class_debug_ok (PathName)

class PathName : public Set
{
public:
	int			flags;
	short		n_levels;
	MCHAR**		path_levels;
	Thunk*		root_set_thunk;
	Value*		root_set;

				PathName();
				~PathName();
#	define		is_pathname(v) ((DbgVerify(!is_sourcepositionwrapper(v)), (v))->tag == class_tag(PathName))

				classof_methods (PathName, Set);
	void		collect() { delete this; }
	ScripterExport void		sprin1(CharStream* s);

	ScripterExport Value* eval();
	void		append(MCHAR* level_name);
	Value*		find_object(MCHAR* name);
	Value*		get_object();

	ScripterExport Value* map(node_map& m);

#include "defimpfn.h"
	def_generic  (get,		"get");   // indexed get (no put or append)
	def_property ( count );
	def_property ( center );
	def_property ( min );
	def_property ( max );
};

extern MCHAR* ellipsis_level_name;
extern MCHAR* parent_level_name;

// Added: 12/17/03
// This class provides an interface to a derived implementation class that caches scene node names
// based on the node name resolution scheme used by MAXScript. There is a single, static instance
// of the derived class.
// usage: SceneNodeByNameCache::GetInst().GetSceneNodeByName(theName,true,false);
class SceneNodeByNameCache
{
public:
	ScripterExport virtual ~SceneNodeByNameCache();
	// get the singleton instance of SceneNodeByNameCache
	ScripterExport static SceneNodeByNameCache& GetInst();
	// get the INode* given the name. If exactMatch is false, use inexact (MXS) name matching. Can return NULL
	ScripterExport virtual INode *GetSceneNodeByName(const MCHAR* name, bool exactMatch = false, bool caseSensitive = false) = 0;
};

#endif


text:
package com.oembedler.moon.graphql;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.NestedRuntimeException;

/**
 * @author oEmbedler Inc.
 */
public class SpringGraphQLSchemaBeanFactory implements ApplicationContextAware, GraphQLSchemaBeanFactory {

    private ApplicationContext applicationContext;

    @Override
    public <T> T getBeanByType(final Class<T> objectClass) {
        return retrieveBean(objectClass, null);
    }

    @Override
    public <T> T getBeanByName(final String beanName) {
        return retrieveBean(null, beanName);
    }

    @Override
    public <T> boolean containsBean(final Class<T> objectClass) {
        String[] beanNames = applicationContext.getBeanNamesForType(objectClass);
        return beanNames != null && beanNames.length > 0;
    }

    private <T> T retrieveBean(final Class<T> objectClass, final String beanName) {
        T object = null;
        if (StringUtils.isNoneBlank(beanName) &&
                applicationContext != null && applicationContext.containsBean(beanName)) {
            object = (T) applicationContext.getBean(beanName);
        } else {
            object = BeanFactoryUtils.beanOfType(applicationContext, objectClass);
        }
        return object;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}


text:
@interface JXMagicMoveTransition ()

@property (nonatomic, assign) JXMagicMoveTransitionType type;

@end

@implementation JXMagicMoveTransition

+ (instancetype)transitionWithTransitionType:(JXMagicMoveTransitionType)type
{
    return [[self alloc] initWithTransitionType:type];
}

- (instancetype)initWithTransitionType:(JXMagicMoveTransitionType)type
{
    self = [super init];
    if (self) {
        self.type = type;
    }
    return self;
}

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.3f;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    switch (self.type) {
        case JXMagicMoveTransitionTypePush:
            [self doPushAnimation:transitionContext];
            break;
        case JXMagicMoveTransitionTypePop:
            [self doPopAnimation:transitionContext];
            break;
        default:
            break;
    }
}

- (void)doPushAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
{
    JXMagicMoveController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    JXMagicMovePushedController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *containerView = [transitionContext containerView];

    JXMagicMoveCell *cell = (JXMagicMoveCell *)[fromVC.collectionView cellForItemAtIndexPath:fromVC.currentIndexPath];
    //这里的imageView相当于一个临时的替身演员用于过渡
    UIImageView *imageView = [[UIImageView alloc] initWithImage:cell.headerImageView.image];
    imageView.frame = [cell.headerImageView convertRect:cell.headerImageView.bounds toView:containerView];
    //下路addsubview的顺序不能颠倒,不然替身演员就看不到了
    [containerView addSubview:toVC.view];
    [containerView addSubview:imageView];
    //动画前清理现场和状态调整
    cell.headerImageView.hidden = YES;
    toVC.view.alpha = 0;
    toVC.headerImageView.hidden = YES;

    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        imageView.frame = [toVC.headerImageView convertRect:toVC.headerImageView.bounds toView:containerView];
        toVC.view.alpha = 1;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
        toVC.headerImageView.hidden = NO;
        imageView.hidden = YES;
    }];
}

- (void)doPopAnimation:(id<UIViewControllerContextTransitioning>)transitionContext
{
    JXMagicMovePushedController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    JXMagicMoveController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    //containerView会自动把当前环境的fromVC.view添加到index为0的位置,所以push或者pop的时候要把toVC.view添加到合适的层级
    UIView *containerView = [transitionContext containerView];

    JXMagicMoveCell *cell = (JXMagicMoveCell *)[toVC.collectionView cellForItemAtIndexPath:toVC.currentIndexPath];

    UIImageView *imageView = [containerView.subviews lastObject];
    fromVC.headerImageView.hidden = YES;
    cell.headerImageView.hidden = YES;
    imageView.hidden = NO;
    //toVC一定要添加到最底层,否则会遮盖imageView,而且在手势交互失败的时候,containerView会自动移除它
    [containerView insertSubview:toVC.view atIndex:0];
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        fromVC.view.alpha = 0;
        imageView.frame = [cell.headerImageView convertRect:cell.headerImageView.bounds toView:containerView];
    }completion:^(BOOL finished) {
        if ([transitionContext transitionWasCancelled]) {
            [transitionContext completeTransition:NO];
            imageView.hidden = YES;
            fromVC.headerImageView.hidden = NO;
        }else {
            [transitionContext completeTransition:YES];
            cell.headerImageView.hidden = NO;
            [imageView removeFromSuperview];
        }
    }];
}
@end


text:
// Copyright (c) 2010-12, Pierre-Antoine Delsart, Kurtis Geerlings, Joey Huston,
//                 Brian Martin, and Christopher Vermilion
//
//----------------------------------------------------------------------
// This file is part of SpartyJet.
//
//  SpartyJet is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 3 of the License, or
//  (at your option) any later version.
//
//  SpartyJet is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with SpartyJet; if not, write to the Free Software
//  Foundation, Inc.:
//      59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//----------------------------------------------------------------------

/*
 * This is an example C++ program to drive SpartyJet.  Can be used:
 *  $> ./FourVecExample.exe
 *
 * This example demonstrates using input directly from memory, i.e., the output
 * of other code as opposed to a file.
 */

#include "SJconfig.h"

#include "JetCore/JetBuilder.hh"
#include "IO/FourVecInput.hh"
#include "FastJetTools/FastJetFinder.hh"

#include "fastjet/JetDefinition.hh"

using namespace fastjet;
using namespace SpartyJet;
using namespace SpartyJet::FastJet;

#include <string>
#include <cmath>
using namespace std;

/// A really simple four-vector class.  You can use anything that provides this interface
/// E.g., fastjet::PseudoJet, TLorentzVector, CLHEP vector, etc.
struct StupidFourVector {
  double x,y,z,t;
  // all you need is this operator:  (no error checking in this dummy implementation)
  double operator[](int i) const
    {switch(i) {case 0: return x; case 1: return y; case 2: return z; case 3: default: return t;}}
};

/// A skeleton class that provides the four-vector input -- presumably wraps
/// some other code.  Functions defined below.
class Reader {
public:
  Reader() : event(0), n_particles(0) {}

  // These three functions must be implemented in your Reader class!  next() can return any four-vector class.
  bool empty() const;
  const StupidFourVector& next(); // can also return by value, but this is cheaper
  //StupidFourVector next();
  bool event_done() const;

private:
  int event;
  int n_particles;
  StupidFourVector v;
};

int main() {

  // Create a builder object
  JetBuilder builder(DEBUG);
  //builder.silent_mode(); // turn off debugging

  // Create an input object and open the input file
  Reader reader;
  FourVecInput<Reader> input(reader);
  builder.configure_input(&input);

  // Add an algorithm (AntiKt)
  FastJetFinder *anti4 = new FastJetFinder("AntiKt4", antikt_algorithm, 0.4, false);
  builder.add_default_analysis(anti4);

  // Add a text output file to easily list all of the jets
  builder.add_text_output(string(SPARTYJET_DIR)+"/data/output/fourvec.dat");

  // Configure the output (name of tree, root file)
  builder.configure_output("SpartyJet_Tree",string(SPARTYJET_DIR)+"/data/output/fourvec.root");

  // Run the builder on the events
  builder.process_events();

  return 0;
}

bool Reader::empty() const {return (event >= 10);}
bool Reader::event_done() const {return (n_particles >= 20);}

/// generate some pseudo-data (obviously not at all random)
/// events are produced in identical pairs, just as a check
const StupidFourVector& Reader::next() {
  if (event_done()) n_particles = 0;

  n_particles++;
  double n = n_particles * (event / 2);
  v.x = 10.0 + n;
  v.y = 5.0 + n;
  v.z = 20.0 * (10.0 - n);
  v.t = sqrt(v.x*v.x + v.y*v.y + v.z*v.z);

  if (event_done()) event++;
  return v;
}


text:
/**
  @module ember-flexberry-gis
*/

import Ember from 'ember';
import layout from '../templates/components/flexberry-maptoolbar';

/**
  Component's CSS-classes names.
  JSON-object containing string constants with CSS-classes names related to component's .hbs markup elements.

  @property {Object} flexberryClassNames
  @property {String} flexberryClassNames.prefix Component's CSS-class names prefix ('flexberry-maptoolbar').
  @property {String} flexberryClassNames.wrapper Component's wrapping
 CSS-class name ('flexberry-maptoolbar').
  @readonly
  @static

  @for FlexberryMaptoolbarComponent
*/
const flexberryClassNamesPrefix = 'flexberry-maptoolbar';
const flexberryClassNames = {
  prefix: flexberryClassNamesPrefix,
  wrapper: flexberryClassNamesPrefix
};

/**
  Map toolbar component.
  Component must be used in combination with any map tool components as a wrapper for them.

  Usage:
  templates/my-map-form.hbs
  ```handlebars
  {{#flexberry-maptoolbar}}
    {{map-tools/base name="my-map-tool" leafletMap=leafletMap}}
  {{/flexberry-maptoolbar}}
  ```

  @class FlexberryMaptoolbarComponet
  @extends Ember.Component
*/
let FlexberryMaptoolbarComponent = Ember.Component.extend({
  /**
    Component's template reference.
  */
  layout,

  /**
    Reference to component's CSS-classes names.
    Must be also a component's instance property to be available from component's .hbs template.
  */
  flexberryClassNames,

  /**
    Component's wrapping
 CSS-classes names.

    Any other CSS-classes can be added through component's 'class' property.
    ```handlebars
    {{flexberry-maptoolbar
      class="secondary"
    }}
    ```

    @property classNames
    @type String[]
    @default ['flexberry-maptoolbar', 'ui', 'menu']
  */
  classNames: [flexberryClassNames.wrapper, 'ui', 'menu']
});

// Add component's CSS-class names as component's class static constants
// to make them available outside of the component instance.
FlexberryMaptoolbarComponent.reopenClass({
  flexberryClassNames
});

export default FlexberryMaptoolbarComponent;


text:
package com.restfiddle.dto;

import java.util.List;

public class OAuth2RequestDTO extends BaseDTO {

    private String authorizationUrl;

    private String accessTokenUrl;

    private String clientId;

    private String clientSecret;

    private String accessTokenLocation;

    private List<String> scopes;

    public String getAuthorizationUrl() {
	return authorizationUrl;
    }

    public void setAuthorizationUrl(String authorizationUrl) {
	this.authorizationUrl = authorizationUrl;
    }

    public String getAccessTokenUrl() {
	return accessTokenUrl;
    }

    public void setAccessTokenUrl(String accessTokenUrl) {
	this.accessTokenUrl = accessTokenUrl;
    }

    public String getClientId() {
	return clientId;
    }

    public void setClientId(String clientId) {
	this.clientId = clientId;
    }

    public String getClientSecret() {
	return clientSecret;
    }

    public void setClientSecret(String clientSecret) {
	this.clientSecret = clientSecret;
    }

    public String getAccessTokenLocation() {
	return accessTokenLocation;
    }

    public void setAccessTokenLocation(String accessTokenLocation) {
	this.accessTokenLocation = accessTokenLocation;
    }

    public List<String> getScopes() {
	return scopes;
    }

    public void setScopes(List<String> scopes) {
	this.scopes = scopes;
    }

}