text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />

//@tag enterprise
/**
 * @class Ext.data.amf.Encoder
 * This class serializes data in the Action Message Format (AMF) format.
 * It can write simple and complex objects, to be used in conjunction with an
 * AMF-compliant server.
 * To encode a byte array, first construct an Encoder, optionally setting the format:
 *
 *     var encoder = Ext.create('Ext.data.amf.Encoder', {
 *       format: 3
 *     });
 *
 * Then use the writer methods to out data to the :
 *
 *     encoder.writeObject(1);
 *
 * And access the data through the #bytes property:
 *     encoder.bytes;
 *
 * You can also reset the class to start a new byte array:
 *
 *     encoder.clear();
 *
 * Current limitations:
 * AMF3 format (format:3)
 * - writeObject will write out XML object, not legacy XMLDocument objects. A
 *   writeXmlDocument method is provided for explicitly writing XMLDocument
 *   objects.
 * - Each object is written out explicitly, not using the reference tables
 *   supported by the AMF format. This means the function does NOT support
 *   circular reference objects.
 * - Array objects: only the numbered indices and data will be written out.
 *   Associative values will be ignored.
 * - Objects that aren't Arrays, Dates, Strings, Document (XML) or primitive
 *   values will be written out as anonymous objects with dynamic data.
 * - There's no JavaScript equivalent to the ByteArray type in ActionScript,
 *   hence data will never be searialized as ByteArrays by the writeObject
 *   function. A writeByteArray method is provided for writing out ByteArray objects.
 *
 * AMF0 format (format:0)
 * - Each object is written out explicitly, not using the reference tables
 *   supported by the AMF format. This means the function does NOT support
 *   circular reference objects.
 * - Array objects: the function always writes an associative array (following
 *   the behavior of flex).
 * - Objects that aren't Arrays, Dates, Strings, Document (XML) or primitive
 *   values will be written out as anonymous objects.
 *
 * For more information on working with AMF data please refer to the
 * [AMF Guide](#/guide/amf).
 */
Ext.define('Ext.data.amf.Encoder', {

    alias: 'data.amf.Encoder',

    config: {
        format: 3
    },

    /**
     * @property {Array} bytes
     * @readonly
     * The constructed byte array.
     */
    bytes: [],

    /**
     * Creates new Encoder.
     * @param {Object} config Configuration options
     */
    constructor: function(config) {
        this.initConfig(config);
        this.clear();
    },

    /**
     * Reset all class states and starts a new empty array for encoding data.
     * The method generates a new array for encoding, so it's safe to keep a
     * reference to the old one.
     */
    clear: function() {
        this.bytes = [];
    },

    /**
     * Sets the functions that will correctly serialize for the relevant
     * protocol version.
     * @param {Number} protocol_version the protocol version to support
     */
    applyFormat: function(protocol_version) {
        var funcs = {
            0: {
                writeUndefined: this.write0Undefined,
                writeNull: this.write0Null,
                writeBoolean: this.write0Boolean,
                writeNumber: this.write0Number,
                writeString: this.write0String,
                writeXml: this.write0Xml,
                writeDate: this.write0Date,
                writeArray: this.write0Array,
                writeGenericObject: this.write0GenericObject
            },

            3: {
                writeUndefined: this.write3Undefined,
                writeNull: this.write3Null,
                writeBoolean: this.write3Boolean,
                writeNumber: this.write3Number,
                writeString: this.write3String,
                writeXml: this.write3Xml,
                writeDate: this.write3Date,
                writeArray: this.write3Array,
                writeGenericObject: this.write3GenericObject
            }

        }[protocol_version];
        if (funcs) {
            Ext.apply(this, funcs);
            return protocol_version;
        } else {
            //<debug>
            Ext.Error.raise("Unsupported AMF format: " + protocol_version + ". Only '3' (AMF3) is supported at this point.");
            //</debug>
            return; // return nothing
        }
    },

    /**
     * Write the appropriate data items to the byte array. Supported types:
     * - undefined
     * - null
     * - boolean
     * - integer (if AMF3 - limited by 29-bit int, otherwise passed as double)
     * - double
     * - UTF-8 string
     * - XML Document (identified by being instaneof Document. Can be generated with: new DOMParser()).parseFromString(xml, "text/xml");
     * @param {Object} item A primitive or object to write to the stream
     */
    writeObject: function(item) {
        var t = typeof(item);
        //Ext.log("Writing " + item + " of type " + t);
        if (t === "undefined") {
            this.writeUndefined();
        } else if (item === null) { // can't check type since typeof(null) returns "object"
            this.writeNull();
        } else if (Ext.isBoolean(item)) {
            this.writeBoolean(item);
        } else if (Ext.isString(item)) {
            this.writeString(item);
        } else if (t === "number" || item instanceof Number) { // Can't use Ext.isNumeric since it accepts strings as well
            this.writeNumber(item);
        } else if (t === "object") {
            // Figure out which object this is
            if (item instanceof Date) {
                this.writeDate(item);
            } else if (Ext.isArray(item)) { // this won't catch associative arrays deserialized by the Packet class!
                this.writeArray(item);
            } else if (this.isXmlDocument(item)) {
                this.writeXml(item);
            } else {
                // Treat this as a generic object with name/value pairs of data.
                this.writeGenericObject(item);
            }
        } else {
            //<debug>
            Ext.log.warn("AMF Encoder: Unknown item type " + t + " can't be written to stream: " + item);
            //</debug>
        }
    },

    /**
     * Writes the AMF3 undefined value to the byte array.
     * @private
     */
    write3Undefined: function() {
        this.writeByte(0x00); // AMF3 undefined
    },

    /**
     * Writes the AMF0 undefined value to the byte array.
     * @private
     */
    write0Undefined: function() {
        this.writeByte(0x06); // AMF0 undefined
    },

    /**
     * Writes the AMF3 null value to the byte array.
     * @private
     */
    write3Null: function() {
        this.writeByte(0x01); // AMF3 null
    },

    /**
     * Writes the AMF0 null value to the byte array.
     * @private
     */
    write0Null: function() {
        this.writeByte(0x05); // AMF0 null
    },

    /**
     * Writes the appropriate AMF3 boolean value to the byte array.
     * @param {boolean} item The value to write
     * @private
     */
    write3Boolean: function(item) {
        //<debug>
        if (typeof(item) !== "boolean") {
            Ext.log.warn("Encoder: writeBoolean argument is not a boolean. Coercing.");
        }
        // </debug>
        if (item) {
            this.writeByte(0x03); // AMF3 true
        } else {
            this.writeByte(0x02); // AMF3 false
        }
    },

    /**
     * Writes the appropriate AMF0 boolean value to the byte array.
     * @param {boolean} item The value to write
     * @private
     */
    write0Boolean: function(item) {
        //<debug>
        if (typeof(item) !== "boolean") {
            Ext.log.warn("Encoder: writeBoolean argument is not a boolean. Coercing.");
        }
        // </debug>
        this.writeByte(0x01); // AMF0 boolean marker
        if (item) {
            this.writeByte(0x01); // AMF0 true
        } else {
            this.writeByte(0x00); // AMF0 false
        }
    },

    /**
     * Encodes a U29 int, returning a byte array with the encoded number.
     * @param item - unsigned int value
     * @private
     */
    encode29Int: function(item) {
        var data = [], // prepare the bytes, then send them to the array
            num = item,
            nibble,
            i;
        if (num == 0) {
            return [0]; // no other data
        }
        // we have a special case if the number is 4-nibbles in U29 encoding
        if (num > 0x001fffff) {
            // last nibble is an 8-bit value
            nibble = num & 0xff;
            data.unshift(nibble);
            num = num >> 8;
        }
        // get all the 7-bit parts ready
        while (num > 0) {
            nibble = num & 0x7f; // 7 bits
            data.unshift(nibble);
            num = num >> 7;
        }
        // now we need to mark each MSb of a 7-bit byte with a 1, except the absolute last one which has a 0.
        // If there's an 8-bit byte, the 7-bit byte before it is marked with 1 as well.
        for (i = 0; i < data.length - 1; i++) {
            data[i] = data[i] | 0x80;
        }
        return data;
    },

    /**
     * Writes a numberic value to the byte array in AMF3 format
     * @param item A native numeric value, Number instance or one of Infinity, -Infinity or NaN
     * @private
     */
    write3Number: function(item) {
        var data;
        var maxInt = 0x1fffffff,
            minSignedInt = -0xfffffff;
        //<debug>
        if (typeof(item) !== "number" && !(item instanceof Number)) {
            Ext.log.warn("Encoder: writeNumber argument is not numeric. Can't coerce.");
        }
        // </debug>

        // switch to the primitive value for handling:
        if (item instanceof Number) {
            item = item.valueOf();
        }
        // First we need to determine if this is an integer or a float.
        // AMF3 allows integers between -2^28 < item < 2^29, else they need to be passed as doubles.
        if (item % 1 === 0 && item >= minSignedInt && item <= maxInt) {
            // The number has no decimal point and is within bounds. Let's encode it.
            item = item & maxInt; // get an unsigned value to work with - we only care about 29 bits.
            data = this.encode29Int(item);
            // And , mark it as an integer
            data.unshift(0x04); // AMF3 integer marker
            // write it!
            this.writeBytes(data);

        } else {
            data = this.encodeDouble(item);
            data.unshift(0x05); // AMF3 double marker
            this.writeBytes(data);
        }
    },

    /**
     * Writes a numberic value to the byte array in AMF0 format
     * @param item A native numeric value, Number instance or one of Infinity, -Infinity or NaN
     * @private
     */
    write0Number: function(item) {
        var data;
        //<debug>
        if (typeof(item) !== "number" && !(item instanceof Number)) {
            Ext.log.warn("Encoder: writeNumber argument is not numeric. Can't coerce.");
        }
        // </debug>

        // switch to the primitive value for handling:
        if (item instanceof Number) {
            item = item.valueOf();
        }
        //In AMF0 numbers are always serialized as double-float values.
        data = this.encodeDouble(item);
        data.unshift(0x00); // AMF0 double marker
        this.writeBytes(data);
    },

    /**
     * Convert a UTF 16 char to a UTF 8 char
     * @param {Number} c char 16-bit code to convert
     * @return {Array} byte array with the UTF 8 values
     */
    encodeUtf8Char: function(c) {
        var data = [],
            val, b, i,
            marker;
        //<debug>
        if (c > 0x10FFFF) {
            //<debug>
            Ext.Error.raise("UTF 8 char out of bounds");
            //</debug>
        }
        //</debug>
        if (c <= 0x7F) {
            // One byte UTF8
            data.push(c);
        } else {
            // Multi-byte UTF8. Figure out how many bytes:
            if (c <= 0x7ff) {
                b = 2;
            } else if (c <= 0xffff) {
                b = 3;
            } else {
                b = 4;
            }
            // encode LSBs of value
            marker = 0x80; // MSB marker
            for (i = 1; i < b; i++) {
                val = (c & 0x3F) | 0x80; // lowest 6 bits of number, plus a flag to mark the byte
                data.unshift(val);
                c = c >> 6; // drop 6 LSbs
                marker = (marker >> 1) | 0x80; // add one more bit for every byte
            }
            // the final byte is now ready, but we need to mark it to show how many other bytes follow
            val = c | marker;
            data.unshift(val);
        }
        return data;
    },

    /**
     * Accepts a string and returns a byte array encoded in UTF-8
     * @param {String} str String to encode
     * @return {Array} byte array with string encoded in UTF-8 format
     * @private
     */
    encodeUtf8String: function(str) {
        var i,
            utf8Data = [];
        for (i = 0; i < str.length; i++) {
            var data = this.encodeUtf8Char(str.charCodeAt(i));
            Ext.Array.push(utf8Data, data);
        }
        return utf8Data;

        // quicker conversion, doesn't work in IE:
        //          utf8String = unescape(encodeURIComponent(str)),
        //          utf8Data = [];

    },

    /**
     * Encode the length of a UTF-8 string in AMF3 format.
     * @param {Array} utf8Data byte array with the encoded data
     * @return {Array} byte array encoding of length
     *
     * @private
     */
    encode3Utf8StringLen: function(utf8Data) {
        var len = utf8Data.length,
            data = [];
        if (len <= 0xFFFFFFF) {
            // String is under max allowed length in AMF3
            // AMF3 strings use the LSb to mark whether it's a string reference or a string value. For now we only pass values:
            len = len << 1;
            len = len | 1; // mark as value
            // push length value to the array
            data =this.encode29Int(len);
        } else {
            //<debug>
            Ext.Error.raise("UTF8 encoded string too long to serialize to AMF: " + len);
            //</debug>
        }
        return data;
    },

    /**
     * Write an AMF3 UTF-8 string to the byte array
     * @param {String} item The string to write
     * @private
     */
    write3String: function(item) {
        //<debug>
        if (!Ext.isString(item)) {
            Ext.log.warn("Encoder: writString argument is not a string.");
        }
        // </debug>
        if (item == "") { // special case for the empty string
            this.writeByte(0x06); // AMF3 string marker
            this.writeByte(0x01); // zero length string
        } else {
            // first encode string to UTF-8.
            var utf8Data = this.encodeUtf8String(item);
            var lenData = this.encode3Utf8StringLen(utf8Data);
            // only write encoding once we got here, i.e. length of string is legal
            this.writeByte(0x06); // AMF3 string marker, only if we can actually write a string
            this.writeBytes(lenData);
            this.writeBytes(utf8Data);
        }
    },

    /**
     * Encode 16- or 32-bit integers into big-endian (network order) bytes
     * @param {Number} value the number to encode.
     * @param {Number} byte_count 2 or 4 byte encoding
     * @return {Array} byte array with encoded number
     */
    encodeXInt: function(value, byte_count) {
        var data = [],
            i;
        for (i = 0; i < byte_count; i++) {
            data.unshift(value & 0xff);
            value = value >> 8;
        }
        return data;
    },

    /**
     * Write an AMF0 UTF-8 string to the byte array
     * @param {String} item The string to write
     * @private
     */
    write0String: function(item) {
        //<debug>
        if (!Ext.isString(item)) {
            Ext.log.warn("Encoder: writString argument is not a string.");
        }
        // </debug>
        if (item == "") { // special case for the empty string
            this.writeByte(0x02); // AMF0 short string marker
            this.writeBytes([0x00, 0x00]); // zero length string
        } else {
            // first encode string to UTF-8.
            var utf8Data = this.encodeUtf8String(item);
            var encoding;
            var lenData;
            if (utf8Data.length <= 0xffff) {
                // short string
                encoding = 0x02; // short string
                lenData = this.encodeXInt(utf8Data.length, 2);
            } else {
                // long string
                encoding = 0x0C; // long string
                lenData = this.encodeXInt(utf8Data.length, 4);
            }
            this.writeByte(encoding); // Approperiate AMF0 string marker
            this.writeBytes(lenData);
            this.writeBytes(utf8Data);
        }
    },

    /**
     * Writes an XML document in AMF3 format.
     * @param {Object} xml XML document (type Document typically)
     * @param {number} amfType Either 0x07 or 0x0B - the AMF3 object type to use
     * @private
     */
    write3XmlWithType: function(xml, amfType) {
        //<debug>
        // We accept XML Documents, or strings
        if (amfType !== 0x07 && amfType !== 0x0B) {
            Ext.Error.raise("write XML with unknown AMF3 code: " + amfType);
        }
        if (!this.isXmlDocument(xml)) {
            Ext.log.warn("Encoder: write3XmlWithType argument is not an xml document.");
        }
        // </debug>
        var xmlStr = this.convertXmlToString(xml);
        if (xmlStr == "") { // special case for the empty string
            this.writeByte(amfType); // AMF3 XML marker
            this.writeByte(0x01); // zero length string
        } else {
            // first encode string to UTF-8.
            var utf8Data = this.encodeUtf8String(xmlStr);
            var lenData = this.encode3Utf8StringLen(utf8Data);
            // only write encoding once we got here, i.e. length of string is legal
            this.writeByte(amfType); // AMF3 XML marker, only if we can actually write the string
            this.writeBytes(lenData);
            this.writeBytes(utf8Data);
        }
    },

    /**
     * Writes an Legacy XMLDocument (ActionScript Legacy XML object) in AMF3
     * format. Must be called explicitly.
     * The writeObject method will call writeXml and not writeXmlDocument.
     * @param {Object} xml XML document (type Document typically) to write
     */
    write3XmlDocument: function(xml) {
        this.write3XmlWithType(xml, 0x07);
    },

    /**
     * Writes an XML object (ActionScript 3 new XML object) in AMF3 format.
     * @param {Object} xml XML document (type Document typically) to write
     * @private
     */
    write3Xml: function(xml) {
        this.write3XmlWithType(xml, 0x0B);
    },

    /**
     * Writes an XMLDocument in AMF0 format.
     * @param {Object} xml XML document (type Document typically) to write
     * @private
     */
    write0Xml: function(xml) {
        //<debug>
        // We accept XML Documents, or strings
        if (!this.isXmlDocument(xml)) {
            Ext.log.warn("Encoder: write0Xml argument is not an xml document.");
        }
        // </debug>
        var xmlStr = this.convertXmlToString(xml);
        this.writeByte(0x0F); // AMF0 XML marker

        // Always encoded as a long string
        var utf8Data = this.encodeUtf8String(xmlStr);
        var lenData = this.encodeXInt(utf8Data.length, 4);
        this.writeBytes(lenData);
        this.writeBytes(utf8Data);

    },

    /**
     * Writes a date in AMF3 format.
     * @param {Date} date the date object
     * @private
     */
    write3Date: function(date) {

        //<debug>
        if (!(date instanceof Date)) {
            Ext.Error.raise("Serializing a non-date object as date: " + date);
        }
        //</debug>
        // For now, we don't use object references to just encode the date.
        this.writeByte(0x08); // AMF3 date marker
        this.writeBytes(this.encode29Int(0x1)); // mark this as a date value - we don't support references yet
        this.writeBytes(this.encodeDouble(new Number(date)));
    },

    /**
     * Writes a date in AMF0 format.
     * @param {Date} date the date object
     * @private
     */
    write0Date: function(date) {

        //<debug>
        if (!(date instanceof Date)) {
            Ext.Error.raise("Serializing a non-date object as date: " + date);
        }
        //</debug>
        // For now, we don't use object references to just encode the date.
        this.writeByte(0x0B); // AMF0 date marker
        this.writeBytes(this.encodeDouble(new Number(date)));
        this.writeBytes([0x00, 0x00]); // placeholder for timezone, standard says to keep 0, flash actually writes data here
    },

    /**
     * Writes an array in AMF3 format. Only the ordered part of the array use handled.
     * Unordered parts are ignored (e.g. a["hello"] will not be encoded).
     * @param {Array} arr the array to serialize.
     * @private
     */
    write3Array: function(arr) {

        //<debug>
        if (!Ext.isArray(arr)) {
            Ext.Error.raise("Serializing a non-array object as array: " + arr);
        }
        if (arr.length > 0xFFFFFFF) {
            Ext.Error.raise("Array size too long to encode in AMF3: " + arr.length);
        }
        //</debug>
        // For now, we don't use object references to just encode the array.
        this.writeByte(0x09); // AMF3 array marker

        // encode ordered part of array's length
        var len = arr.length;
        len = len << 1; // right-most bit marks this as size
        len = len | 0x1; // mark it a size
        this.writeBytes(this.encode29Int(len));

        // The associative part of the array is ignored, so mark it as empty
        this.writeByte(0x01); // equivalent to an empty UTF-8 string

        // now iterate over the array, writing each element
        Ext.each(arr, function(x) {this.writeObject(x);}, this);
    },

    /**
     * Writes a key-value pair in AMF0 format.
     * @param {String} key the name of the property
     * @param {Object} value to write in AMF0 format
     */
    write0ObjectProperty: function(key, value) {
        if (!(key instanceof String) && (typeof(key) !== "string")) {
            // coerce to a string
            key = key + "";
        }
        // first encode the key to a short UTF-8.
        var utf8Data = this.encodeUtf8String(key);
        var lenData;
        lenData = this.encodeXInt(utf8Data.length, 2);
        this.writeBytes(lenData);
        this.writeBytes(utf8Data);
        // and now write out the object
        this.writeObject(value);
    },

    /**
     * Writes an associative array in AMF0 format.
     * @param {Array} arr the array to serialize.
     * @private
     */
    write0Array: function(arr) {
        var key;
        //<debug>
        if (!Ext.isArray(arr)) {
            Ext.Error.raise("Serializing a non-array object as array: " + arr);
        }
        //</debug>

        /* This writes a strict array, but it seems Flex always writes out associative arrays, so mimic behavior

         // For now, we don't use object references to just encode the array.
         this.writeByte(0x0A); // AMF0 strict array marker

         // encode ordered part of array's length
         var len = arr.length;
         this.writeBytes(this.encodeXInt(len, 4));

         // now iterate over the array, writing each element
         Ext.each(arr, function(x) {this.writeObject(x);}, this);
         */
        // Use ECMA (associative) array type
        this.writeByte(0x08); // AMF0 ECMA-array marker
        // we need to know the length of the array before we write the serialized data
        // to the array. Better to traverse it twice than to copy all the byte data afterwards
        var total = 0;
        for (key in arr) {
            total++;
        }
        // Now write out the length of the array
        this.writeBytes(this.encodeXInt(total, 4));
        // then write out the data
        for (key in arr) {
            Ext.Array.push(this.write0ObjectProperty(key, arr[key]));
        }
        // And finally the object end marker
        this.writeBytes([0x00, 0x00, 0x09]);
    },

    /**
     * Writes a strict-array in AMF0 format. Unordered parts are ignored (e.g.
     * a["hello"] will not be encoded). This function is included for
     * completeness and will never be called by writeObject.
     * @param {Array} arr the array to serialize.
     */
    write0StrictArray: function(arr) {

        //<debug>
        if (!Ext.isArray(arr)) {
            Ext.Error.raise("Serializing a non-array object as array: " + arr);
        }
        //</debug>

        // For now, we don't use object references to just encode the array.
        this.writeByte(0x0A); // AMF0 strict array marker

        // encode ordered part of array's length
        var len = arr.length;
        this.writeBytes(this.encodeXInt(len, 4));

        // now iterate over the array, writing each element
        Ext.each(arr, function(x) {this.writeObject(x);}, this);
    },

    /**
     * Write a byte array in AMF3 format. This function is never called directly
     * by writeObject since there's no way to distinguish a regular array from a
     * byte array.
     * @param {Array} arr the object to serialize.
     */
    write3ByteArray: function(arr) {

        //<debug>
        if (!Ext.isArray(arr)) {
            Ext.Error.raise("Serializing a non-array object as array: " + arr);
        }
        if (arr.length > 0xFFFFFFF) {
            Ext.Error.raise("Array size too long to encode in AMF3: " + arr.length);
        }
        //</debug>
        this.writeByte(0x0c); // Byte array marker

        // for now no support for references, so just dump the length and data

        // encode array's length
        var len = arr.length;
        len = len << 1; // right-most bit marks this as size
        len = len | 0x1; // mark it a size
        this.writeBytes(this.encode29Int(len));
        // and finally, dump the byte data
        this.writeBytes(arr);
    },

    /**
     * Write an object to the byte array in AMF3 format.
     * Since we don't have the class information form Flex, the object
     * is written as an anonymous object.
     * @param {Array} obj the object to serialize.
     * @private
     */
    write3GenericObject: function(obj) {
        var name;

        //<debug>
        if (!Ext.isObject(obj)) {
            Ext.Error.raise("Serializing a non-object object: " + obj);
        }
        //</debug>
        // For now, we don't use object references so just encode the object.
        this.writeByte(0x0A); // AMF3 object marker
        // The following 29-int is marked as follows (LSb to MSb) to signify a
        // "U29O-traits":
        // 1 - LSb marks an object value (1) or an object reference (0) which
        //     is not yet supported.
        // 1 - trait values (1) or trait references (0) which are not supported
        //     yet.
        // 0 - AMF3 format (0) or externalizable, i.e. object handles own
        //     serialization (1) which is not supported.
        // 1 - dynamic (1) or not dynamic (0) object which is not relevant since
        //     we pass all data as dynamic fields.
        // The reset of the bits signify how many sealed traits the object has.
        //     we pass 0 since all data is passed as dynamic fields
        var oType = 0x0b; // binary 1011
        this.writeByte(oType);
        // Next we pass the class name, which is the empty string for anonymous
        // objects
        this.writeByte(0x01);
        // Next are the sealed traits (of which we have none)
        // And now the name / value pairs of dynamic fields
        for (name in obj) {
            // Ensure that name is actually a string
            var newName = new String(name).valueOf();
            if (newName == "") {
                //<debug>
                Ext.Error.raise("Can't encode non-string field name: " + name);
                //</debug>
            }
            var nameData = (this.encodeUtf8String(name));
            this.writeBytes(this.encode3Utf8StringLen(name));
            this.writeBytes(nameData);
            this.writeObject(obj[name]);
        }
        // And mark the end of the dynamic field section with the empty string
        this.writeByte(0x01);
    },

    /**
     * Write an object to the byte array in AMF0 format.
     * Since we don't have the class information form Flex, the object
     * is written as an anonymous object.
     * @param {Array} obj the object to serialize.
     * @private
     */
    write0GenericObject: function(obj) {
        var typed, amfType, key;
        //<debug>
        if (!Ext.isObject(obj)) {
            Ext.Error.raise("Serializing a non-object object: " + obj);
        }
        //</debug>
        // For now, we don't use object references so just encode the object.
        // if the object is typed, the ID changes and we need to send the type ahead of the data
        typed = !!obj.$flexType;
        amfType = typed ? 0x10 : 0x03; // typed vs. untyped object
        this.writeByte(amfType); // AMF0 object marker
        // if typed, send object type
        if (typed) {
            this.write0ShortUtf8String(obj.$flexType);
        }
        // then write out the data. There's no counter, but other than that it's the same as an ECMA array
        for (key in obj) {
            if (key != "$flexType") {
                Ext.Array.push(this.write0ObjectProperty(key, obj[key]));
            }
        }
        // And finally the object end marker
        this.writeBytes([0x00, 0x00, 0x09]);
    },

    /**
     * Writes a byte to the byte array
     * @param {number} b Byte to write to the array
     * @private
     */
    writeByte: function(b) {

        //<debug>
        if (b < 0 || b > 255) {
            Ex.Error.raise('ERROR: Value being written outside byte range: ' + b);
        }
        //</debug>
        Ext.Array.push(this.bytes, b);
    },

    /**
     * Writes a byte array to the byte array
     * @param {number} b Byte array to append to the array
     * @private
     */
    writeBytes: function(b) {
        var i;
        //<debug>
        if (!Ext.isArray(b)) {
            Ext.Error.raise("Decoder: writeBytes parameter is not an array: " + b);
        }
        for (i = 0; i < b.length; i++) {
            if (b[i] < 0 || b[i] > 255 || !Ext.isNumber(b[i])) {
                Ext.Error.raise("ERROR: Value " + i + " being written outside byte range: " + b[i]);
            }
        }
        //</debug>
        Ext.Array.push(this.bytes, b);
    },

    /**
     * Converts an XML Document object to a string.
     * @param {Object} xml XML document (type Document typically) to convert
     * @return {String} A string representing the document
     * @private
     */
    convertXmlToString: function(xml) {
        var str;
        if (window.XMLSerializer) {
            // this is not IE, so:
            str = new window.XMLSerializer().serializeToString(xml);
        } else {
            //no XMLSerializer, might be an old version of IE
            str = xml.xml;
        }
        return str;
    },

    /**
     * Tries to determine if an object is an XML document
     * @param {Object} item to identify
     * @return {Boolean} true if it's an XML document, false otherwise
     */
    isXmlDocument: function(item) {
        // We can't test if Document is defined since IE just throws an exception. Instead rely on the DOMParser object
        if (window.DOMParser) {
            if (Ext.isDefined(item.doctype)) {
                return true;
            }
        }
        // Otherwise, check if it has an XML field
        if (Ext.isString(item.xml)) {
            // and we can get the xml
            return true;
        }
        return false;
    },

    /*
     * The encodeDouble function is derived from code from the typedarray.js library by Linden Research, Inc.
     *

     Copyright (c) 2010, Linden Research, Inc.

     Permission is hereby granted, free of charge, to any person obtaining a copy
     of this software and associated documentation files (the "Software"), to deal
     in the Software without restriction, including without limitation the rights
     to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     copies of the Software, and to permit persons to whom the Software is
     furnished to do so, subject to the following conditions:

     The above copyright notice and this permission notice shall be included in
     all copies or substantial portions of the Software.

     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     THE SOFTWARE.
     */

    /**
     * Encodes an IEEE-754 double-precision number.
     * @param {Number} num the number to encode
     * @return {Array} byte array containing the encoded number
     * @private
     */
    encodeDouble: function(v) {
        var ebits = 11, fbits = 52; // double
        var bias = (1 << (ebits - 1)) - 1,
            s, e, f, ln,
            i, bits, str, data = [];

        // Precalculated values
        var K_INFINITY=[127,240,0,0,0,0,0,0],
            K_NINFINITY=[255,240,0,0,0,0,0,0],
            K_NAN=[255,248,0,0,0,0,0,0];

        // Compute sign, exponent, fraction
        if (isNaN(v)) {
            data = K_NAN;
        } else if (v === Infinity) {
            data = K_INFINITY;
        } else if (v == -Infinity) {
            data = K_NINFINITY;
        } else {
            // not a special case, so encode
            if (v === 0) {
                e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0;
            }
            else {
                s = v < 0;
                v = Math.abs(v);

                if (v >= Math.pow(2, 1 - bias)) {
                    // Normalized
                    ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
                    e = ln + bias;
                    f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
                }
                else {
                    // Denormalized
                    e = 0;
                    f = Math.round(v / Math.pow(2, 1 - bias - fbits));
                }
            }

            // Pack sign, exponent, fraction
            bits = [];
            for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); }
            for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); }
            bits.push(s ? 1 : 0);
            bits.reverse();
            str = bits.join('');

            // Bits to bytes
            data = [];
            while (str.length) {
                data.push(parseInt(str.substring(0, 8), 2));
                str = str.substring(8);
            }
        }
        return data;
    },

    /**
     * Writes a short UTF8 string preceded with a 16-bit length.
     * @param {String} str the string to write
     */
    write0ShortUtf8String: function(str) {
        var utf8Data = this.encodeUtf8String(str),
            lenData;
        lenData = this.encodeXInt(utf8Data.length, 2);
        this.writeBytes(lenData);
        this.writeBytes(utf8Data);
    },

    /**
     * Writes an AMF packet to the byte array
     * @param {Array} headers the headers to serialize. Each item in the array
     *                should be an object with three fields:
     *                name, mustUnderstand, value
     * @param {Array} messages the messages to serialize. Each item in the array
     *                should be an object with three fields:
     *                targetUri, responseUri, body
     */
    writeAmfPacket: function(headers, messages) {
        var i;
        //<debug>
        if (this.config.format != 0) {
            Ext.Error.raise ("Trying to write a packet on an AMF3 Encoder. Only AMF0 is supported!");
        }
        if (!Ext.isArray(headers)) {
            Ext.Error.raise("headers is not an array: " + headers);
        }
        if (!Ext.isArray(messages)) {
            Ext.Error.raise("messages is not an array: " + messages);
        }
        //</debug>
        // Write Packet marker
        this.writeBytes([0x00, 0x00]); // AMF 0 version for this packet.
        // Write header count
        this.writeBytes(this.encodeXInt(headers.length, 2));
        // And actual headers
        for (i in headers) {
            this.writeAmfHeader(headers[i].name, headers[i].mustUnderstand, headers[i].value);
        }
        // Write message count
        this.writeBytes(this.encodeXInt(messages.length, 2));
        // And actual messages
        for (i in messages) {
            this.writeAmfMessage(messages[i].targetUri, messages[i].responseUri, messages[i].body);
        }
    },

    /**
     * Write an AMF header to the byte array. AMF headers are always encoded in AMF0.
     * @param {String} headerName the header name
     * @param {Boolean} mustUnderstand true if the receiver must understand this header or else reject it, false otherwise
     * @param {Object} value the value to serialize. Must be an object that can be serialized by AMF
     * @private
     */
    writeAmfHeader: function(headerName, mustUnderstand, value) {
        //<debug>
        if (this.config.format != 0) {
            Ext.Error.raise ("Trying to write a header on an AMF3 Encoder. Only AMF0 is supported!");
        }
        if (!Ext.isString(headerName)) {
            Ext.Error.raise("targetURI is not a string: " + targetUri);
        }
        if ((typeof(mustUnderstand) !== "boolean") && !Ext.isBoolean(mustUnderstand)) {
            Ext.Error.raise("mustUnderstand is not a boolean value: " + mustUnderstand);
        }
        //</debug>
        // write header name
        this.write0ShortUtf8String(headerName);
        // write must understand byte
        var mu = mustUnderstand ? 0x01 : 0x00;
        this.writeByte(mu);
        // next write the header length of -1 (undetermined) to the stream
        this.writeBytes(this.encodeXInt(-1, 4));
        // write value
        this.writeObject(value);
    },

    /**
     * Writes an AMF message to the byte array. AMF messages are always encoded in AMF0.
     * @param {String} targetUri the class / method to call
     * @param {String} responseUri the response should call here
     * @param {Array} body the parameters to pass to the called method, wrapped in an array
     * @private
     */
    writeAmfMessage: function(targetUri, responseUri, body) {
        //<debug>
        if (this.config.format != 0) {
            Ext.Error.raise ("Trying to write a message on an AMF3 Encoder. Only AMF0 is supported!");
        }
        if (!Ext.isString(targetUri)) {
            Ext.Error.raise("targetURI is not a string: " + targetUri);
        }
        if (!Ext.isString(responseUri)) {
            Ext.Error.raise("targetURI is not a string: " + responseUri);
        }
        if (!Ext.isArray(body)) {
            Ext.Error.raise("body is not an array: " + typeof(body));
        }
        //</debug>
        // write target URI
        this.write0ShortUtf8String(targetUri);
        // write response URI
        this.write0ShortUtf8String(responseUri);
        // next write the message length of -1 (undetermined) to the stream
        this.writeBytes(this.encodeXInt(-1, 4));
        // write the paramters
        this.write0StrictArray(body);
    }

});


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

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.

=cut

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=head1 NAME

Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::DumpAllTreesOrthoXML

=head1 DESCRIPTION

This Analysis/RunnableDB is designed to dump all the trees of a database
in a single file, with the OrthoXML format

It requires one parameter:
 - compara_db: connection parameters to the Compara database

The following parameters are optional:
 - file: [string] output file to dump (otherwise: standard output)

=head1 SYNOPSIS

standaloneJob.pl Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::DumpAllTreesOrthoXML
  -compara_db 'mysql://ensro:@compara4:3306/mp12_compara_nctrees_66c' -member_type ncrna -file dump_ncrna

=head1 AUTHORSHIP

Ensembl Team. Individual contributions can be found in the GIT log.

=head1 APPENDIX

The rest of the documentation details each of the object methods.
Internal methods are usually preceded with an underscore (_)

=cut

package Bio::EnsEMBL::Compara::RunnableDB::GeneTrees::DumpAllTreesOrthoXML;

use strict;

use Bio::EnsEMBL::ApiVersion;
use Bio::EnsEMBL::Compara::Graph::OrthoXMLWriter;

use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable');

sub fetch_input {
    my ($self) = @_;

    # Defines the file handle
    my $file_handle = *STDOUT;
    if (defined $self->param('file')) {
        $file_handle = IO::File->new( $self->param('file'), 'w');
    }
    $self->param('file_handle', $file_handle);

    # Creates the OrthoXML writer
    my $w = Bio::EnsEMBL::Compara::Graph::OrthoXMLWriter->new(
            -HANDLE => $self->param('file_handle'),
            -SOURCE => "Ensembl Compara",
            -SOURCE_VERSION => software_version(),
            );
    $self->param('writer', $w);

    # List of all the trees
    my $list_trees = $self->compara_dba->get_GeneTreeAdaptor->fetch_all(-clusterset_id => 'default', -member_type => $self->param('member_type'), -tree_type => 'tree');

    $self->param('tree_list', $list_trees);

}

sub run {
    my ($self) = @_;

    my $seq_member_adaptor = $self->compara_dba->get_SeqMemberAdaptor;
    my $callback_list_members = sub {
        my ($species) = @_;
        my $constraint = 'm.genome_db_id = '.($species->dbID);
        $constraint .= ' AND gtr.tree_type = "tree"';
        $constraint .= ' AND gtr.clusterset_id = "default"';
        $constraint .= ' AND gtr.member_type = "'.($self->param('member_type')).'"' if defined $self->param('member_type');
        my $join = [[['gene_tree_node', 'gtn'], 'm.seq_member_id = gtn.seq_member_id', undef], [['gene_tree_root', 'gtr'], 'gtn.root_id = gtr.root_id', undef]];
        return $seq_member_adaptor->generic_fetch($constraint, $join);
    };

    my $list_species = $self->compara_dba->get_GenomeDBAdaptor->fetch_all;
    # Launches the dump
    $self->param('writer')->_write_data($list_species, $callback_list_members, $self->param('tree_list'));
}

sub write_output {
    my ($self) = @_;
    $self->param('writer')->finish();
    $self->param('file_handle')->close();
}

1;

redpajama_set_name: RedPajamaGithub


text:
/**
 * \class Zeni::Model
 *
 * \ingroup zenilib
 *
 * \brief An Abstraction of a 3D Model
 *
 * The Model class is responsible for loading 3ds models into a Vertex_Buffer
 * using lib3ds.
 *
 * \author bazald
 *
 * Contact: bazald@zenipex.com
 */

/**
 * \class Zeni::Model_Visitor
 *
 * \ingroup zenilib
 *
 * \brief A visitor base class
 *
 * A Model_Visitor is called once per node each time visit_nodes
 * is called.
 *
 * \author bazald
 *
 * Contact: bazald@zenipex.com
 */

/**
 * \class Zeni::Model_Extents
 *
 * \ingroup zenilib
 *
 * \brief A visitor for determining the extents or bounds of a model
 *
 * \note You should create a new Model_Extents for each call of visit_nodes.
 *
 * \warning It gives valid results for the first frame of an animation only.
 *
 * \author bazald
 *
 * Contact: bazald@zenipex.com
 */

#ifndef ZENI_MODEL_H
#define ZENI_MODEL_H

#include <Zeni/Coordinate.h>
#include <Zeni/Vector3f.h>

#include <memory>

struct Lib3dsFile;
struct Lib3dsMesh;
struct Lib3dsMeshInstanceNode;
struct Lib3dsNode;

namespace Zeni {

  class ZENI_GRAPHICS_DLL Model;
  struct Quaternion;

  class ZENI_GRAPHICS_DLL Model_Visitor {
  public:
    Model_Visitor() {}
    virtual ~Model_Visitor() {}

    // Note visiting function
    virtual void operator()(const Model & /*model*/, Lib3dsNode * const & /*node*/) {}

    // Mesh visiting function
    virtual void operator()(const Model & /*model*/, Lib3dsMeshInstanceNode * const & /*node*/, Lib3dsMesh * const & /*mesh*/) {}
  };

  class ZENI_GRAPHICS_DLL Model_Extents : public Model_Visitor {
  public:
    Model_Extents();

    virtual void operator()(const Model &model, Lib3dsMeshInstanceNode * const &node, Lib3dsMesh * const &mesh);

    Point3f lower_bound, upper_bound; ///< The bounding box of model, first frame only if animated
    bool started;
  };

#ifndef TEMP_DISABLE
  class ZENI_GRAPHICS_DLL Model {
  public:
    /// The only way to create a Model
    Model(const String &filename, const bool align_normals_ = false);
    Model(const Model &rhs);
    ~Model();

    Model & operator =(const Model &rhs);

    // Accessors
    inline Lib3dsFile * const & get_file() const; ///< Get the full 3ds file info
    Point3f get_position() const; ///< Get the position of the Model
    inline const Model_Extents & get_extents() const; ///< Get the extents of the Model
    float get_keyframes() const; ///< Get the number of keyframes; may be higher than you expect
    inline const Vector3f & get_scale() const; ///< Get the Model scale
    inline std::pair<Vector3f, float> get_rotate() const; ///< Get the Model rotation
    inline const Point3f & get_translate() const; ///< Get the Model translation
    inline const float & get_keyframe() const; ///< Get the current (key)frame
    inline bool will_do_normal_alignment() const; // Find out whether the Model will try to fix broken normals before rendering

    // Modifiers
    inline void set_scale(const Vector3f &multiplier); ///< Scale the Model
    inline void set_rotate(const float &angle, const Vector3f &ray); ///< Rotate the Model
    inline void set_rotate(const Quaternion &quaternion); ///< Rotate the Model
    inline void set_translate(const Point3f &vector); ///< Translate the Model
    void set_keyframe(const float &keyframe); ///< Set the current (key)frame; interpolation is automatic
    inline void do_normal_alignment(const bool align_normals_ = true); // Set whether Model should try to fix broken normals before rendering

    // Post-Order Traversal
    void visit_nodes(Model_Visitor &mv, Lib3dsNode * node = 0) const; ///< Visit all nodes
    void visit_meshes(Model_Visitor &mv, Lib3dsNode * node = 0, Lib3dsMesh * const &mesh = 0) const; ///< Visit all meshes

    void render() const;

    // Thread-Unsafe versions
    inline Lib3dsFile * const & thun_get_file() const; ///< Get the full 3ds file info - Thread Unsafe Version

  private:
    String m_filename;
    Lib3dsFile *m_file;
    float m_keyframe;
    bool m_align_normals;

    mutable Model_Visitor *m_unrenderer;

    Model_Extents m_extents;
    Point3f m_position;

    Vector3f m_scale, m_rotate;
    Point3f m_translate;
    float m_rotate_angle;

//     class ZENI_GRAPHICS_DLL Loader : public Task {
//       Loader(const Loader &);
//       Loader & operator=(const Loader &);
//
//     public:
//       Loader(Model &model) : m_model(model) {}
//
//       int function();
//
//     private:
//       Model &m_model;
//     };

    void load();

//     mutable Loader m_loader;
//     mutable Runonce_Computation m_loader_op;
  };
#endif

  struct ZENI_GRAPHICS_DLL Model_Init_Failure : public Error {
    Model_Init_Failure() : Error("Zeni Model Failed to Initialize Correctly") {}
  };

  struct ZENI_GRAPHICS_DLL Model_Render_Failure : public Error {
    Model_Render_Failure() : Error("Zeni Model Failed to Render") {}
  };

}

#endif


text:
namespace LionFire.Referencing
{
    public class Listing<T>
    {
        #region Construction

        public Listing() { }
        public Listing(string name, string type = null, string mimeType = null, bool directory = false)
        {
            Name = name;
            Type = type;
            MimeType = mimeType;
            IsDirectory = directory;
        }
        public static implicit operator Listing<T>(string name) => new Listing<T> { Name = name };

        #endregion

        public string Name { get; private set; }

        public string MimeType { get; }
        public bool IsDirectory { get; }

        public IReference UnderlyingReference { get; set; }
        public string RawName { get; set; }

        public string Type { get; set; }

        public override string ToString() => this.ToXamlAttribute();

    }
}


text:
package org.apache.camel.component.netty4.http.rest;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.netty4.http.BaseNettyTest;
import org.junit.Test;

public class RestNettyHttpOptionsTest extends BaseNettyTest {

    @Test
    public void testNettyServerOptions() throws Exception {
        Exchange exchange = template.request("http://localhost:" + getPort() + "/users/v1/customers", new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                exchange.getIn().setHeader(Exchange.HTTP_METHOD, "OPTIONS");
            }
        });

        assertEquals(200, exchange.getOut().getHeader(Exchange.HTTP_RESPONSE_CODE));
        assertEquals("OPTIONS,GET", exchange.getOut().getHeader("ALLOW"));
        assertEquals("", exchange.getOut().getBody(String.class));

        exchange = fluentTemplate.to("http://localhost:" + getPort() + "/users/v1/123").withHeader(Exchange.HTTP_METHOD, "OPTIONS").send();
        assertEquals(200, exchange.getOut().getHeader(Exchange.HTTP_RESPONSE_CODE));
        assertEquals("OPTIONS,PUT", exchange.getOut().getHeader("ALLOW"));
        assertEquals("", exchange.getOut().getBody(String.class));
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                // configure to use netty on localhost with the given port
                restConfiguration().component("netty4-http").host("localhost").port(getPort());

                // use the rest DSL to define the rest services
                rest("/users/")
                    .get("v1/customers")
                        .to("mock:customers")
                    .put("v1/{id}")
                        .to("mock:id");
            }
        };
    }

}


text:
ENV['RACK_ENV'] = 'test'

require 'app'
require 'rspec'
require 'rack/test'

describe 'Galera health check' do
  include Rack::Test::Methods

  def app
    Whazzup.new
  end

  def db_client
    @db_client ||= Mysql2::Client.new(Whazzup.connection_settings)
  end

  before do
    Whazzup.set(:wsrep_state_dir, 'spec/data/3_node_cluster_synced')
    Whazzup.set(:hostname, 'test.local')
  end

  it 'should require and initialize checkers, and make a first check' do
    Whazzup.set(:services, [:xdb])
    expect_any_instance_of(Whazzup).to receive(:require_relative).with 'lib/checkers/galera_health_checker'

    service_checker_class = double
    expect(Whazzup::SERVICE_CHECKERS[:xdb]).to receive(:constantize) { service_checker_class }
    expect(service_checker_class).to receive(:new)

    health_checker = double
    expect(HealthChecker).to receive(:new).once { health_checker }
    expect(health_checker).to receive(:check).once

    app
  end

  it 'should be marked up if it is a a synced node' do
    get '/xdb'
    expect(last_response.status).to be(200)
  end

  it 'should be marked down if it is a donor node' do
    Whazzup.set(:wsrep_state_dir, 'spec/data/3_node_cluster_donor')
    get '/xdb'
    expect(last_response.status).to be(503)
  end

  it 'should be marked up if it is a donor node in a 2 node cluster' do
    Whazzup.set(:wsrep_state_dir, 'spec/data/2_node_cluster_donor')
    get '/xdb'
    expect(last_response.status).to be(200)
  end

  it 'should be marked down if the wsrep state files cannot be read' do
    Whazzup.set(:wsrep_state_dir, 'does/not/exist')
    get '/xdb'
    expect(last_response.status).to be(503)
  end

  it 'should be marked down if it is marked down in the database' do
    begin
      db_client.query("update state set available = 0 where host_name = 'test.local'")

      get '/xdb'
      expect(last_response.status).to be(503)
    ensure
      db_client.query("update state set available = 1 where host_name = 'test.local'")
    end
  end

  it 'should be marked down if no row is found for the desired host in the DB' do
    Whazzup.set(:hostname, 'does.not.exist')

    get '/xdb'
    expect(last_response.status).to be(503)
  end

  it 'should be marked down if there is trouble connecting to the database' do
    allow_any_instance_of(Mysql2::Client).to receive(:query).and_raise(Mysql2::Error, 'mocking connection failure')

    get '/xdb'
    expect(last_response.status).to be(503)
  end

  it 'should support the OPTIONS method for checking health (HAProxy default method)' do
    options '/xdb'
    expect(last_response.status).to be(200)
  end
end


text:
@extends ('layout')

@section ('content')

Standings for {{ $season->season_name }}

@foreach ($season->leagues as $league)

{{ $league->league_name }}

		{!! $league->displayStandingsByWeek($league->gameDays($season)->where('exhibition', false)->get()) !!}

@endforeach

@endsection


text: angular.js examples


text:
<?php

$db = new mysqli('thepark.db.5969281.hostedresource.com','thepark','OIZtRQmFhopZnGgPOofbLGQbENlVcTk6BOQCNX6PgmaunxRqVO@','thepark');

header('Content-Type: application/json');

if ($db->connect_error > 0) {
	die('Connection failed: '. $db->connect_errno);
}

$result = $db->query('SELECT * FROM results');
$teams = array();

while($team = $result->fetch_array()) {
    $teams[] = $team;
}

echo json_encode($teams);

?>


text:
package org.spongepowered.vanilla.applaunch.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/*
 * A class that attempts to parse command line arguments into key value pairs to allow addition and editing.
 * Can not use JOptSimple as that doesn't parse out the values for keys unless the spec says it has a value.
 */
public class ArgumentList {

    private static final Logger LOGGER = LogManager.getLogger();
    private final List<Supplier<String[]>> entries = new ArrayList<>();
    private final Map<String, EntryValue> values = new HashMap<>();

    public static ArgumentList from(final String... args) {
        final ArgumentList ret = new ArgumentList();

        boolean ended = false;
        for (int x = 0; x < args.length; x++) {
            if (!ended) {
                if ("--".equals(args[x])) { // '--' by itself means there are no more arguments
                    ended = true;
                } else if ("-".equals(args[x])) {
                    ret.addRaw(args[x]);
                } else if (args[x].startsWith("-")) {
                    final int idx = args[x].indexOf('=');
                    final String key = idx == -1 ? args[x] : args[x].substring(0, idx);
                    final String value = idx == -1 ? null : idx == args[x].length() - 1 ? "" : args[x].substring(idx + 1);

                    if (idx == -1 && x + 1 < args.length && !args[x + 1].startsWith("-")) { //Not in --key=value, so try and grab the next argument.
                        ret.addArg(true, key, args[x + 1]); //Assume that if the next value is a "argument" then don't use it as a value.
                        x++; // This isn't perfect, but the best we can do without knowing all of the spec.
                    } else {
                        ret.addArg(false, key, value);
                    }
                } else {
                    ret.addRaw(args[x]);
                }
            } else {
                ret.addRaw(args[x]);
            }
        }
        return ret;
    }

    public void addRaw(final String arg) {
        this.entries.add(() -> new String[]{arg});
    }

    public void addArg(final boolean split, final String raw, final String value) {
        final int idx = raw.startsWith("--") ? 2 : 1;
        final String prefix = raw.substring(0, idx);
        final String key = raw.substring(idx);
        final EntryValue entry = new EntryValue(split, prefix, key, value);
        if (this.values.containsKey(key)) {
            ArgumentList.LOGGER.debug("Duplicate entries for " + key + " Unindexable");
        } else {
            this.values.put(key, entry);
        }
        this.entries.add(entry);
    }

    public String[] getArguments() {
        return this.entries.stream()
            .flatMap(e -> Arrays.stream(e.get()))
            .toArray(String[]::new);
    }

    public boolean hasValue(final String key) {
        return this.getOrDefault(key, null) != null;
    }

    public String get(final String key) {
        final EntryValue ent = this.values.get(key);
        return ent == null ? null : ent.getValue();
    }

    public String getOrDefault(final String key, final String value) {
        final EntryValue ent = this.values.get(key);
        return ent == null ? value : ent.getValue() == null ? value : ent.getValue();
    }

    public void put(final String key, final String value) {
        EntryValue entry = this.values.get(key);
        if (entry == null) {
            entry = new EntryValue(true, "--", key, value);
            this.values.put(key, entry);
            this.entries.add(entry);
        } else {
            entry.setValue(value);
        }
    }

    public void putLazy(final String key, final String value) {
        final EntryValue ent = this.values.get(key);
        if (ent == null) {
            this.addArg(true, "--" + key, value);
        } else if (ent.getValue() == null) {
            ent.setValue(value);
        }
    }

    public String remove(final String key) {
        final EntryValue ent = this.values.remove(key);
        if (ent == null) {
            return null;
        }
        this.entries.remove(ent);
        return ent.getValue();
    }

    private static class EntryValue implements Supplier<String[]> {

        private final String prefix;
        private final String key;
        private final boolean split;
        private String value;

        public EntryValue(final boolean split, final String prefix, final String key, final String value) {
            this.split = split;
            this.prefix = prefix;
            this.key = key;
            this.value = value;
        }

        public String getKey() {
            return this.key;
        }

        public String getValue() {
            return this.value;
        }

        public void setValue(final String value) {
            this.value = value;
        }

        @Override
        public String[] get() {
            if (this.getValue() == null) {
                return new String[]{this.prefix + this.getKey()};
            }
            if (this.split) {
                return new String[]{this.prefix + this.getKey(), this.getValue()};
            }
            return new String[]{this.prefix + this.getKey() + '=' + this.getValue()};
        }

        @Override
        public String toString() {
            return String.join(", ", this.get());
        }
    }
}


text:
   /*******************************************************/
   /*      "C" Language Integrated Production System      */
   /*                                                     */
   /*             CLIPS Version 6.24  06/05/06            */
   /*                                                     */
   /*         DEFGLOBAL BASIC COMMANDS HEADER FILE        */
   /*******************************************************/

/*************************************************************/
/* Purpose:                                                  */
/* Principal Programmer(s):                                  */
/*      Gary D. Riley                                        */
/*                                                           */
/* Contributing Programmer(s):                               */
/*      Brian L. Dantes                                      */
/*                                                           */
/* Revision History:                                         */
/*      6.23: Corrected compilation errors for files         */
/*            generated by constructs-to-c. DR0861           */
/*                                                           */
/*      6.24: Renamed BOOLEAN macro type to intBool.         */
/*                                                           */
/*************************************************************/

#ifndef _H_globlbsc
#define _H_globlbsc

#ifndef _H_evaluatn
#include "evaluatn.h"
#endif

#ifdef LOCALE
#undef LOCALE
#endif

#ifdef _GLOBLBSC_SOURCE_
#define LOCALE
#else
#define LOCALE extern
#endif

#define GetDefglobalList(a,b) EnvGetDefglobalList(GetCurrentEnvironment(),a,b)
#define GetDefglobalWatch(a) EnvGetDefglobalWatch(GetCurrentEnvironment(),a)
#define ListDefglobals(a,b) EnvListDefglobals(GetCurrentEnvironment(),a,b)
#define SetDefglobalWatch(a,b) EnvSetDefglobalWatch(GetCurrentEnvironment(),a,b)
#define Undefglobal(a) EnvUndefglobal(GetCurrentEnvironment(),a)

   LOCALE void                           DefglobalBasicCommands(void *);
   LOCALE void                           UndefglobalCommand(void *);
   LOCALE intBool                        EnvUndefglobal(void *,void *);
   LOCALE void                           GetDefglobalListFunction(void *,DATA_OBJECT_PTR);
   LOCALE void                           EnvGetDefglobalList(void *,DATA_OBJECT_PTR,void *);
   LOCALE void                          *DefglobalModuleFunction(void *);
   LOCALE void                           PPDefglobalCommand(void *);
   LOCALE int                            PPDefglobal(void *,char *,char *);
   LOCALE void                           ListDefglobalsCommand(void *);
   LOCALE void                           EnvListDefglobals(void *,char *,void *);
   LOCALE unsigned                       EnvGetDefglobalWatch(void *,void *);
   LOCALE void                           EnvSetDefglobalWatch(void *,unsigned,void *);
   LOCALE void                           ResetDefglobals(void *);

#ifndef _GLOBLBSC_SOURCE_
   extern unsigned                       WatchGlobals;
#endif

#endif


text:
bl_info = {
    "name": "Tomb Raider .SAT file importer",
    "author": "Israel Jacquez",
    "version": (1, 0),
    "blender": (2, 78, 0),
    "location": "File > Import-Export",
    "description": "Import .SAT file",
    "warning": "",
    "wiki_url": "https://github.com/ijacquez/trsat",
    "tracker_url": "https://github.com/ijacquez/trsat/issues",
    "category": "Import-Export"
}

import re
import os
import imp
import math
import struct

import bpy
import bmesh

from mathutils import *
from bpy_extras import io_utils
from bpy.app.handlers import persistent
from bpy.props import StringProperty, BoolProperty

ST_SOLID_RECTANGLE = 0x25
ST_SOLID_TRIANGLE = 0x24
ST_SPRITE = 0x27
ST_TRANSPARENT_RECTANGLE = 0x21
ST_INVISIBLE_RECTANGLE = 0x23
ST_INVISIBLE_TRIANGLE = 0x22

SCALE = 1/256.0

class Header(object):
    def __init__(self, header_data):
        if not isinstance(header_data, tuple):
            raise TypeError("?")
        self.ascii_string_1 = header_data[0]
        self.x = header_data[1] * SCALE
        self.z = header_data[2] * SCALE
        self.y_bottom = header_data[3]
        self.y_top = header_data[4]
        self.ascii_string_2 = header_data[5]
        self.reserved_1 = header_data[6]
        self.door_data_size = header_data[7] * 2
        self.vertex_count = header_data[8]
        self.vertices = header_data[9:9 + self.vertex_count]
        self.surface_count = header_data[9 + self.vertex_count]
        self.surface_type_count = header_data[10 + self.vertex_count]
        self.surfaces = header_data[11 + self.vertex_count:11 + self.vertex_count + self.surface_count]

class Vertex(object):
    def __init__(self, vertex_data):
        if not isinstance(vertex_data, tuple):
            raise TypeError("?")
        self.x = vertex_data[0] * SCALE
        self.y = vertex_data[1] * SCALE
        self.z = vertex_data[2] * SCALE
        self.color = vertex_data[3]

    def __str__(self):
        return "(%i,%i,%i,0x%04X)" % (self.x, self.y, self.z, self.color)

class Rectangle(object):
    def __init__(self, rectangle_data):
        if not isinstance(rectangle_data, tuple):
            raise TypeError("?")
        # Why shift by 4 if each vertex is 8 bytes?
        self.vertices = [(p >> 4) for p in rectangle_data[0:4]]
        self.texture = rectangle_data[4]

    def __str__(self):
        return "(%i,%i,%i,%i,0x%04X)" % (self.vertices[0],
                                         self.vertices[1],
                                         self.vertices[2],
                                         self.vertices[3],
                                         self.texture)

class Triangle(object):
    def __init__(self, triangle_data):
        if not isinstance(triangle_data, tuple):
            raise TypeError("?")
        # Why shift by 4 if each vertex is 8 bytes?
        self.vertices = [(p >> 4) for p in triangle_data[0:3]]
        self.texture = triangle_data[3]

    def __str__(self):
        return "(%i,%i,%i,0x%04X)" % (self.vertices[0],
                                      self.vertices[1],
                                      self.vertices[2],
                                      self.texture)

class SurfaceType(object):
    def __init__(self, surface_type_data):
        if not isinstance(surface_type_data, tuple):
            raise TypeError("?")
        self.id = surface_type_data[0]
        self.surface_count = surface_type_data[1]
        self.surfaces = surface_type_data[2:2 + self.surface_count]

    def __str__(self):
        return ""

def create_mesh(offset, fp):
    fp.seek(offset, 0)
    header_data = ()
    header_data += struct.unpack('>8s' + # ASCII string
                                 'i' +   # X-offset of room
                                 'i' +   # Z-offset of room
                                 'i' +   # Y-offset of room's floor
                                 'i' +   # Y-offset of room's ceiling
                                 '8s' +  # ASCII string
                                 'i' +   # Integer that's always 0x00000002
                                 'i' +   # Number of bytes to "DOORDATA" divided by 2
                                 'H',    # Number of vertices
                                 fp.read(42))
    vertices = []
    for vertex_id in range(header_data[8]):
        vertex_data = struct.unpack('>h' + # X-offset of vertex (local coordinates)
                                    'h' +  # Y-offset of vertex (local coordinates)
                                    'h' +  # Z-offset of vertex (local coordinates)
                                    'H',   # 16-bit BGR
                                    fp.read(8))
        vertex = Vertex(vertex_data)
        vertices.append(vertex)
    header_data += tuple(vertices)

    header_data += struct.unpack('>H' + # Total number of surfaces in the room
                                 'H',   # Total number of surface types
                                 fp.read(4))
    surfaces = []
    for surface_type_id in range(header_data[10 + header_data[8]]):
        surface_type_data = struct.unpack('>H' + # Type of surface type
                                          'H',   # Number of surfaces of this type
                                          fp.read(4))
        for surface_idx in range(surface_type_data[1]):
            surface = None
            if (surface_type_data[0] == ST_TRANSPARENT_RECTANGLE):
                surface_data = struct.unpack('>HHHH' + # Indices in the vertex list
                                             'H',      # Texture index
                                             fp.read(10))
                surface = Rectangle(surface_data)
            elif (surface_type_data[0] == ST_INVISIBLE_TRIANGLE):
                pass
            elif (surface_type_data[0] == ST_INVISIBLE_RECTANGLE):
                pass
            elif (surface_type_data[0] == ST_SOLID_TRIANGLE):
                surface_data = struct.unpack('>HHH' + # Indices in the vertex list
                                             'H',     # Texture index
                                             fp.read(8))
                surface = Triangle(surface_data)
            elif (surface_type_data[0] == ST_SOLID_RECTANGLE):
                surface_data = struct.unpack('>HHHH' + # Indices in the vertex list
                                             'H',      # Texture index
                                             fp.read(10))
                surface = Rectangle(surface_data)
            elif (surface_type_data[0] == ST_SPRITE):
                pass
            if surface is not None:
                surfaces.append(surface)
    header_data += tuple(surfaces)

    header = Header(header_data)
    print("0x%04X" % (offset))
    print("vertex count: ", header.vertex_count)
    print("surface count: ", header.surface_count)
    print("surface type count: ", header.surface_type_count)
    print("len(surfaces): ", len(header.surfaces))

    name = "o_0x%04X" % (offset)
    me = bpy.data.meshes.new(name + '_mesh')
    new_bmesh = bmesh.new()

    rotate_axis = lambda angle, axis: Matrix.Rotation(math.radians(angle), 4, axis).decompose()[1]

    rot_y = rotate_axis(180.0, 'Y')
    rot_x = rotate_axis(90.0, 'X')

    for vertex in header.vertices:
        v = Vector((vertex.x, vertex.y, vertex.z))
        pv = (rot_y * rot_x) * v
        new_bmesh.verts.new(pv[:])
    new_bmesh.verts.index_update()
    new_bmesh.verts.ensure_lookup_table()
    for surface in header.surfaces:
        indices = [new_bmesh.verts[i] for i in surface.vertices]
        new_bmesh.faces.new(indices)
    new_bmesh.to_mesh(me)
    new_bmesh.free()

    ob = bpy.data.objects.new(name, me)

    loc = (rot_y * rot_x) * Vector((header.x, 0.0, header.z))

    ob.location = loc[:]
    ob.show_name = True

    # Link object to scene and make active
    scene = bpy.context.scene
    scene.objects.link(ob)
    scene.objects.active = ob

    ob.select = True

class ImportTombRaiderSAT(bpy.types.Operator, io_utils.ImportHelper):
    bl_idname = "import_scene.tomb_raider_sat_file"
    bl_label = "Import Tomb Raider (.SAT)"
    bl_description = "Import Tomb Raider (.SAT) file"
    bl_options = {'REGISTER', 'UNDO'}

    use_filter = BoolProperty(default = True, options = {'HIDDEN'})

    # use filter to show only the SAT files in a directory
    filename_ext = ".sat"
    filter_glob = StringProperty(default = "*.sat", options = {'HIDDEN'})

    def execute(self, context):
        try:
            base_path = os.path.dirname(self.filepath)

            # Ugly, remove... this finds all the MESHPOS
            offsets = []
            first_offset = 0
            with open(self.filepath, mode = 'rb') as fp:
                data = fp.read()
                while data != []:
                    try:
                        offset = data.index(str.encode('MESHPOS '))
                        real_offset = offset + first_offset
                        offsets.append(real_offset)
                        print("==> 0x%04X" % (real_offset))
                        first_offset += offset + 8
                        data = data[offset + 8:]
                    except:
                        break

            with open(self.filepath, mode = 'rb') as fp:
                for offset in offsets:
                    create_mesh(offset, fp)
            return {'FINISHED'}
        except (ValueError, RuntimeError) as e:
            self.report({'ERROR'}, "%s" % (e))
            return {'CANCELLED'}
        return {'FINISHED'}

def menu_import_tomb_raider_sat(self, context):
    self.layout.operator(ImportTombRaiderSAT.bl_idname, text = ImportTombRaiderSAT.bl_label)

def register():
    bpy.utils.register_class(ImportTombRaiderSAT)
    bpy.types.INFO_MT_file_import.append(menu_import_tomb_raider_sat)

def unregister():
    bpy.utils.unregister_class(ImportTombRaiderSAT)
    bpy.types.INFO_MT_file_import.remove(menu_import_tomb_raider_sat)

if __name__ == '__main__':
    register()


text:
using UnityEngine;
using UnityEngine.UI;

namespace revisual.pipit
{
    using System;
    using data;
    public class FlickBook : MonoBehaviour, IProgressReciever
    {
        public BookModel model;
        private RawImage _baseImage;
        private RawImage _overlayImage;
        private bool _imageSet;

        public void Awake()
        {
            _baseImage = transform.Find("BasePanel").GetComponent<RawImage>();
            _overlayImage = transform.Find("OverlayPanel").GetComponent<RawImage>();

            model.aspectRatioResolved.AddOnce(
                aspectRatio =>
                            {
                                transform.Find("BasePanel").GetComponent<AspectRatioFitter>().aspectRatio = aspectRatio;
                                transform.Find("OverlayPanel").GetComponent<AspectRatioFitter>().aspectRatio = aspectRatio;
                                model.SetImageAtIndex(_baseImage, 0);
                            });
        }

        public void OnProgress(float prog)
        {
            model.SetAlphaAtIndex(_baseImage, prog);
        }

        private IBook _book;
        private float _currentPosition;
        private int _currentIndex;
        private float _currentAlpha;

        public void Update()
        {
            model.SetBaseImage(_baseImage);
            model.SetOverlayImage(_overlayImage);
        }

    }
}


text:
import invariant from "invariant";
import TinyQueue from "tinyqueue";

// Push promises onto a queue with a priority.
// Run a given number of jobs in parallel
// Useful for prioritizing network requests
export default class LoadQueue {
  constructor({ threads }) {
    // TODO: Consider not running items with zero priority
    // Priority is a function so that items can change their priority between
    // when their priority is evaluated.
    // For example, we might add a track to the playlist and then scroll to/away
    // from it before it gets processed.
    this._queue = new TinyQueue([], (a, b) => a.priority() - b.priority());
    this._availableThreads = threads;
  }

  push(task, priority) {
    const t = { task, priority };
    this._queue.push(t);
    // Wait until the next event loop to pick a task to run. This way, we can
    // enqueue multiple items in an event loop, and be sure they will be run in
    // priority order.
    setTimeout(() => {
      this._run();
    }, 0);
    return () => {
      // TODO: Could return a boolean representing if the task has already been
      // kicked off.
      this._queue = this._queue.filter((t1) => t1 !== t);
    };
  }

  _run() {
    while (this._availableThreads > 0) {
      if (this._queue.length === 0) {
        return;
      }
      this._availableThreads--;
      const t = this._queue.pop();
      const promise = t.task();
      invariant(
        typeof promise.then === "function",
        `LoadQueue only supports loading Promises. Got ${promise}`
      );
      promise.then(() => {
        this._availableThreads++;
        this._run();
      });
    }
  }
}


text:
<?php

interface __IConditionalFlowTransition extends __IFlowTransition {

    public function evaluateCondition();

}


text:
"""
Module for parsing JSON files
"""

import json

class JSONParser:
    """
    The base class for parsing JSON files
    """

    def __init__(self, path):
        """
        Constructor

        Args:
            self(JSONParser): the JSON parser
            path(Str): The file path to read JSON data from
        """
        self._path = path
        self._data = None
        self._readfile()

    def _readfile(self):
        """
        Reads the data from the JSON file associated with the JSON parser

        Args:
            self(JSONParser): the JSON parser

        Returns:
            Dict: A dictionary representation of the JSON data
        """
        try:
            with open(self._path, "r+") as datafile:
                self._data = json.load(datafile)
        except json.JSONDecodeError:
            # TODO: Improve error handling
            print("could not decode JSON")
            self._data = {}
        except FileNotFoundError:
            open(self._path, 'w')
            self._data = {}

    def getdata(self):
        """
        Returns the data associated with the JSON file of the JSON parser

        Args:
            self(JSONParser): the JSON parser

        Returns:
            Dict: A dictionary representation of the JSON data
        """
        return self._data

    def savedata(self, savedata=None):
        """
        Saves the input data to the JSON file of the JSON parser
        Saves the current data of the parser if no input data is given

        Args:
            self(JSONParser): the JSON parser
            savedata(Dict): the JSON data to be saved to file
        """
        if savedata is None:
            # TODO: save current class data to the JSON file at path
            pass
        else:
            # TODO: save the input data to the JSON file at path
            pass


text:
////////////////////////////////////////////////////////////////////////////////
//
// QLabel.h
//
// Copyright (c) 2016 Semenyakin Vladimir (semenyakinVS@gmail.com)
//
// Distributed under the MIT (See accompanying file LICENSE.txt or copy at
// https://opensource.org/licenses/MIT)
//
///////////////////////////////////////////////////////////////////////////////
#ifndef QLABEL_H_
#define QLABEL_H_

///////////////////////////////////////////////////////////////////////////////
#include "QFrame.h"

///////////////////////////////////////////////////////////////////////////////
class QLabel : public QFrame {
	CPPRT_DECLARATION(QLabel);

public:
	QLabel();
	virtual ~QLabel();

	virtual QLabel *dcastQLabel() { return this; }
};

///////////////////////////////////////////////////////////////////////////////
#endif /* QLABEL_H_ */


text:
"use strict";
var assert = require('assert');
var helper = require("../helper.js");
var shell = require('shelljs');
var sampleData = require("soajs.mongodb.data/modules/proxy");
var proxy;

describe("importing sample data", function () {

	it("do import", function (done) {
		shell.pushd(sampleData.dir);
		shell.exec("chmod +x " + sampleData.shell, function (code) {
			assert.equal(code, 0);
			shell.exec(sampleData.shell, function (code) {
				assert.equal(code, 0);
				shell.popd();
				done();
			});
		});
	});

	it("starting pre servers", function (done) {
		console.log('test data imported.');
		proxy = helper.requireModule('./index');
		setTimeout(function () {
			done();
		}, 2000);
	});

	it("Running Tests", function(done){
		require("./soajs.proxy.test.js");
		done();
	});
});


text:
<?php

namespace Newscoop\Router;

/**
 * Zend Router wrapper for setting in container.
 */
class RouterFactory
{
    public static function initRouter($container) {
        $front = \Zend_Controller_Front::getInstance();
        $router = $front->getRouter();

        $router->addRoute(
            'admin',
            new \Zend_Controller_Router_Route(
                'admin/:controller/:action/*',
                array(
                    'module' => 'admin',
                    'controller' => 'legacy',
                    'action' => 'index',
                )
            )
        );

        $router->addDefaultRoutes();

        $router->addRoute(
            'content',
            new \Zend_Controller_Router_Route(':language/:issue/:section/:articleNo/:articleUrl', array(
                'module' => 'default',
                'controller' => 'legacy',
                'action' => 'index',
                'articleUrl' => null,
                'articleNo' => null,
                'section' => null,
                'issue' => null,
                'language' => null,
            ), array(
                'language' => '[a-z]{2}',
            ))
        );

        $router->addRoute(
            'confirm-email',
            new \Zend_Controller_Router_Route('confirm-email/:user/:token', array(
                'module' => 'default',
                'controller' => 'register',
                'action' => 'confirm',
            ))
        );

        $router->addRoute(
            'topic',
            new \Zend_Controller_Router_Route(':language/topic/:id/:topicName', array(
                'module' => 'default',
                'controller' => 'topic',
                'action' => 'articles',
                'topicName' => null,
            ), array(
                'language' => '[a-z]{2}',
            ))
        );

        $router->addRoute(
            'author',
            new \Zend_Controller_Router_Route('author/:author', array(
                'module' => 'default',
                'controller' => 'author',
                'action' => 'profile',
            ))
        );

        $router->addRoute(
            'user',
            new \Zend_Controller_Router_Route('user/profile/:username/:action', array(
                'module' => 'default',
                'controller' => 'user',
                'action' => 'profile',
            ))
        );

        $router->addRoute(
            'author',
            new \Zend_Controller_Router_Route('author/:author', array(
                'module' => 'default',
                'controller' => 'author',
                'action' => 'profile',
            ))
        );

        $image = $container->getParameter('image');
        $router->addRoute('image',
            new \Zend_Controller_Router_Route_Regex($image['cache_url'] . '/(.*)', array(
                'module' => 'default',
                'controller' => 'image',
                'action' => 'cache',
            ), array(
                1 => 'src',
            ), $image['cache_url'] . '/%s')
        );

        $router->addRoute('rest',
            new \Zend_Rest_Route($front, array(), array(
                'admin' => array(
                    'slideshow-rest',
                    'subscription-rest',
                    'subscription-section-rest',
                    'subscription-ip-rest',
                ),
            ))
        );

        $router->addRoute(
            'search',
            new \Zend_Controller_Router_Route(
                ':language/search',
                array(
                    'module' => 'default',
                    'controller' => 'search',
                    'action' => 'index',
                    'language' => null,
                ), array(
                    'language' => '[a-z]{2}',
                )
            )
        );

        return $router;
    }
}


text:
using Workbench.Core.Models;

namespace Workbench.Messages
{
    /// <summary>
    /// Message sent when a new aggregate variable is added to the model.
    /// </summary>
    public class AggregateVariableAddedMessage : WorkspaceChangedMessage
    {
        /// <summary>
        /// Initialize the new aggregate added message with the new aggregate variable.
        /// </summary>
        /// <param name="newVariable"></param>
        public AggregateVariableAddedMessage(AggregateVariableModel newVariable)
        {
            Added = newVariable;
        }

        /// <summary>
        /// Gets the new aggregate variable.
        /// </summary>
        public AggregateVariableModel Added { get; private set; }

        /// <summary>
        /// Gets the new aggregate variable name.
        /// </summary>
        public string NewVariableName
        {
            get
            {
                return Added.Name;
            }
        }
    }
}


text:
using System;
using System.Runtime.InteropServices;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
    /// <summary>
    /// This allows us to get pNode as an IntPtr instead of a via a RCW. Otherwise, a second
    /// invocation of the same snippet may cause an AccessViolationException.
    /// </summary>
    [Guid("3DFA7603-3B51-4484-81CD-FF1470123C7C")]
    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IVsExpansionSessionInternal
    {
        void Reserved1();
        void Reserved2();
        void Reserved3();
        void Reserved4();
        void Reserved5();
        void Reserved6();
        void Reserved7();
        void Reserved8();

        /// <summary>
        /// WARNING: Marshal pNode with GetUniqueObjectForIUnknown and call ReleaseComObject on it
        /// before leaving the calling method.
        /// </summary>
        [PreserveSig]
        int GetSnippetNode([MarshalAs(UnmanagedType.BStr)] string bstrNode, out IntPtr pNode);

        void Reserved9();
        void Reserved10();
        void Reserved11();
    }
}


text:
Projects = new Meteor.Collection('projects');

Tags.TagsMixin(Projects);
Projects.allowTags(function (userId, doc) {
	return roles.isAdmin() || userId === doc.owner;
});

Comments = new Meteor.Collection('comments');

Notifications = new Meteor.Collection('notifications');

Settings = new Meteor.Collection('settings');

Tasks = new Meteor.Collection('tasks');

Offers = new Meteor.Collection('offers');


text:
namespace Fixtures.Azure.AcceptanceTestsPaging
{
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;

    /// <summary>
    /// Long-running Operation for AutoRest
    /// </summary>
    public partial interface IAutoRestPagingTestService : IDisposable
    {
        /// <summary>
        /// The base URI of the service.
        /// </summary>
        Uri BaseUri { get; set; }

        /// <summary>
        /// Gets or sets json serialization settings.
        /// </summary>
        JsonSerializerSettings SerializationSettings { get; }

        /// <summary>
        /// Gets or sets json deserialization settings.
        /// </summary>
        JsonSerializerSettings DeserializationSettings { get; }

        /// <summary>
        /// The management credentials for Azure.
        /// </summary>
        ServiceClientCredentials Credentials { get; }

        /// <summary>
        /// Gets or sets the preferred language for the response.
        /// </summary>
        string AcceptLanguage { get; set; }

        /// <summary>
        /// The retry timeout for Long Running Operations.
        /// </summary>
        int? LongRunningOperationRetryTimeout { get; set; }

        IPagingOperations Paging { get; }

    }
}


text:
Greeting !!!

#eTechBuddy.com is Arya'sportfolio and blogging site.

About Us

Portfolio

Blog

Contact


text:
Collection of Deep Reinforcement Learning algorithms.

Dependencies:

* [Tensorflow 1.3.0](https://www.tensorflow.org/install/)
* [tflearn](http://tflearn.org/installation/)
* [OpenAI Gym 0.9.2](https://github.com/openai/gym/)

Tested with Python 2.7 and Python 3.6

So far:

1. DDPG - Deep Deterministic Policy Gradients, evaluated on the Pendulum-v0 environment in OpenAI Gym.

## Places where this code has been used

If you have used this code to do something cool, send me a link and a GIF (via email or pull request) and I'll add it

1. @keithmgould [used the same the DDPG code](https://github.com/keithmgould/deep-rl) to solve the inverted Pendulum task in Roboschool. ![InvertedPendulum demo](https://raw.githubusercontent.com/keithmgould/deep-rl/master/demo.gif)
2. @janscholten [Deep Reinforcement Learning with Feedback-based Exploration](https://arxiv.org/abs/1903.06151) [[code]](https://github.com/janscholten/ppmp)


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<title>VHŘB | Blog</title>

	<meta name="description" content="Blog about everything">
	<meta name="author" content="Michal Dobrovolný">

	<link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon">
	<link rel="icon" href="img/favicon.ico" type="image/x-icon">

	<link href='http://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
	<link href='http://fonts.googleapis.com/css?family=PT+Serif' rel='stylesheet' type='text/css'>

	<link href="css/default.css" rel="stylesheet" type="text/css" media="all">
	<link href="css/print.css" rel="stylesheet" type="text/css" media="print">
	<link href="css/blog.css" rel="stylesheet" type="text/css" media="all">

			vhrb.cz

work

about

contact

blog

Why use https on your website?!

			2015-02-27 10:30 AM

				What is motivation for use HTTPS? This web is static and hasn't any login form or other personal data. Read more.

Apache vs Nginx

			2015-03-01 11:22 AM

				"Apache has longer history." "Nginx is more stable." Then what is better? How to make choice? Read more.

	© vhrb.cz


text:
package tabletserver

import (
	"encoding/json"
	"fmt"
	"html/template"
	"net/url"
	"strings"
	"time"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/sqltypes"
	"github.com/youtube/vitess/go/streamlog"
	"github.com/youtube/vitess/go/vt/callinfo"
	"golang.org/x/net/context"
)

// SqlQueryLogger is the main stream logger object
var SqlQueryLogger = streamlog.New("SqlQuery", 50)

const (
	// QuerySourceRowcache means query result is found in rowcache.
	QuerySourceRowcache = 1 << iota
	// QuerySourceConsolidator means query result is found in consolidator.
	QuerySourceConsolidator
	// QuerySourceMySQL means query result is returned from MySQL.
	QuerySourceMySQL
)

// SQLQueryStats records the stats for a single query
type SQLQueryStats struct {
	Method               string
	PlanType             string
	OriginalSql          string
	BindVariables        map[string]interface{}
	rewrittenSqls        []string
	RowsAffected         int
	NumberOfQueries      int
	StartTime            time.Time
	EndTime              time.Time
	MysqlResponseTime    time.Duration
	WaitingForConnection time.Duration
	CacheHits            int64
	CacheAbsent          int64
	CacheMisses          int64
	CacheInvalidations   int64
	QuerySources         byte
	Rows                 [][]sqltypes.Value
	TransactionID        int64
	ctx                  context.Context
	Error                error
}

func newSqlQueryStats(methodName string, ctx context.Context) *SQLQueryStats {
	return &SQLQueryStats{
		Method:    methodName,
		StartTime: time.Now(),
		ctx:       ctx,
	}
}

// Send finalizes a record and sends it
func (stats *SQLQueryStats) Send() {
	stats.EndTime = time.Now()
	SqlQueryLogger.Send(stats)
}

// AddRewrittenSql adds a single sql statement to the rewritten list
func (stats *SQLQueryStats) AddRewrittenSql(sql string, start time.Time) {
	stats.QuerySources |= QuerySourceMySQL
	stats.NumberOfQueries++
	stats.rewrittenSqls = append(stats.rewrittenSqls, sql)
	stats.MysqlResponseTime += time.Now().Sub(start)
}

// TotalTime returns how long this query has been running
func (stats *SQLQueryStats) TotalTime() time.Duration {
	return stats.EndTime.Sub(stats.StartTime)
}

// RewrittenSql returns a semicolon separated list of SQL statements
// that were executed.
func (stats *SQLQueryStats) RewrittenSql() string {
	return strings.Join(stats.rewrittenSqls, "; ")
}

// SizeOfResponse returns the approximate size of the response in
// bytes (this does not take in account BSON encoding). It will return
// 0 for streaming requests.
func (stats *SQLQueryStats) SizeOfResponse() int {
	if stats.Rows == nil {
		return 0
	}
	size := 0
	for _, row := range stats.Rows {
		for _, field := range row {
			size += len(field.Raw())
		}
	}
	return size
}

// FmtBindVariables returns the map of bind variables as JSON. For
// values that are strings or byte slices it only reports their type
// and length.
func (stats *SQLQueryStats) FmtBindVariables(full bool) string {
	var out map[string]interface{}
	if full {
		out = stats.BindVariables
	} else {
		// NOTE(szopa): I am getting rid of potentially large bind
		// variables.
		out = make(map[string]interface{})
		for k, v := range stats.BindVariables {
			switch val := v.(type) {
			case string:
				out[k] = fmt.Sprintf("string %v", len(val))
			case []byte:
				out[k] = fmt.Sprintf("bytes %v", len(val))
			default:
				out[k] = v
			}
		}
	}
	b, err := json.Marshal(out)
	if err != nil {
		log.Warningf("could not marshal %q", stats.BindVariables)
		return ""
	}
	return string(b)
}

// FmtQuerySources returns a comma separated list of query
// sources. If there were no query sources, it returns the string
// "none".
func (stats *SQLQueryStats) FmtQuerySources() string {
	if stats.QuerySources == 0 {
		return "none"
	}
	sources := make([]string, 3)
	n := 0
	if stats.QuerySources&QuerySourceMySQL != 0 {
		sources[n] = "mysql"
		n++
	}
	if stats.QuerySources&QuerySourceRowcache != 0 {
		sources[n] = "rowcache"
		n++
	}
	if stats.QuerySources&QuerySourceConsolidator != 0 {
		sources[n] = "consolidator"
		n++
	}
	return strings.Join(sources[:n], ",")
}

// ContextHTML returns the HTML version of the context that was used, or "".
// This is a method on SQLQueryStats instead of a field so that it doesn't need
// to be passed by value everywhere.
func (stats *SQLQueryStats) ContextHTML() template.HTML {
	return callinfo.HTMLFromContext(stats.ctx)
}

// ErrorStr returns the error string or ""
func (stats *SQLQueryStats) ErrorStr() string {
	if stats.Error != nil {
		return stats.Error.Error()
	}
	return ""
}

// RemoteAddrUsername returns some parts of CallInfo if set
func (stats *SQLQueryStats) RemoteAddrUsername() (string, string) {
	ci, ok := callinfo.FromContext(stats.ctx)
	if !ok {
		return "", ""
	}
	return ci.RemoteAddr(), ci.Username()
}

// Format returns a tab separated list of logged fields.
func (stats *SQLQueryStats) Format(params url.Values) string {
	_, fullBindParams := params["full"]

	remoteAddr, username := stats.RemoteAddrUsername()
	return fmt.Sprintf(
		"%v\t%v\t%v\t%v\t%v\t%.6f\t%v\t%q\t%v\t%v\t%q\t%v\t%.6f\t%.6f\t%v\t%v\t%v\t%v\t%v\t%v\t%q\t\n",
		stats.Method,
		remoteAddr,
		username,
		stats.StartTime.Format(time.StampMicro),
		stats.EndTime.Format(time.StampMicro),
		stats.TotalTime().Seconds(),
		stats.PlanType,
		stats.OriginalSql,
		stats.FmtBindVariables(fullBindParams),
		stats.NumberOfQueries,
		stats.RewrittenSql(),
		stats.FmtQuerySources(),
		stats.MysqlResponseTime.Seconds(),
		stats.WaitingForConnection.Seconds(),
		stats.RowsAffected,
		stats.SizeOfResponse(),
		stats.CacheHits,
		stats.CacheMisses,
		stats.CacheAbsent,
		stats.CacheInvalidations,
		stats.ErrorStr(),
	)
}