text:
pc.extend(pc, function () {
    // Shared math variable to avoid excessive allocation
    var transform = new pc.Mat4();
    var newWtm = new pc.Mat4();

    var position = new pc.Vec3();
    var rotation = new pc.Vec3();
    var scale = new pc.Vec3();

    var ammoRayStart, ammoRayEnd;

    var collisions = {};
    var frameCollisions = {};

    /**
    * @name pc.RaycastResult
    * @class Object holding the result of a successful raycast hit
    * @constructor Create a new RaycastResul
    * @param {pc.Entity} entity The entity that was hit
    * @param {pc.Vec3} point The point at which the ray hit the entity in world space
    * @param {pc.Vec3} normal The normal vector of the surface where the ray hit in world space.
    * @property {pc.Entity} entity The entity that was hit
    * @property {pc.Vec3} point The point at which the ray hit the entity in world space
    * @property {pc.Vec3} normal The normal vector of the surface where the ray hit in world space.
    */
    var RaycastResult = function RaycastResult(entity, point, normal) {
        this.entity = entity;
        this.point = point;
        this.normal = normal;
    };

    /**
    * @name pc.SingleContactResult
    * @class Object holding the result of a contact between two rigid bodies
    * @constructor Create a new SingleContactResult
    * @param {pc.Entity} a The first entity involved in the contact
    * @param {pc.Entity} b The second entity involved in the contact
    * @param {pc.ContactPoint} contactPoint The contact point between the two entities
    * @property {pc.Entity} a The first entity involved in the contact
    * @property {pc.Entity} b The second entity involved in the contact
    * @property {pc.Vec3} localPointA The point on Entity A where the contact occured, relative to A
    * @property {pc.Vec3} localPointB The point on Entity B where the contact occured, relative to B
    * @property {pc.Vec3} pointA The point on Entity A where the contact occured, in world space
    * @property {pc.Vec3} pointB The point on Entity B where the contact occured, in world space
    * @property {pc.Vec3} normal The normal vector of the contact on Entity B, in world space
    */
    var SingleContactResult = function SingleContactResult(a, b, contactPoint) {
        if (arguments.length === 0) {
            this.a = null;
            this.b = null;
            this.localPointA = new pc.Vec3();
            this.localPointB = new pc.Vec3();
            this.pointA = new pc.Vec3();
            this.pointB = new pc.Vec3();
            this.normal = new pc.Vec3();
        } else {
            this.a = a;
            this.b = b;
            this.localPointA = contactPoint.localPoint;
            this.localPointB = contactPoint.localPointOther;
            this.pointA = contactPoint.point;
            this.pointB = contactPoint.pointOther;
            this.normal = contactPoint.normal;
        }
    };

    /**
    * @name pc.ContactPoint
    * @class Object holding the result of a contact between two Entities.
    * @constructor Create a new ContactPoint
    * @param {pc.Vec3} localPoint The point on the entity where the contact occured, relative to the entity
    * @param {pc.Vec3} localPointOther The point on the other entity where the contact occured, relative to the other entity
    * @param {pc.Vec3} point The point on the entity where the contact occured, in world space
    * @param {pc.Vec3} pointOther The point on the other entity where the contact occured, in world space
    * @param {pc.Vec3} normal The normal vector of the contact on the other entity, in world space
    * @property {pc.Vec3} localPoint The point on the entity where the contact occured, relative to the entity
    * @property {pc.Vec3} localPointOther The point on the other entity where the contact occured, relative to the other entity
    * @property {pc.Vec3} point The point on the entity where the contact occured, in world space
    * @property {pc.Vec3} pointOther The point on the other entity where the contact occured, in world space
    * @property {pc.Vec3} normal The normal vector of the contact on the other entity, in world space
    */
    var ContactPoint = function ContactPoint(localPoint, localPointOther, point, pointOther, normal) {
        if (arguments.length === 0) {
            this.localPoint = new pc.Vec3();
            this.localPointOther = new pc.Vec3();
            this.point = new pc.Vec3();
            this.pointOther = new pc.Vec3();
            this.normal = new pc.Vec3();
        } else {
            this.localPoint = localPoint;
            this.localPointOther = localPointOther;
            this.point = point;
            this.pointOther = pointOther;
            this.normal = normal;
        }
    }

    /**
    * @name pc.ContactResult
    * @class Object holding the result of a contact between two Entities
    * @constructor Create a new ContactResult
    * @param {pc.Entity} other The entity that was involved in the contact with this entity
    * @param {pc.ContactPoint[]} contacts An array of ContactPoints with the other entity
    * @property {pc.Entity} other The entity that was involved in the contact with this entity
    * @property {pc.ContactPoint[]} contacts An array of ContactPoints with the other entity
    */
    var ContactResult = function ContactResult(other, contacts) {
        this.other = other;
        this.contacts = contacts;
    }

    // Events Documentation
    /**
    * @event
    * @name pc.RigidBodyComponentSystem#contact
    * @description Fired when a contact occurs between two rigid bodies
    * @param {pc.SingleContactResult} result Details of the contact between the two bodies
    */

    /**
     * @name pc.RigidBodyComponentSystem
     * @constructor Create a new RigidBodyComponentSystem
     * @class The RigidBodyComponentSystem maintains the dynamics world for simulating rigid bodies, it also controls global values for the world such as gravity.
     * Note: The RigidBodyComponentSystem is only valid if 3D Physics is enabled in your application. You can enable this in the application settings for your Depot.
     * @param {pc.Application} app The Application
     * @extends pc.ComponentSystem
     */
    var RigidBodyComponentSystem = function RigidBodyComponentSystem (app) {
        this.id = 'rigidbody';
        this.description = "Adds the entity to the scene's physical simulation.";
        app.systems.add(this.id, this);
        this._stats = app.stats.frame;

        this.ComponentType = pc.RigidBodyComponent;
        this.DataType = pc.RigidBodyComponentData;

        this.contactPointPool = new pc.AllocatePool(ContactPoint, 1);
        this.contactResultPool = new pc.AllocatePool(ContactResult, 1);
        this.singleContactResultPool = new pc.AllocatePool(SingleContactResult, 1);

        this.schema = [
            'enabled',
            'type',
            'mass',
            'linearDamping',
            'angularDamping',
            'linearFactor',
            'angularFactor',
            'friction',
            'restitution',
            'group',
            'mask',
            'body'
        ];

        this.maxSubSteps = 10;
        this.fixedTimeStep = 1/60;

        this.on('remove', this.onRemove, this);
    };
    RigidBodyComponentSystem = pc.inherits(RigidBodyComponentSystem, pc.ComponentSystem);

    pc.extend(RigidBodyComponentSystem.prototype, {
        onLibraryLoaded: function () {
            // Create the Ammo physics world
            if (typeof Ammo !== 'undefined') {
                var collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
                var dispatcher = new Ammo.btCollisionDispatcher(collisionConfiguration);
                var overlappingPairCache = new Ammo.btDbvtBroadphase();
                var solver = new Ammo.btSequentialImpulseConstraintSolver();
                this.dynamicsWorld = new Ammo.btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);

                this._ammoGravity = new Ammo.btVector3(0, -9.82, 0);
                this.dynamicsWorld.setGravity(this._ammoGravity);

                // Lazily create temp vars
                ammoRayStart = new Ammo.btVector3();
                ammoRayEnd = new Ammo.btVector3();
                pc.ComponentSystem.on('update', this.onUpdate, this);
            } else {
                // Unbind the update function if we haven't loaded Ammo by now
                pc.ComponentSystem.off('update', this.onUpdate, this);
            }
        },

        initializeComponentData: function (component, _data, properties) {
            properties = ['enabled', 'mass', 'linearDamping', 'angularDamping', 'linearFactor', 'angularFactor', 'friction', 'restitution', 'type', 'group', 'mask'];

            // duplicate the input data because we are modifying it
            var data = {};
            properties.forEach(function (prop) {
                data[prop] = _data[prop];
            })

            // backwards compatibility
            if (_data.bodyType) {
                data.type = _data.bodyType;
                console.warn("WARNING: rigidbody.bodyType: Property is deprecated. Use type instead.");
            }

            if (data.linearFactor && pc.type(data.linearFactor) === 'array') {
                data.linearFactor = new pc.Vec3(data.linearFactor[0], data.linearFactor[1], data.linearFactor[2]);
            }
            if (data.angularFactor && pc.type(data.angularFactor) === 'array') {
                data.angularFactor = new pc.Vec3(data.angularFactor[0], data.angularFactor[1], data.angularFactor[2]);
            }

            RigidBodyComponentSystem._super.initializeComponentData.call(this, component, data, properties);
        },

        cloneComponent: function (entity, clone) {
            // create new data block for clone
            var data = {
                enabled: entity.rigidbody.enabled,
                mass: entity.rigidbody.mass,
                linearDamping: entity.rigidbody.linearDamping,
                angularDamping: entity.rigidbody.angularDamping,
                linearFactor: [entity.rigidbody.linearFactor.x, entity.rigidbody.linearFactor.y, entity.rigidbody.linearFactor.z],
                angularFactor: [entity.rigidbody.angularFactor.x, entity.rigidbody.angularFactor.y, entity.rigidbody.angularFactor.z],
                friction: entity.rigidbody.friction,
                restitution: entity.rigidbody.restitution,
                type: entity.rigidbody.type,
                group: entity.rigidbody.group,
                mask: entity.rigidbody.mask
            };

            this.addComponent(clone, data);
        },

        onRemove: function (entity, data) {
            if (data.body) {
                this.removeBody(data.body);
                Ammo.destroy(data.body);
            }

            data.body = null;
        },

        addBody: function (body, group, mask) {
            if (group !== undefined && mask !== undefined) {
                this.dynamicsWorld.addRigidBody(body, group, mask);
            } else {
                this.dynamicsWorld.addRigidBody(body);
            }

            return body;
        },

        removeBody: function (body) {
            this.dynamicsWorld.removeRigidBody(body);
        },

        addConstraint: function (constraint) {
            this.dynamicsWorld.addConstraint(constraint);
            return constraint;
        },

        removeConstraint: function (constraint) {
            this.dynamicsWorld.removeConstraint(constraint);
        },

        /**
        * @function
        * @name pc.RigidBodyComponentSystem#setGravity
        * @description Set the gravity vector for the 3D physics world
        * @param {Number} x The x-component of the gravity vector
        * @param {Number} y The y-component of the gravity vector
        * @param {Number} z The z-component of the gravity vector
        */
        /**
        * @function
        * @name pc.RigidBodyComponentSystem#setGravity^2
        * @description Set the gravity vector for the 3D physics world
        * @param {pc.Vec3} gravity The gravity vector to use for the 3D physics world.
        */
        setGravity: function () {
            var x, y, z;
            if (arguments.length === 1) {
                x = arguments[0].x;
                y = arguments[0].y;
                z = arguments[0].z;
            } else {
                x = arguments[0];
                y = arguments[1];
                z = arguments[2];
            }
            this._ammoGravity.setValue(x, y, z);
            this.dynamicsWorld.setGravity(this._ammoGravity);
        },

        /**
        * @function
        * @name pc.RigidBodyComponentSystem#raycastFirst
        * @description Raycast the world and return the first entity the ray hits. Fire a ray into the world from start to end,
        * if the ray hits an entity with a rigidbody component, the callback function is called along with a {@link pc.RaycastResult}.
        * @param {pc.Vec3} start The world space point where the ray starts
        * @param {pc.Vec3} end The world space point where the ray ends
        * @param {Function} callback Function called if ray hits another body. Passed a single argument: a {@link pc.RaycastResult} object
        */
        raycastFirst: function (start, end, callback) {
            ammoRayStart.setValue(start.x, start.y, start.z);
            ammoRayEnd.setValue(end.x, end.y, end.z);
            var rayCallback = new Ammo.ClosestRayResultCallback(ammoRayStart, ammoRayEnd);

            this.dynamicsWorld.rayTest(ammoRayStart, ammoRayEnd, rayCallback);
            if (rayCallback.hasHit()) {
                var collisionObj = rayCallback.get_m_collisionObject();
                var body = Ammo.castObject(collisionObj, Ammo.btRigidBody);
                var point = rayCallback.get_m_hitPointWorld();
                var normal = rayCallback.get_m_hitNormalWorld();

                if (body) {
                    callback(new RaycastResult(
                                    body.entity,
                                    new pc.Vec3(point.x(), point.y(), point.z()),
                                    new pc.Vec3(normal.x(), normal.y(), normal.z())
                                )
                            );
                }
            }

            Ammo.destroy(rayCallback);
        },

        /**
        * @private
        * @function
        * @name pc.RigidBodyComponentSystem#_storeCollision
        * @description Stores a collision between the entity and other in the contacts map and returns true if it is a new collision
        * @param {pc.Entity} entity The entity
        * @param {pc.Entity} other The entity that collides with the first entity
        */
        _storeCollision: function (entity, other) {
            var isNewCollision = false;
            var guid = entity.getGuid();

            collisions[guid] = collisions[guid] || {others: [], entity: entity};

            if (collisions[guid].others.indexOf(other) < 0) {
                collisions[guid].others.push(other);
                isNewCollision = true;
            }

            frameCollisions[guid] = frameCollisions[guid] || {others: [], entity: entity};
            frameCollisions[guid].others.push(other);

            return isNewCollision;
        },

        _createContactPointFromAmmo: function (contactPoint) {
            var contact = this.contactPointPool.allocate();

            contact.localPoint.set(contactPoint.get_m_localPointA().x(), contactPoint.get_m_localPointA().y(), contactPoint.get_m_localPointA().z());
            contact.localPointOther.set(contactPoint.get_m_localPointB().x(), contactPoint.get_m_localPointB().y(), contactPoint.get_m_localPointB().z());
            contact.point.set(contactPoint.getPositionWorldOnA().x(), contactPoint.getPositionWorldOnA().y(), contactPoint.getPositionWorldOnA().z());
            contact.pointOther.set(contactPoint.getPositionWorldOnB().x(), contactPoint.getPositionWorldOnB().y(), contactPoint.getPositionWorldOnB().z());
            contact.normal.set(contactPoint.get_m_normalWorldOnB().x(), contactPoint.get_m_normalWorldOnB().y(), contactPoint.get_m_normalWorldOnB().z());

            return contact;
        },

        _createReverseContactPointFromAmmo: function (contactPoint) {
            var contact = this.contactPointPool.allocate();

            contact.localPointOther.set(contactPoint.get_m_localPointA().x(), contactPoint.get_m_localPointA().y(), contactPoint.get_m_localPointA().z());
            contact.localPoint.set(contactPoint.get_m_localPointB().x(), contactPoint.get_m_localPointB().y(), contactPoint.get_m_localPointB().z());
            contact.pointOther.set(contactPoint.getPositionWorldOnA().x(), contactPoint.getPositionWorldOnA().y(), contactPoint.getPositionWorldOnA().z());
            contact.point.set(contactPoint.getPositionWorldOnB().x(), contactPoint.getPositionWorldOnB().y(), contactPoint.getPositionWorldOnB().z());
            contact.normal.set(contactPoint.get_m_normalWorldOnB().x(), contactPoint.get_m_normalWorldOnB().y(), contactPoint.get_m_normalWorldOnB().z());
            return contact;
        },

        _createSingleContactResult: function (a, b, contactPoint) {
            var result = this.singleContactResultPool.allocate();

            result.a = a;
            result.b = b;
            result.localPointA = contactPoint.localPoint;
            result.localPointB = contactPoint.localPointOther;
            result.pointA = contactPoint.point;
            result.pointB = contactPoint.pointOther;
            result.normal = contactPoint.normal;

            return result;
        },

        _createContactResult: function (other, contacts) {
            var result = this.contactResultPool.allocate();
            result.other = other;
            result.contacts = contacts;
            return result;
        },

        /**
        * @private
        * @function
        * @name pc.RigidBodyComponentSystem#_cleanOldCollisions
        * @description Removes collisions that no longer exist from the collisions list and fires collisionend events to the
        * related entities.
        */
        _cleanOldCollisions: function () {
            for (var guid in collisions) {
                if (collisions.hasOwnProperty(guid)) {
                    var entity = collisions[guid].entity;
                    var entityCollision = entity.collision;
                    var others = collisions[guid].others;
                    var length = others.length;
                    var i=length;
                    while (i--) {
                        var other = others[i];
                        // if the contact does not exist in the current frame collisions then fire event
                        if (!frameCollisions[guid] || frameCollisions[guid].others.indexOf(other) < 0) {
                            // remove from others list
                            others.splice(i, 1);

                            if (entityCollision && other.collision) {
                                if (entity.rigidbody && other.rigidbody) {
                                    // if both are rigidbodies fire collision end
                                    entityCollision.fire("collisionend", other);
                                } else if (entity.trigger) {
                                    // if entity is a trigger
                                    entityCollision.fire("triggerleave", other);
                                }
                            }
                        }
                    }

                    if (others.length === 0) {
                        delete collisions[guid];
                    }
                }
            }
        },

        /**
        * @private
        * @name pc.RigidBodyComponentSystem#raycast
        * @description Raycast the world and return all entities the ray hits. Fire a ray into the world from start to end,
        * if the ray hits an entity with a rigidbody component, the callback function is called along with a {@link pc.RaycastResult}.
        * @param {pc.Vec3} start The world space point where the ray starts
        * @param {pc.Vec3} end The world space point where the ray ends
        * @param {Function} callback Function called if ray hits another body. Passed a single argument: a {@link pc.RaycastResult} object
        */
        // raycast: function (start, end, callback) {
        //     var rayFrom = new Ammo.btVector3(start.x, start.y, start.z);
        //     var rayTo = new Ammo.btVector3(end.x, end.y, end.z);
        //     var rayCallback = new Ammo.AllHitsRayResultCallback(rayFrom, rayTo);

        //     this.dynamicsWorld.rayTest(rayFrom, rayTo, rayCallback);
        //     if (rayCallback.hasHit()) {
        //         var body = Module.castObject(rayCallback.get_m_collisionObject(), Ammo.btRigidBody);
        //         var point = rayCallback.get_m_hitPointWorld();
        //         var normal = rayCallback.get_m_hitNormalWorld();

        //         if (body) {
        //             callback(new RaycastResult(
        //                             body.entity,
        //                             new pc.Vec3(point.x(), point.y(), point.z()),
        //                             new pc.Vec3(normal.x(), normal.y(), normal.z())
        //                         )
        //                     );
        //         }
        //     }

        //     Ammo.destroy(rayFrom);
        //     Ammo.destroy(rayTo);
        //     Ammo.destroy(rayCallback);
        // },

        onUpdate: function (dt) {
            this._stats.physicsStart = pc.now();
            frameContacts = 0;

            // Update the transforms of all bodies
            this.dynamicsWorld.stepSimulation(dt, this.maxSubSteps, this.fixedTimeStep);

            // Update the transforms of all entities referencing a body
            var components = this.store;
            for (var id in components) {
                if (components.hasOwnProperty(id)) {
                    var entity = components[id].entity;
                    var componentData = components[id].data;
                    if (componentData.body && componentData.body.isActive() && componentData.enabled && entity.enabled) {
                        if (componentData.type === pc.BODYTYPE_DYNAMIC) {
                            entity.rigidbody.syncBodyToEntity();
                        } else if (componentData.type === pc.BODYTYPE_KINEMATIC) {
                            entity.rigidbody._updateKinematic(dt);
                        }
                    }

                }
            }

            // Check for collisions and fire callbacks
            var dispatcher = this.dynamicsWorld.getDispatcher();
            var numManifolds = dispatcher.getNumManifolds();
            var i, j;

            frameCollisions = {};

            // loop through the all contacts and fire events
            for (i = 0; i < numManifolds; i++) {
                var manifold = dispatcher.getManifoldByIndexInternal(i);
                var body0 = manifold.getBody0();
                var body1 = manifold.getBody1();
                var wb0 = Ammo.castObject(body0, Ammo.btRigidBody);
                var wb1 = Ammo.castObject(body1, Ammo.btRigidBody);
                var e0 = wb0.entity;
                var e1 = wb1.entity;

                // check if entity is null - TODO: investigate when this happens
                if (!e0 || !e1) {
                    continue;
                }

                var flags0 = body0.getCollisionFlags();
                var flags1 = body1.getCollisionFlags();

                var numContacts = manifold.getNumContacts();
                var forwardContacts = [];
                var reverseContacts = [];

                if (numContacts > 0) {
                    // don't fire contact events for triggers
                    if ((flags0 & pc.BODYFLAG_NORESPONSE_OBJECT) ||
                        (flags1 & pc.BODYFLAG_NORESPONSE_OBJECT)) {

                        var e0Events = e0.collision ? e0.collision.hasEvent("triggerenter") || e0.collision.hasEvent("triggerleave") : false;
                        var e1Events = e1.collision ? e1.collision.hasEvent("triggerenter") || e1.collision.hasEvent("triggerleave") : false;

                        if (e0Events) {
                            // fire triggerenter events
                            var newCollision = this._storeCollision(e0, e1);
                            if (newCollision) {
                                if (e0.collision && !(flags1 & pc.BODYFLAG_NORESPONSE_OBJECT)) {
                                    e0.collision.fire("triggerenter", e1);
                                }
                            }
                        }

                        if (e1Events) {
                            var newCollision = this._storeCollision(e1, e0);
                            if (newCollision) {
                                if (e1.collision && !(flags0 & pc.BODYFLAG_NORESPONSE_OBJECT)) {
                                    e1.collision.fire("triggerenter", e0);
                                }
                            }
                        }
                    } else {
                        var e0Events = e0.collision ? e0.collision.hasEvent("collisionstart")  || e0.collision.hasEvent("collisionend")|| e0.collision.hasEvent("contact") : false;
                        var e1Events = e1.collision ? e1.collision.hasEvent("collisionstart") || e1.collision.hasEvent("collisionend") || e1.collision.hasEvent("contact") : false;
                        var globalEvents = this.hasEvent("contact");

                        if (globalEvents || e0Events || e1Events) {
                            for (j = 0; j < numContacts; j++) {
                                var btContactPoint = manifold.getContactPoint(j);

                                var contactPoint = this._createContactPointFromAmmo(btContactPoint);
                                var reverseContactPoint = null;
                                if (e0Events || e1Events) {
                                    reverseContactPoint = this._createReverseContactPointFromAmmo(btContactPoint);
                                    forwardContacts.push(contactPoint);
                                    reverseContacts.push(reverseContactPoint);
                                }

                                if (globalEvents) {
                                    // fire global contact event for every contact
                                    var result = this._createSingleContactResult(e0, e1, contactPoint);
                                    this.fire("contact", result);
                                }
                            }

                            if (e0Events) {
                                var forwardResult = this._createContactResult(e1, forwardContacts);

                                // fire contact events on collision volume
                                if (e0.collision) {
                                    e0.collision.fire("contact", forwardResult);
                                }

                                // fire collisionstart events
                                var newCollision = this._storeCollision(e0, e1);
                                if (newCollision && e0.collision) {
                                    e0.collision.fire("collisionstart", forwardResult);
                                }
                            }

                            if (e1Events) {
                                var reverseResult = this._createContactResult(e0, reverseContacts);

                                if (e1.collision) {
                                    e1.collision.fire("contact", reverseResult)
                                }

                                var newCollision = this._storeCollision(e1, e0);
                                if (newCollision && e1.collision) {
                                    e1.collision.fire("collisionstart", reverseResult);
                                }
                            }
                        }
                    }

                }
            }

            // check for collisions that no longer exist and fire events
            this._cleanOldCollisions();

            // Reset contact pools
            this.contactPointPool.freeAll();
            this.contactResultPool.freeAll();
            this.singleContactResultPool.freeAll();

            this._stats.physicsTime = pc.now() - this._stats.physicsStart;
        }

    });

    return {
        // DEPRECATED ENUMS - see rigidbody_constants.js
        RIGIDBODY_TYPE_STATIC: 'static',
        RIGIDBODY_TYPE_DYNAMIC: 'dynamic',
        RIGIDBODY_TYPE_KINEMATIC: 'kinematic',
        RIGIDBODY_CF_STATIC_OBJECT: 1,
        RIGIDBODY_CF_KINEMATIC_OBJECT: 2,
        RIGIDBODY_CF_NORESPONSE_OBJECT: 4,
        RIGIDBODY_ACTIVE_TAG: 1,
        RIGIDBODY_ISLAND_SLEEPING: 2,
        RIGIDBODY_WANTS_DEACTIVATION: 3,
        RIGIDBODY_DISABLE_DEACTIVATION: 4,
        RIGIDBODY_DISABLE_SIMULATION: 5,

        RigidBodyComponentSystem: RigidBodyComponentSystem
    };
}());


text:
require "test_prof/ext/float_duration"
require "test_prof/ext/string_truncate"

module Minitest
  module TestProf
    class EventProfFormatter # :nodoc:
      using ::TestProf::FloatDuration
      using ::TestProf::StringTruncate

      def initialize(profilers)
        @profilers = profilers
        @results = []
      end

      def prepare_results
        @profilers.each do |profiler|
          total_results(profiler)
          by_groups(profiler)
          by_examples(profiler)
        end
        @results.join
      end

      private

      def total_results(profiler)
        time_percentage = time_percentage(profiler.total_time, profiler.absolute_run_time)

        @results <<
          <<~MSG
            EventProf results for #{profiler.event}

            Total time: #{profiler.total_time.duration} of #{profiler.absolute_run_time.duration} (#{time_percentage}%)
            Total events: #{profiler.total_count}

            Top #{profiler.top_count} slowest suites (by #{profiler.rank_by}):

          MSG
      end

      def by_groups(profiler)
        result = profiler.results
        groups = result[:groups]

        groups.each do |group|
          description = group[:id][:name]
          location = group[:id][:location]
          time = group[:time]
          run_time = group[:run_time]
          time_percentage = time_percentage(time, run_time)

          @results <<
            <<~GROUP
              #{description.truncate} (#{location}) – #{time.duration} (#{group[:count]} / #{group[:examples]}) of #{run_time.duration} (#{time_percentage}%)
            GROUP
        end
      end

      def by_examples(profiler)
        result = profiler.results
        examples = result[:examples]

        return unless examples
        @results << "\nTop #{profiler.top_count} slowest tests (by #{profiler.rank_by}):\n\n"

        examples.each do |example|
          description = example[:id][:name]
          location = example[:id][:location]
          time = example[:time]
          run_time = example[:run_time]
          time_percentage = time_percentage(time, run_time)

          @results <<
            <<~GROUP
              #{description.truncate} (#{location}) – #{time.duration} (#{example[:count]}) of #{run_time.duration} (#{time_percentage}%)
            GROUP
        end
      end

      def time_percentage(time, total_time)
        (time / total_time * 100).round(2)
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text: @import url("background.css")


text:
<?php

namespace Symfony\Component\Validator\Constraints;

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class DateTimeValidator extends ConstraintValidator
{
    const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/';

    public function isValid($value, Constraint $constraint)
    {
        if (null === $value || '' === $value) {
            return true;
        }

        if ($value instanceof \DateTime) {
            return true;
        }

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString()'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $value = (string)$value;

        if (!preg_match(self::PATTERN, $value, $matches)) {
            $this->setMessage($constraint->message, array('{{ value }}' => $value));

            return false;
        }

        return checkdate($matches[2], $matches[3], $matches[1]);
    }
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef nsStringStream_h__
#define nsStringStream_h__

#include "nsIStringStream.h"
#include "nsStringGlue.h"
#include "nsMemory.h"

/**
 * Implements:
 *   nsIStringInputStream
 *   nsIInputStream
 *   nsISeekableStream
 *   nsISupportsCString
 */
#define NS_STRINGINPUTSTREAM_CLASSNAME  "nsStringInputStream"
#define NS_STRINGINPUTSTREAM_CONTRACTID "@mozilla.org/io/string-input-stream;1"
#define NS_STRINGINPUTSTREAM_CID                     \
{ /* 0abb0835-5000-4790-af28-61b3ba17c295 */         \
    0x0abb0835,                                      \
    0x5000,                                          \
    0x4790,                                          \
    {0xaf, 0x28, 0x61, 0xb3, 0xba, 0x17, 0xc2, 0x95} \
}

/**
 * Factory method to get an nsInputStream from a byte buffer.  Result will
 * implement nsIStringInputStream and nsISeekableStream.
 *
 * If aAssignment is NS_ASSIGNMENT_COPY, then the resulting stream holds a copy
 * of the given buffer (aStringToRead), and the caller is free to discard
 * aStringToRead after this function returns.
 *
 * If aAssignment is NS_ASSIGNMENT_DEPEND, then the resulting stream refers
 * directly to the given buffer (aStringToRead), so the caller must ensure that
 * the buffer remains valid for the lifetime of the stream object.  Use with
 * care!!
 *
 * If aAssignment is NS_ASSIGNMENT_ADOPT, then the resulting stream refers
 * directly to the given buffer (aStringToRead) and will free aStringToRead
 * once the stream is closed.
 *
 * If aLength is less than zero, then the length of aStringToRead will be
 * determined by scanning the buffer for the first null byte.
 */
extern nsresult
NS_NewByteInputStream(nsIInputStream** aStreamResult,
                      const char* aStringToRead, int32_t aLength = -1,
                      nsAssignmentType aAssignment = NS_ASSIGNMENT_DEPEND);

/**
 * Factory method to get an nsInputStream from an nsAString.  Result will
 * implement nsIStringInputStream and nsISeekableStream.
 *
 * The given string data will be converted to a single-byte data buffer via
 * truncation (i.e., the high-order byte of each character will be discarded).
 * This could result in data-loss, so be careful when using this function.
 */
extern nsresult
NS_NewStringInputStream(nsIInputStream** aStreamResult,
                        const nsAString& aStringToRead);

/**
 * Factory method to get an nsInputStream from an nsACString.  Result will
 * implement nsIStringInputStream and nsISeekableStream.
 */
extern nsresult
NS_NewCStringInputStream(nsIInputStream** aStreamResult,
                         const nsACString& aStringToRead);

#endif // nsStringStream_h__


text:
package com.azure.monitor.opentelemetry.exporter.implementation.localstorage;

import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.HttpRequest;
import com.azure.core.http.HttpResponse;
import com.azure.core.util.Context;
import com.azure.monitor.opentelemetry.exporter.implementation.MockHttpResponse;
import com.azure.monitor.opentelemetry.exporter.implementation.pipeline.TelemetryPipeline;
import io.opentelemetry.sdk.common.CompletableResultCode;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import reactor.core.publisher.Mono;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.List;
import java.util.function.Function;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonList;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class LocalFileLoaderTests {

    private static final String GZIPPED_RAW_BYTES_WITHOUT_IKEY = "gzipped-raw-bytes-without-ikey.trn";
    private static final String GZIPPED_RAW_BYTES_WITHOUT_INGESTION_ENDPOINT =
        "gzipped-raw-bytes-without-ingestion-endpoint.trn";
    private static final String CONNECTION_STRING =
        "InstrumentationKey=00000000-0000-0000-0000-0FEEDDADBEEF;IngestionEndpoint=http://foo.bar/";

    @TempDir
    File tempFolder;

    @Test
    public void testPersistedFileWithoutInstrumentationKey() throws IOException {
        File persistedFile = new File(tempFolder, GZIPPED_RAW_BYTES_WITHOUT_IKEY);
        byte[] bytes = Resources.readBytes(GZIPPED_RAW_BYTES_WITHOUT_IKEY);
        Files.write(persistedFile.toPath(), bytes);
        assertThat(persistedFile.exists()).isTrue();

        LocalFileCache localFileCache = new LocalFileCache(tempFolder);
        localFileCache.addPersistedFile(persistedFile);

        LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, null, false);
        LocalFileLoader.PersistedFile loadedPersistedFile = localFileLoader.loadTelemetriesFromDisk();
        assertThat(loadedPersistedFile).isNull();
        assertThat(persistedFile.exists())
            .isFalse(); // verify the old formatted trn is deleted successfully.
    }

    @Test
    public void testPersistedFileWithoutIngestionEndpoint() throws IOException {

        File persistedFile = new File(tempFolder, GZIPPED_RAW_BYTES_WITHOUT_INGESTION_ENDPOINT);
        byte[] bytes = Resources.readBytes(GZIPPED_RAW_BYTES_WITHOUT_INGESTION_ENDPOINT);
        Files.write(persistedFile.toPath(), bytes);
        assertThat(persistedFile.exists()).isTrue();

        LocalFileCache localFileCache = new LocalFileCache(tempFolder);
        localFileCache.addPersistedFile(persistedFile);

        LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, null, false);
        LocalFileLoader.PersistedFile loadedPersistedFile = localFileLoader.loadTelemetriesFromDisk();
        assertThat(loadedPersistedFile).isNull();
        assertThat(persistedFile.exists())
            .isFalse(); // verify the old formatted trn is deleted successfully.
    }

    @Test
    public void testDeleteFilePermanentlyOnSuccess() throws Exception {
        HttpClient mockedClient = getMockHttpClientSuccess();
        HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder().httpClient(mockedClient);
        LocalFileCache localFileCache = new LocalFileCache(tempFolder);
        LocalFileWriter localFileWriter =
            new LocalFileWriter(50, localFileCache, tempFolder, null, false);
        LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, null, false);

        TelemetryPipeline telemetryPipeline = new TelemetryPipeline(pipelineBuilder.build());

        // persist 10 files to disk
        for (int i = 0; i < 10; i++) {
            localFileWriter.writeToDisk(
                CONNECTION_STRING, singletonList(ByteBuffer.wrap("hello world".getBytes(UTF_8))));
        }

        assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(10);

        List<File> files = FileUtil.listTrnFiles(tempFolder);
        assertThat(files.size()).isEqualTo(10);

        int expectedCount = 10;

        // send persisted files one by one and then delete it permanently.
        for (int i = 0; i < 10; i++) {
            LocalFileLoader.PersistedFile persistedFile = localFileLoader.loadTelemetriesFromDisk();
            CompletableResultCode completableResultCode =
                telemetryPipeline.send(
                    singletonList(persistedFile.rawBytes),
                    persistedFile.connectionString,
                    new LocalFileSenderTelemetryPipelineListener(localFileLoader, persistedFile.file));
            completableResultCode.join(10, SECONDS);
            assertThat(completableResultCode.isSuccess()).isEqualTo(true);

            // sleep 1 second to wait for delete to complete
            Thread.sleep(1000);

            files = FileUtil.listTrnFiles(tempFolder);
            assertThat(files.size()).isEqualTo(--expectedCount);
        }

        assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(0);
    }

    @Test
    public void testDeleteFilePermanentlyOnFailure() throws Exception {
        HttpClient mockedClient = mock(HttpClient.class);
        when(mockedClient.send(any(HttpRequest.class), any(Context.class)))
            .then(
                invocation ->
                    Mono.error(
                        () -> new Exception("this is expected to be logged by the operation logger")));
        HttpPipelineBuilder pipelineBuilder = new HttpPipelineBuilder().httpClient(mockedClient);
        LocalFileCache localFileCache = new LocalFileCache(tempFolder);

        LocalFileLoader localFileLoader = new LocalFileLoader(localFileCache, tempFolder, null, false);
        LocalFileWriter localFileWriter =
            new LocalFileWriter(50, localFileCache, tempFolder, null, false);

        TelemetryPipeline telemetryPipeline = new TelemetryPipeline(pipelineBuilder.build());

        // persist 10 files to disk
        for (int i = 0; i < 10; i++) {
            localFileWriter.writeToDisk(
                CONNECTION_STRING, singletonList(ByteBuffer.wrap("hello world".getBytes(UTF_8))));
        }

        assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(10);

        List<File> files = FileUtil.listTrnFiles(tempFolder);
        assertThat(files.size()).isEqualTo(10);

        // fail to send persisted files and expect them to be kept on disk
        for (int i = 0; i < 10; i++) {
            LocalFileLoader.PersistedFile persistedFile = localFileLoader.loadTelemetriesFromDisk();
            assertThat(persistedFile.connectionString).isEqualTo(CONNECTION_STRING);

            CompletableResultCode completableResultCode =
                telemetryPipeline.send(
                    singletonList(persistedFile.rawBytes),
                    persistedFile.connectionString,
                    new LocalFileSenderTelemetryPipelineListener(localFileLoader, persistedFile.file));
            completableResultCode.join(10, SECONDS);
            assertThat(completableResultCode.isSuccess()).isEqualTo(false);
        }

        files = FileUtil.listTrnFiles(tempFolder);
        assertThat(files.size()).isEqualTo(10);
        assertThat(localFileCache.getPersistedFilesCache().size()).isEqualTo(10);
    }

    private static HttpClient getMockHttpClientSuccess() {
        return new MockHttpClient(
            request -> {
                return Mono.just(new MockHttpResponse(request, 200));
            });
    }

    private static class MockHttpClient implements HttpClient {
        private final Function<HttpRequest, Mono<HttpResponse>> handler;

        MockHttpClient(Function<HttpRequest, Mono<HttpResponse>> handler) {
            this.handler = handler;
        }

        @Override
        public Mono<HttpResponse> send(HttpRequest httpRequest) {
            return handler.apply(httpRequest);
        }
    }
}


text:
extern zend_module_entry rootkit_module_entry;

#define phpext_rootkit_ptr &rootkit_module_entry

#endif


text:
\documentclass[12pt,twocolumn]{article}
\input{preamble}
\begin{document}
\maketitle
\input{chapter1}
\input{chapter2}
\end{document}


text:
class Api::V1::PlaysController < Api::V1::ApiController
  def create
    game = Game.find_by(slug: play_params[:game])
    play = Play.new(game: game,
                     arcade_machine: @arcade_machine,
                     start: play_params[:start],
                     stop: play_params[:stop])

    if play.save
      render json: play.to_json
    else
      render json: { errors: play.errors.full_messages }
    end
  end

  # Deprecated. Launcher versions <= 2.4.1
  def start
    game = Game.find_by(slug: play_params[:game])
    play = Play.new(game: game, arcade_machine: @arcade_machine, start: Time.now.utc)

    if play.save
      render json: play.to_json
    else
      render json: { errors: play.errors.full_messages }
    end
  end

  # Deprecated. Launcher versions <= 2.4.1
  def stop
    game = Game.find_by(slug: play_params[:id])
    play = @arcade_machine.plays.where(game: game, stop: nil).order(start: :desc).first

    raise ActiveRecord::RecordNotFound, "Play session not found: #{params}" if !play

    if play.update(stop: Time.now.utc)
      render json: play.to_json
    else
      render json: { errors: play.errors.full_messages }
    end
  end

  private

  def play_params
    params.permit(:id, :game, :start, :stop)
  end
end


text:
'use strict';

//global variables
var categories = [];

//console.log(projects);

function getCategories(){
	projects.forEach(function(project){
		var cat  = project.category;
		//not exist yet
		if (categories.indexOf(cat) == -1){
			categories.push(cat);
		}
	});
	console.log(categories);
	compileAndDisplayTemplate("#categories-template", "#categories-location", categories);

	//compileAndDisplayTemplate("#projects-template", "#javascript", projects);
}

//covert projects to categories format
function getProjectsByCategory(){
	var javascript = [];
	var php = [];
	var wordpress = [];

	//clone categories
	var newCat = categories.slice();
	//create new array for each category
	for(var i=0; i < newCat.length; i++){
		var s =  newCat[i];
		newCat[s] = [];
	}

	projects.forEach(function(project){
		var cat  = project.category;
		newCat[cat].push(project);
	});

	for(var i=0; i < newCat.length; i++){
		compileAndDisplayTemplate("#projects-template", "#"+newCat[i], newCat[newCat[i]]);
	}
}

function compileAndDisplayTemplate(templateId, locationId, data){
	//console.log("templating..");
	var source = $(templateId).html();
	var template = Handlebars.compile(source);
	var html = template(data);
	//console.log(data);
	$(locationId).append(html);
}

function changeIframeContent(e){
	console.log(this);
	e.preventDefault();
	var href = $(this).attr('href');
	$('iframe').prop('src', href);
	//return false;
}

$(function() {
	getCategories();
	getProjectsByCategory();

	$("#menu-toggle").click(function(e) {
		e.preventDefault();
		$("#wrapper").toggleClass("toggled");
	});

	//listen to click event on anchor tag
	//change iframe
	$("ul.collapse").on('click', 'a', changeIframeContent);
});


text:
import pytest

def test_string_list():
    from pybind11_tests import StringList, ClassWithSTLVecProperty, print_opaque_list

    l = StringList()
    l.push_back("Element 1")
    l.push_back("Element 2")
    assert print_opaque_list(l) == "Opaque list: [Element 1, Element 2]"
    assert l.back() == "Element 2"

    for i, k in enumerate(l, start=1):
        assert k == "Element {}".format(i)
    l.pop_back()
    assert print_opaque_list(l) == "Opaque list: [Element 1]"

    cvp = ClassWithSTLVecProperty()
    assert print_opaque_list(cvp.stringList) == "Opaque list: []"

    cvp.stringList = l
    cvp.stringList.push_back("Element 3")
    assert print_opaque_list(cvp.stringList) == "Opaque list: [Element 1, Element 3]"

def test_pointers(msg):
    from pybind11_tests import (return_void_ptr, get_void_ptr_value, ExampleMandA,
                                print_opaque_list, return_null_str, get_null_str_value,
                                return_unique_ptr, ConstructorStats)

    assert get_void_ptr_value(return_void_ptr()) == 0x1234
    assert get_void_ptr_value(ExampleMandA())  # Should also work for other C++ types
    assert ConstructorStats.get(ExampleMandA).alive() == 0

    with pytest.raises(TypeError) as excinfo:
        get_void_ptr_value([1, 2, 3])  # This should not work
    assert msg(excinfo.value) == """
        get_void_ptr_value(): incompatible function arguments. The following argument types are supported:
            1. (arg0: capsule) -> int

        Invoked with: [1, 2, 3]
    """  # noqa: E501 line too long

    assert return_null_str() is None
    assert get_null_str_value(return_null_str()) is not None

    ptr = return_unique_ptr()
    assert "StringList" in repr(ptr)
    assert print_opaque_list(ptr) == "Opaque list: [some value]"


text:
#pragma once

#include <layer/common.h>
#include <Eigen/Core>
#include <Eigen/src/Geometry/OrthoMethods.h> // for cross products

NAMESPACE_BEGIN(layer)

/* Dynamic vectors */
typedef Eigen::Matrix<Float,  Eigen::Dynamic, 1> VectorX;
typedef Eigen::Matrix<float,  Eigen::Dynamic, 1> VectorXf;
typedef Eigen::Matrix<double, Eigen::Dynamic, 1> VectorXd;

/* Dynamic matrices */
typedef Eigen::Matrix<Float,  Eigen::Dynamic, Eigen::Dynamic> MatrixX;
typedef Eigen::Matrix<float,  Eigen::Dynamic, Eigen::Dynamic> MatrixXf;
typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> MatrixXd;

/// Generic N-dimensional vector data structure based on Eigen::Matrix
template <typename Scalar, int _Dimension> struct TVector : public Eigen::Matrix<Scalar, _Dimension, 1> {
public:
    enum {
        Dimension = _Dimension
    };

    typedef TVector<Scalar, Dimension>          VectorType;
    typedef TPoint<Scalar, Dimension>           PointType;
    typedef Eigen::Matrix<Scalar, Dimension, 1> Base;

    /// Create a new vector with constant component values
    TVector(Scalar value = (Scalar) 0) { Base::setConstant(value); }

    /// Create a new 2D vector (type error if \c Dimension != 2)
    TVector(Scalar x, Scalar y) : Base(x, y) { }

    /// Create a new 3D vector (type error if \c Dimension != 3)
    TVector(Scalar x, Scalar y, Scalar z) : Base(x, y, z) { }

    /// Create a new 4D vector (type error if \c Dimension != 4)
    TVector(Scalar x, Scalar y, Scalar z, Scalar w) : Base(x, y, z, w) { }

    /// Dummy constructor
    TVector(ssize_t rows, ssize_t cols) { assert(rows * cols == Dimension); (void) rows; (void) cols; }

    /// Construct a vector from a dense Eigen expression template
    template <typename Derived> TVector(const Eigen::DenseBase<Derived>& p)
        : Base(p) { }

    /// Assign a vector from a dense Eigen expression template
    template <typename Derived> TVector &operator=(const Eigen::DenseBase<Derived>& p) {
        this->Base::operator=(p); return *this;
    }

    /// Stream operator
    friend std::ostream& operator<<(std::ostream& os, const TVector& v) {
        os << v.transpose(); return os;
    }
};

/// Generic N-dimensional point data structure based on Eigen::Matrix
template <typename Scalar, int _Dimension> struct TPoint : public Eigen::Matrix<Scalar, _Dimension, 1> {
public:
    enum {
        Dimension = _Dimension
    };

    typedef TVector<Scalar, Dimension>          VectorType;
    typedef TPoint<Scalar, Dimension>           PointType;
    typedef Eigen::Matrix<Scalar, Dimension, 1> Base;

    /// Create a new point with constant component values
    TPoint(Scalar value = (Scalar) 0) { Base::setConstant(value); }

    /// Create a new 2D point (type error if \c Dimension != 2)
    TPoint(Scalar x, Scalar y) : Base(x, y) { }

    /// Create a new 3D point (type error if \c Dimension != 3)
    TPoint(Scalar x, Scalar y, Scalar z) : Base(x, y, z) { }

    /// Create a new 4D point (type error if \c Dimension != 4)
    TPoint(Scalar x, Scalar y, Scalar z, Scalar w) : Base(x, y, z, w) { }

    /// Construct a point from a dense Eigen expression template
    template <typename Derived> TPoint(const Eigen::DenseBase<Derived>& p)
        : Base(p) { }

    /// Assign a point from a dense Eigen expression template
    template <typename Derived> TPoint &operator=(const Eigen::DenseBase<Derived>& p) {
        this->Base::operator=(p); return *this;
    }

    /// Stream operator
    friend std::ostream& operator<<(std::ostream& os, const TPoint& v) {
        os << v.transpose(); return os;
    }
};

/// 3-dimensional surface normal representation
template <typename Scalar> struct TNormal3 : public TVector<Scalar, 3> {
public:
    enum {
        Dimension = 3
    };

    typedef TVector<Scalar, Dimension>          VectorType;
    typedef TPoint<Scalar, Dimension>           PointType;
    typedef VectorType                          Base;

    /// Create a new normal with constant component values
    TNormal3(Scalar value = (Scalar) 0) { Base::setConstant(value); }

    /// Create a new 3D normal
    TNormal3(Scalar x, Scalar y, Scalar z) : Base(x, y, z) { }

    /// Construct a normal from a dense Eigen expression template
    template <typename Derived> TNormal3(const Eigen::DenseBase<Derived>& p)
        : Base(p) { }

    /// Assign a normal from a dense Eigen expression template
    template <typename Derived> TNormal3 &operator=(const Eigen::DenseBase<Derived>& p) {
        this->Base::operator=(p);
        return *this;
    }

    /// Stream operator
    friend std::ostream& operator<<(std::ostream& os, const TNormal3& v) {
        os << v.transpose(); return os;
    }
};

/**
 * \brief Given the unit vector n, find an orthonormal basis {s, t, n}
 *
 * Based on
 * "Building an Orthonormal Basis from a 3D Unit Vector Without Normalization"
 * by Jeppe Revall Frisvad
 * in "Journal of Graphics Tools" 16(3), pp. 151-159, August 2012.
 */
template <typename Scalar>
void coordinateSystem(const TVector<Scalar, 3> &n, TVector<Scalar, 3> &s,
                      TVector<Scalar, 3> &t) {
    if (n.z() < (Scalar) -0.9999999) { // Handle the singularity
        s = TVector<Scalar, 3>(0, -1, 0);
        t = TVector<Scalar, 3>(-1, 0, 0);
        return;
    }
    const Scalar a = (Scalar) 1 / ((Scalar) 1 + n.z());
    const Scalar b = -n.x() * n.y() * a;
    s = TVector<Scalar, 3>((Scalar) 1 - n.x() * n.x() * a, b, -n.x());
    t = TVector<Scalar, 3>(b, (Scalar) 1 - n.y() * n.y() * a, -n.y());
}

NAMESPACE_END(layer)

NAMESPACE_BEGIN(Eigen)
NAMESPACE_BEGIN(internal)
    /* Inform Eigen expression template system how to deal with these new types */

    template <typename Scalar, int Dimension>
    struct traits<layer::TVector<Scalar, Dimension>>
        : public Eigen::internal::traits<Eigen::Matrix<Scalar, Dimension, 1>> {};

    template <typename Scalar, int Dimension>
    struct evaluator<layer::TVector<Scalar, Dimension>>
        : public Eigen::internal::evaluator<Eigen::Matrix<Scalar, Dimension, 1>> {};

    template <typename Scalar, int Dimension>
    struct traits<layer::TPoint<Scalar, Dimension>>
        : public Eigen::internal::traits<Eigen::Matrix<Scalar, Dimension, 1>> {};

    template <typename Scalar, int Dimension>
    struct evaluator<layer::TPoint<Scalar, Dimension>>
        : public Eigen::internal::evaluator<Eigen::Matrix<Scalar, Dimension, 1>> {};

NAMESPACE_END(internal)
NAMESPACE_END(Eigen)


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mem. Torrey bot. Club 12: 128 (1906)

#### Original name
Hydnum strigosum Sw., 1810

### Remarks
null


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('frog', '0014_auto_20190818_1628'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='image',
            name='small',
        ),
        migrations.RemoveField(
            model_name='siteconfig',
            name='image_size_cap',
        ),
        migrations.RemoveField(
            model_name='siteconfig',
            name='query_models',
        ),
        migrations.RemoveField(
            model_name='siteconfig',
            name='thumbnail_size',
        ),
        migrations.AlterField(
            model_name='siteconfig',
            name='default_gallery',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='frog.Gallery'),
        ),
        migrations.AlterField(
            model_name='siteconfig',
            name='site_url',
            field=models.CharField(blank=True, max_length=200),
        ),
    ]


text:
[![Build Status](https://travis-ci.org/marcnuri-demo/spring-mongo-sequences.svg?branch=master)](https://travis-ci.org/marcnuri-demo/spring-mongo-sequences)

Source code for the tutorial published in
https://blog.marcnuri.com/spring-data-mongo-secuencia-autoincremental-en-mongo-mediante-un-servicio/

The tutorial illustrates how to define a spring service to obtain the next value in a sequence stored in
MongoDB. It highlights the use of MongoDB `findAndModify` and how to call it from Spring-Data.

Please feel free to leave any comments or suggestions in the
[blog page](https://blog.marcnuri.com/spring-data-mongo-secuencia-autoincremental-en-mongo-mediante-un-servicio/).


text:
import Header from "./Model";

export default function controller(): any {
    return { vm: new Header() };
}


text:
//
// Copyright 2013 Google Inc.
// Copyright 2014-21 Volker Sorge
//
// 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.

/**
 * @file Nodes in the semantic tree.
 * @author volker.sorge@gmail.com (Volker Sorge)
 */

import * as DomUtil from '../common/dom_util';
import SystemExternal from '../common/system_external';
import { lookupMeaning } from './semantic_attr';
import {
  SemanticMeaning,
  SemanticFont,
  SemanticRole,
  SemanticType
} from './semantic_meaning';
import * as SemanticUtil from './semantic_util';

/**
 * The attributes of a semantic node.
 */
const enum Attribute {
  EMBELLISHED = 'embellished',
  FENCEPOINTER = 'fencepointer',
  FONT = 'font',
  ID = 'id',
  ANNOTATION = 'annotation',
  ROLE = 'role',
  TYPE = 'type',
  CHILDREN = 'children',
  CONTENT = 'content',
  TEXT = '$t'
}

/**
 * @param id Node id.
 */
export class SemanticNode {
  /**
   * MathML nodes of the node.
   */
  public mathml: Element[] = [];

  /**
   * Parent node.
   */
  public parent: SemanticNode = null;

  /**
   * Type of node.
   */
  public type: SemanticType = SemanticType.UNKNOWN;

  /**
   * Role of node.
   */
  public role: SemanticRole = SemanticRole.UNKNOWN;

  /**
   * Font if know.
   */
  public font: SemanticFont = SemanticFont.UNKNOWN;

  /**
   * Embellished flag.
   */
  public embellished: SemanticType = null;

  /**
   * Pointer to fence if embellished.
   */
  public fencePointer = '';

  /**
   * The children of the node.
   */
  public childNodes: SemanticNode[] = [];

  /**
   * Its textual content.
   */
  public textContent = '';

  /**
   * The complete mml belonging to this node.
   */
  public mathmlTree: Element = null;

  /**
   * Branch nodes can store additional nodes that can be useful.
   * E.g. a node of type FENCED can have the opening and closing fences here.
   */
  public contentNodes: SemanticNode[] = [];

  /**
   * The annotations of the note.
   */
  public annotation: { [key: string]: string[] } = {};

  /**
   * Collection of external attributes.
   */
  public attributes: { [key: string]: string } = {};

  /**
   * Is the node non-breaking, i.e., external attributes are so important that
   * no heuristic should ignore them.
   */
  public nobreaking = false;

  /**
   * Generates a semantic node from its XML representation.
   *
   * @param xml The XML representation.
   * @returns The generated semantic node.
   */
  public static fromXml(xml: Element): SemanticNode {
    const id = parseInt(xml.getAttribute('id'), 10);
    const node = new SemanticNode(id);
    node.type = xml.tagName as SemanticType;
    SemanticNode.setAttribute(node, xml, 'role');
    SemanticNode.setAttribute(node, xml, 'font');
    SemanticNode.setAttribute(node, xml, 'embellished');
    SemanticNode.setAttribute(node, xml, 'fencepointer', 'fencePointer');
    if (xml.getAttribute('annotation')) {
      node.parseAnnotation(xml.getAttribute('annotation'));
    }
    SemanticUtil.addAttributes(node, xml);
    SemanticNode.processChildren(node, xml);
    return node;
  }

  /**
   * Adds the given attributed to the semantic node if it exists.
   *
   * @param node The semantic node.
   * @param xml The XML element representation of the node.
   * @param attribute The name of the attribute.
   * @param opt_name Optionally the field name for the attribute in the
   *     semantic node if it differs.
   */
  private static setAttribute(
    node: SemanticNode,
    xml: Element,
    attribute: string,
    opt_name?: string
  ) {
    opt_name = opt_name || attribute;
    const value = xml.getAttribute(attribute);
    if (value) {
      /// TODO (TS): Sort this out.
      (node as any)[opt_name] = value;
    }
  }

  /**
   * Processes the children of the XML node to set text content, child nodes and
   * content nodes of the semantic node.
   *
   * @param node The semantic node.
   * @param xml The XML element representation of the node.
   */
  private static processChildren(node: SemanticNode, xml: Element) {
    for (const child of DomUtil.toArray(xml.childNodes)) {
      if (child.nodeType === DomUtil.NodeType.TEXT_NODE) {
        node.textContent = child.textContent;
        continue;
      }
      const children = DomUtil.toArray(child.childNodes).map(
        SemanticNode.fromXml
      );
      children.forEach((x) => (x.parent = node));
      if (DomUtil.tagName(child) === 'CONTENT') {
        node.contentNodes = children;
      } else {
        node.childNodes = children;
      }
    }
  }

  /**
   * @param id The id number.
   */
  constructor(public id: number) {}

  /**
   * Retrieve all subnodes (including the node itself) that satisfy a given
   * predicate.
   *
   * @param pred The predicate.
   * @returns The nodes in the tree for which the
   *     predicate holds.
   */
  public querySelectorAll(pred: (p1: SemanticNode) => boolean): SemanticNode[] {
    let result: SemanticNode[] = [];
    for (let i = 0, child; (child = this.childNodes[i]); i++) {
      result = result.concat(child.querySelectorAll(pred));
    }
    for (let i = 0, content; (content = this.contentNodes[i]); i++) {
      result = result.concat(content.querySelectorAll(pred));
    }
    if (pred(this)) {
      result.unshift(this);
    }
    return result;
  }

  /**
   * An XML tree representation of the current node.
   *
   * @param xml The XML document.
   * @param brief If set attributes are omitted.
   * @returns The XML representation of the node.
   */
  public xml(xml: Document, brief?: boolean): Node {
    /**
     * Translates a list of nodes into XML representation.
     *
     * @param tag Name of the enclosing tag.
     * @param nodes A list of nodes.
     * @returns An XML representation of the node list.
     */
    const xmlNodeList = function (tag: string, nodes: SemanticNode[]): Node {
      const xmlNodes = nodes.map(function (x) {
        return x.xml(xml, brief);
      });
      const tagNode = xml.createElementNS('', tag);
      for (let i = 0, child; (child = xmlNodes[i]); i++) {
        tagNode.appendChild(child);
      }
      return tagNode;
    };
    const node = xml.createElementNS('', this.type);
    if (!brief) {
      this.xmlAttributes(node);
    }
    node.textContent = this.textContent;
    if (this.contentNodes.length > 0) {
      node.appendChild(xmlNodeList(Attribute.CONTENT, this.contentNodes));
    }
    if (this.childNodes.length > 0) {
      node.appendChild(xmlNodeList(Attribute.CHILDREN, this.childNodes));
    }
    return node;
  }

  /**
   * Serializes the XML representation of a node.
   *
   * @param brief If attributes are to be omitted.
   * @returns Serialized string.
   */
  public toString(brief = false): string {
    const xmls = new SystemExternal.xmldom.XMLSerializer();
    const dp = new SystemExternal.xmldom.DOMParser();
    const xml = dp.parseFromString('<snode/>', 'text/xml');
    return xmls.serializeToString(this.xml(xml, brief));
  }

  /**
   * Computes a list of attributes of the semantic node.
   *
   * @returns A list of
   *     pairs.
   */
  public allAttributes(): [Attribute, string][] {
    const attributes: [Attribute, string][] = [];
    attributes.push([Attribute.ROLE, this.role]);
    if (this.font !== SemanticFont.UNKNOWN) {
      attributes.push([Attribute.FONT, this.font]);
    }
    if (Object.keys(this.annotation).length) {
      attributes.push([Attribute.ANNOTATION, this.xmlAnnotation()]);
    }
    if (this.embellished) {
      attributes.push([Attribute.EMBELLISHED, this.embellished]);
    }
    if (this.fencePointer) {
      attributes.push([Attribute.FENCEPOINTER, this.fencePointer]);
    }
    attributes.push([Attribute.ID, this.id.toString()]);
    return attributes;
  }

  /**
   * Turns annotation structure into an attribute.
   *
   * @returns XML string for annotation.
   */
  public xmlAnnotation(): string {
    const result: string[] = [];
    for (const key in this.annotation) {
      this.annotation[key].forEach(function (mean) {
        result.push(key + ':' + mean);
      });
    }
    return result.join(';');
  }

  /**
   * Turns node into JSON format.
   *
   * @returns The JSON object for the node.
   */
  public toJson(): any {
    const json = {} as any;
    json[Attribute.TYPE] = this.type;
    const attributes = this.allAttributes();
    for (let i = 0, attr; (attr = attributes[i]); i++) {
      json[attr[0]] = attr[1].toString();
    }
    if (this.textContent) {
      json[Attribute.TEXT] = this.textContent;
    }
    if (this.childNodes.length) {
      json[Attribute.CHILDREN] = this.childNodes.map(function (child) {
        return child.toJson();
      });
    }
    if (this.contentNodes.length) {
      json[Attribute.CONTENT] = this.contentNodes.map(function (child) {
        return child.toJson();
      });
    }
    return json;
  }

  /**
   * Updates the content of the node thereby possibly changing type and role.
   *
   * @param content The new content string.
   * @param text Text indicator. If true non-breaking spaces are retained.
   */
  public updateContent(content: string, text?: boolean) {
    // Remove superfluous whitespace only if it is not the only content!
    // But without removing non-breaking spaces if we have a text.
    const newContent = text
      ? content
          .replace(/^[ \f\n\r\t\v\u200b]*/, '')
          .replace(/[ \f\n\r\t\v\u200b]*$/, '')
      : content.trim();
    // TODO (simons): If content contains a space, then assume type to be text.
    content = content && !newContent ? content : newContent;
    if (this.textContent === content) {
      return;
    }
    const meaning = lookupMeaning(content);
    this.textContent = content;
    this.role = meaning.role;
    this.type = meaning.type;
    this.font = meaning.font;
  }

  /**
   * Adds MathML nodes to the node's store of MathML nodes if necessary only, as
   * we can not necessarily assume that the MathML of the content nodes and
   * children are all disjoint.
   *
   * @param mmlNodes List of MathML nodes.
   */
  public addMathmlNodes(mmlNodes: Element[]) {
    for (let i = 0, mml; (mml = mmlNodes[i]); i++) {
      if (this.mathml.indexOf(mml) === -1) {
        this.mathml.push(mml);
      }
    }
  }

  /**
   * Appends a child to the node.
   *
   * @param child The new child.
   */
  public appendChild(child: SemanticNode) {
    this.childNodes.push(child);
    this.addMathmlNodes(child.mathml);
    child.parent = this;
  }

  /**
   * Replaces a child node of the node.
   *
   * @param oldNode The node to be replaced.
   * @param newNode The new node.
   */
  public replaceChild(oldNode: SemanticNode, newNode: SemanticNode) {
    const index = this.childNodes.indexOf(oldNode);
    if (index === -1) {
      return;
    }
    oldNode.parent = null;
    newNode.parent = this;
    this.childNodes[index] = newNode;
    // To not mess up the order of MathML elements more than necessary, we only
    // remove and add difference lists. The hope is that we might end up with
    // little change.
    const removeMathml = oldNode.mathml.filter(function (x) {
      return newNode.mathml.indexOf(x) === -1;
    });
    const addMathml = newNode.mathml.filter(function (x) {
      return oldNode.mathml.indexOf(x) === -1;
    });
    this.removeMathmlNodes(removeMathml);
    this.addMathmlNodes(addMathml);
  }

  /**
   * Appends a content node to the node.
   *
   * @param node The new content node.
   */
  public appendContentNode(node: SemanticNode) {
    if (node) {
      this.contentNodes.push(node);
      this.addMathmlNodes(node.mathml);
      node.parent = this;
    }
  }

  /**
   * Removes a content node from the node.
   *
   * @param node The content node to be removed.
   */
  public removeContentNode(node: SemanticNode) {
    if (node) {
      const index = this.contentNodes.indexOf(node);
      if (index !== -1) {
        this.contentNodes.slice(index, 1);
      }
    }
  }

  /**
   * Tests if node is equal to the given node. Two nodes are considered equal if
   * they have the same type, role, content and all its children are equal.
   *
   * @param node The node to test against.
   * @returns True if nodes are equal wrt. structure and content.
   */
  public equals(node: SemanticNode): boolean {
    if (!node) {
      return false;
    }
    if (
      this.type !== node.type ||
      this.role !== node.role ||
      this.textContent !== node.textContent ||
      this.childNodes.length !== node.childNodes.length ||
      this.contentNodes.length !== node.contentNodes.length
    ) {
      return false;
    }
    for (
      let i = 0, node1, node2;
      (node1 = this.childNodes[i]), (node2 = node.childNodes[i]);
      i++
    ) {
      if (!node1.equals(node2)) {
        return false;
      }
    }
    for (
      let i = 0, node1, node2;
      (node1 = this.contentNodes[i]), (node2 = node.contentNodes[i]);
      i++
    ) {
      if (!node1.equals(node2)) {
        return false;
      }
    }
    return true;
  }

  /**
   * Convenience method to display the whole tree and its elements.
   */
  public displayTree() {
    console.info(this.displayTree_(0));
  }

  /**
   * Adds a new annotation annotation if annotation is not empty.
   *
   * @param domain The domain.
   * @param annotation The annotation.
   */
  public addAnnotation(domain: string, annotation: string) {
    if (annotation) {
      this.addAnnotation_(domain, annotation);
    }
  }

  /**
   * Retrieves the annotation annotations for a particular domain.
   *
   * @param domain The domain.
   * @returns The annotation annotations.
   */
  public getAnnotation(domain: string): string[] {
    const content = this.annotation[domain];
    return content ? content : [];
  }

  /**
   * Checks if a node has a particular annotation.
   *
   * @param domain The domain.
   * @param annotation The annotation.
   * @returns True if the annotation is contained.
   */
  public hasAnnotation(domain: string, annotation: string): boolean {
    const content = this.annotation[domain];
    if (!content) {
      return false;
    }
    return content.indexOf(annotation) !== -1;
  }

  /**
   * Parses a annotation string as given, for example, in an attribute.
   *
   * @param stateStr The state string for the annotation.
   */
  public parseAnnotation(stateStr: string) {
    const annotations = stateStr.split(';');
    for (let i = 0, l = annotations.length; i < l; i++) {
      const annotation = annotations[i].split(':');
      this.addAnnotation(annotation[0], annotation[1]);
    }
  }

  /**
   * @returns The semantic meaning of the node.
   */
  public meaning(): SemanticMeaning {
    return { type: this.type, role: this.role, font: this.font };
  }

  /**
   * Adds attributes to the XML representation of the current node.
   *
   * @param node The XML node.
   */
  private xmlAttributes(node: Element) {
    const attributes = this.allAttributes();
    for (let i = 0, attr; (attr = attributes[i]); i++) {
      node.setAttribute(attr[0], attr[1]);
    }
    this.addExternalAttributes(node);
  }

  /**
   * Adds the external attributes for this node to its XML representation.
   *
   * @param node The XML node.
   */
  private addExternalAttributes(node: Element) {
    for (const attr in this.attributes) {
      node.setAttribute(attr, this.attributes[attr]);
    }
  }

  /**
   * Removes MathML nodes from the node's store of MathML nodes.
   *
   * @param mmlNodes List of MathML nodes.
   */
  private removeMathmlNodes(mmlNodes: Element[]) {
    const mmlList = this.mathml;
    for (let i = 0, mml; (mml = mmlNodes[i]); i++) {
      const index = mmlList.indexOf(mml);
      if (index !== -1) {
        mmlList.splice(index, 1);
      }
    }
    this.mathml = mmlList;
  }

  /**
   * Convenience method to display the whole tree and its elements.
   *
   * @param depth The depth of the tree.
   * @returns String with nested tree display.
   */
  private displayTree_(depth: number): string {
    depth++;
    const depthString = Array(depth).join('  ');
    let result = '';
    result += '\n' + depthString + this.toString();
    result += '\n' + depthString + 'MathmlTree:';
    result += '\n' + depthString + this.mathmlTreeString();
    result += '\n' + depthString + 'MathML:';
    for (let i = 0, mml; (mml = this.mathml[i]); i++) {
      result += '\n' + depthString + mml.toString();
    }
    result += '\n' + depthString + 'Begin Content';
    this.contentNodes.forEach(function (x) {
      result += x.displayTree_(depth);
    });
    result += '\n' + depthString + 'End Content';
    result += '\n' + depthString + 'Begin Children';
    this.childNodes.forEach(function (x) {
      result += x.displayTree_(depth);
    });
    result += '\n' + depthString + 'End Children';
    return result;
  }

  /**
   * Returns a display version of the node's associated MathML tree.
   *
   * @returns The MathML tree as string or EMPTY.
   */
  private mathmlTreeString(): string {
    return this.mathmlTree ? this.mathmlTree.toString() : 'EMPTY';
  }

  /**
   * Adds a new annotation annotation.
   *
   * @param domain The domain.
   * @param annotation The annotation.
   */
  private addAnnotation_(domain: string, annotation: string) {
    const content = this.annotation[domain];
    if (content) {
      content.push(annotation);
    } else {
      this.annotation[domain] = [annotation];
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#B06AB3"
        android:endColor="#4568DC"
        android:type="linear"
        android:angle="315"/>

</shape>


text:
package com.navercorp.pinpoint.profiler.context;

import java.util.List;

/**
 * @author Woonduk Kang(emeroad)
 */
public interface SpanChunkFactory {
    SpanChunk newSpanChunk(List<SpanEvent> spanEventList);
}


text:
PicoYPlacaApp
=============

Ver el pico y placa nunca fue tan fácil.


text:
package com.tesshu.subsonic.client.fx.view.radio;

import com.tesshu.subsonic.client.fx.view.ICustomTabContent;

public interface InternetRadioContainer extends ICustomTabContent {

}


text:
package jsonpath

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

type optest struct {
	name     string
	path     string
	expected []int
}

var optests = []optest{
	optest{"single key (period) ", `$.aKey`, []int{opTypeName}},
	optest{"single key (bracket)", `$["aKey"]`, []int{opTypeName}},
	optest{"single key (period) ", `$.*`, []int{opTypeNameWild}},
	optest{"single index", `$[12]`, []int{opTypeIndex}},
	optest{"single key", `$[23:45]`, []int{opTypeIndexRange}},
	optest{"single key", `$[*]`, []int{opTypeIndexWild}},

	optest{"double key", `$["aKey"]["bKey"]`, []int{opTypeName, opTypeName}},
	optest{"double key", `$["aKey"].bKey`, []int{opTypeName, opTypeName}},
}

func TestQueryOperators(t *testing.T) {
	as := assert.New(t)

	for _, t := range optests {
		path, err := parsePath(t.path)
		as.NoError(err)

		as.EqualValues(len(t.expected), len(path.operators))

		for x, op := range t.expected {
			as.EqualValues(pathTokenNames[op], pathTokenNames[path.operators[x].typ])
		}
	}
}


text:
package org.ovirt.engine.ui.webadmin.section.main.presenter.popup.configure;

import org.ovirt.engine.ui.common.presenter.AbstractModelBoundPopupPresenterWidget;
import org.ovirt.engine.ui.uicommonweb.models.configure.roles_ui.RoleModel;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;

public class RolePopupPresenterWidget extends AbstractModelBoundPopupPresenterWidget<RoleModel, RolePopupPresenterWidget.ViewDef> {

    public interface ViewDef extends AbstractModelBoundPopupPresenterWidget.ViewDef<RoleModel> {
    }

    @Inject
    public RolePopupPresenterWidget(EventBus eventBus, ViewDef view) {
        super(eventBus, view);
    }

}


text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { SegundoComponent } from './segundo.component';

describe('SegundoComponent', () => {
  let component: SegundoComponent;
  let fixture: ComponentFixture<SegundoComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ SegundoComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SegundoComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});


text:
/* /////////////////////////////////////////////////////////////////////////
 * File:        examples/cpp/inserters/example.cpp.inserter.hex_ptr/example.cpp.inserter.hex_ptr.cpp
 *
 * Purpose:     C++ example program for Pantheios. Demonstrates:
 *
 *                - use of Pantheios::hex_ptr inserter class for pointer
 *                  types
 *                - use of pantheios::logputs() in bail-out conditions
 *
 * Created:     11th November 2008
 * Updated:     6th August 2012
 *
 * www:         http://www.pantheios.org/
 *
 * License:     This source code is placed into the public domain 2006
 *              by Synesis Software Pty Ltd. There are no restrictions
 *              whatsoever to your use of the software.
 *
 *              This software is provided "as is", and any warranties,
 *              express or implied, of any kind and for any purpose, are
 *              disclaimed.
 *
 * ////////////////////////////////////////////////////////////////////// */

#define PANTHEIOS_NO_INCLUDE_OS_AND_3PTYLIB_STRING_ACCESS // Faster compilation

/* Pantheios Header Files */
#include <pantheios/pantheios.hpp>            // Pantheios C++ main header
#include <pantheios/inserters/hex_ptr.hpp>    // for pantheios::hex_ptr

/* Standard C/C++ Header Files */
#include <exception>                          // for std::exception
#include <new>                                // for std::bad_alloc
#include <string>                             // for std::string
#include <stdlib.h>                           // for exit codes

/* ////////////////////////////////////////////////////////////////////// */

/* Define the stock front-end process identity, so that it links when using
 * fe.N, fe.simple, etc. */
PANTHEIOS_EXTERN_C const PAN_CHAR_T PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING("example.cpp.inserter.hex_ptr");

/* ////////////////////////////////////////////////////////////////////// */

#define PSTR(x)         PANTHEIOS_LITERAL_STRING(x)

/* ////////////////////////////////////////////////////////////////////// */

int main()
{
  try
  {
    void* pv = &pv;

    // Log a hex_ptr of precise length with 0x prefix, a length
    // of 8/16 (depending on architecture), and zero-padded;
    // Output: "pv: [0x0012fed0]"

    pantheios::log_NOTICE(PSTR("pv: ["), pantheios::hex_ptr(pv), PSTR("]"));

    // Log a hex_ptr of precise length with 0x prefix;
    // Output: "pv: [0x12fed0]"

    pantheios::log_NOTICE(PSTR("pv: ["), pantheios::hex_ptr(pv, 0, pantheios::fmt::zeroXPrefix), PSTR("]"));

    // Log a hex_ptr into 8 spaces, right justified, with 0x prefix;
    // Output: "pv: [  0x12fed0]"

    pantheios::log_NOTICE(PSTR("pv: ["), pantheios::hex_ptr(pv, 8, pantheios::fmt::zeroXPrefix), PSTR("]"));

    // Log a hex_ptr into 8 spaces, left justified, with 0x prefix;
    // Output: "pv: [0x12fed0  ]"

    pantheios::log_NOTICE(PSTR("pv: ["), pantheios::hex_ptr(pv, -8, pantheios::fmt::zeroXPrefix), PSTR("]"));

    // Log a hex_ptr of precise length with 0x prefix, a length of 16,
    // and zero-padded; Output: "pv: [0x000000000012fed0]"

    pantheios::log_NOTICE(PSTR("pv: ["), pantheios::hex_ptr(pv, 16, pantheios::fmt::zeroPad | pantheios::fmt::zeroXPrefix), PSTR("]"));

    // Log a hex_ptr of precise length with 0x prefix, a length
    // appropriate to the architecture, and zero-padded;
    // Output: "pv: [0x0012fed0]"

    pantheios::log_NOTICE(PSTR("pv: ["), pantheios::hex_ptr(pv, pantheios::hex_ptr::pointerHexWidth, pantheios::fmt::fullHex), PSTR("]"));

    return EXIT_SUCCESS;
  }
  catch(std::bad_alloc&)
  {
    pantheios::log(pantheios::alert, PSTR("out of memory"));
  }
  catch(std::exception& x)
  {
    pantheios::log_CRITICAL(PSTR("Exception: "), x);
  }
  catch(...)
  {
    pantheios::logputs(pantheios::emergency, PSTR("Unexpected unknown error"));
  }

  return EXIT_FAILURE;
}

/* ///////////////////////////// end of file //////////////////////////// */


text:
/* Code, Pre [landscape](http://goo.gl/hnwXeD) */

/* highlight */

pre, .highlight, .gist {
  background: #333 !important;
  margin: 0.5em 0;
  padding: 1em 2%;
  overflow: auto;
  color: #ccc;
  font-size: 14px;
  text-shadow: none;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  border-style: solid;
  border-color: #ddd;
  border-width: 1px 0;
  line-height: 20px;
}

code {
  background: #eee;
  border: 1px solid #d6d6d6;
  padding: 0 5px;
  margin: 0 2px;
  font-size: 90%;
  text-shadow: 0 1px #fff;
  word-break: break-all;
  word-wrap: break-word;
  white-space: normal;
}

.highlight .gutter pre{
  text-align: left;
  padding-right: 20px;
  width: 100%;
  color: #666;
}

pre,
code {
  font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace;
}

pre code {
  background: none;
  text-shadow: none;
  padding: 0;
}

.highlight pre {
  border: none;
  margin: 0;
  padding: 0;
  white-space: pre;
}

.highlight table {
  margin: 0;
  width: auto;
}

.highlight td {
  border: none;
  padding: 0;
}

/* gist */

.container .gist .gist-file {
  border: none;
  font-family: Menlo, "Bitstream Vera Sans Mono", "DejaVu Sans Mono", Monaco, Consolas, monospace;
  margin: 0;
}
.container .gist .gist-file .gist-data {
  background: none;
  border: none;
}
.container .gist .gist-file .gist-data .line-numbers {
  background: none;
  border: none;
  padding-right: 20px;
  color: #666;
  text-align: left;
}
.container .gist .gist-file .gist-data .line-data {
  padding: 0 !important;
}
.container .gist .gist-file .highlight {
  margin: 0;
  padding: 0;
  border: none;
}
.container .gist .gist-file .gist-meta {
  background: #333;
  color: #999;
  font: 0.85em "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-shadow: 0 0;
  padding: 0;
  margin-top: 1em;
  margin-left: 20px;
}
.container .gist .gist-file .gist-meta a {
  color: #258fb8;
  font-weight: normal;
}
.container .gist .gist-file .gist-meta a:hover {
  text-decoration: underline;
}

/* figcaption */

.highlight figcaption {
  zoom: 1;
  font-size: 0.85em;
  color: #999;
  line-height: 1em;
  margin-bottom: 1em;
}
.highlight figcaption:before,
.highlight figcaption:after {
  content: "";
  display: table;
}
.highlight figcaption:after {
  clear: both;
}
.highlight figcaption a {
  float: right;
}

pre .comment,
pre .title {
  color: #999;
}
pre .variable,
pre .attribute,
pre .tag,
pre .regexp,
pre .ruby .constant,
pre .xml .tag .title,
pre .xml .pi,
pre .xml .doctype,
pre .html .doctype,
pre .css .id,
pre .css .class,
pre .css .pseudo {
  color: #f2777a;
}
pre .number,
pre .preprocessor,
pre .built_in,
pre .literal,
pre .params,
pre .constant {
  color: #f99157;
}
pre .class,
pre .ruby .class .title,
pre .css .rules .attribute {
  color: #9c9;
}
pre .string,
pre .value,
pre .inheritance,
pre .header,
pre .ruby .symbol,
pre .xml .cdata {
  color: #9c9;
}
pre .css .hexcolor {
  color: #6cc;
}
pre .function,
pre .python .decorator,
pre .python .title,
pre .ruby .function .title,
pre .ruby .title .keyword,
pre .perl .sub,
pre .javascript .title,
pre .coffeescript .title {
  color: #69c;
}
pre .keyword,
pre .javascript .function {
  color: #c9c;
}


text:
title: "Scientific Success in Context"
collection: talks
type: "Seminar"
slidesurl: 'https://www.dropbox.com/s/lgficitsnge65dw/2021-northwestern.pdf?dl=0'
citation: "Job Talk, CCNR @ Northeastern University, December, 2020"
date: 2020-12-15
---

This is a description of your conference proceedings talk, note the different field in type. You can put anything in this field.


text:
* Hello

[World][google]

[google]: https://www.google.com/


text:
require_relative "client"
require_relative "installer"

module VagrantPlugins
  module Docker
    class DockerError < Vagrant::Errors::VagrantError
      error_namespace("vagrant.provisioners.docker")
    end

    # TODO: Improve handling of vagrant-lxc specifics (like checking for apparmor
    #       profile stuff + autocorrection)
    class Provisioner < Vagrant.plugin("2", :provisioner)
      def initialize(machine, config, installer = nil, client = nil)
        super(machine, config)

        @installer = installer || Installer.new(@machine, config.version)
        @client    = client    || Client.new(@machine)
      end

      def provision
        @logger = Log4r::Logger.new("vagrant::provisioners::docker")

        @logger.info("Checking for Docker installation...")
        @installer.ensure_installed

        # Attempt to start service if not running
        @client.start_service
        raise DockerError, :not_running if !@client.daemon_running?

        if config.images.any?
          @machine.ui.info(I18n.t("vagrant.docker_pulling_images"))
          @client.pull_images(*config.images)
        end

        if config.containers.any?
          @machine.ui.info(I18n.t("vagrant.docker_starting_containers"))
          @client.run(config.containers)
        end
      end
    end
  end
end


text:
package com.eveningoutpost.dexdrip;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.eveningoutpost.dexdrip.Models.Calibration;
import com.eveningoutpost.dexdrip.UtilityModels.CollectionServiceStarter;

public class DoubleCalibrationActivity  extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks {
    Button button;
    private String menu_name = "Add Double Calibration";
    private NavigationDrawerFragment mNavigationDrawerFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(CollectionServiceStarter.isBTShare(getApplicationContext())) {
            Intent intent = new Intent(this, Home.class);
            startActivity(intent);
            finish();
        }
        setContentView(R.layout.activity_double_calibration);
        addListenerOnButton();
    }

    @Override
    protected void onResume(){
        super.onResume();
        mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);
        mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), menu_name, this);
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        mNavigationDrawerFragment.swapContext(position);
    }

    public void addListenerOnButton() {

        button = (Button) findViewById(R.id.save_calibration_button);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                if (Sensor.isActive()) {
                    EditText value_1 = (EditText) findViewById(R.id.bg_value_1);
                    EditText value_2 = (EditText) findViewById(R.id.bg_value_2);
                    String string_value_1 = value_1.getText().toString();
                    String string_value_2 = value_2.getText().toString();

                    if (!TextUtils.isEmpty(string_value_1)){
                        if(!TextUtils.isEmpty(string_value_2)) {
                            double calValue_1 = Double.parseDouble(string_value_1);
                            double calValue_2 = Double.parseDouble(string_value_2);
                            Calibration.initialCalibration(calValue_1, calValue_2, getApplicationContext());
                            Intent tableIntent = new Intent(v.getContext(), Home.class);
                            startActivity(tableIntent);
                            finish();
                        } else {
                            value_2.setError("Calibration Can Not be blank");
                        }
                    } else {
                        value_1.setError("Calibration Can Not be blank");
                    }
                } else {
                    Log.w("DoubleCalibration", "ERROR");
                }
            }
        });

    }
}


text:
(function ($) {
  $.fn.collapsible = function(options) {
    var defaults = {
        accordion: true
    };

    options = $.extend(defaults, options);

    return this.each(function() {

      var $this = $(this);

      var $panel_headers = $(this).find('.collapsible-header');

      // Accordion Open
      function accordionOpen(object) {
        object.parent().toggleClass('active');
        if (object.parent().hasClass('active')){
          object.siblings('.collapsible-body').stop(true,false).slideDown({ duration: 350, easing: "easeOutQuart", queue: false});
        }
        else{
          object.siblings('.collapsible-body').stop(true,false).slideUp({ duration: 350, easing: "easeOutQuart", queue: false});
        }
        $panel_headers.not(object).parent().removeClass('active');
        $panel_headers.not(object).parent().children('.collapsible-body').stop(true,false).slideUp({ duration: 350, easing: "easeOutQuart", queue: false});
      }

      // Collapsible Open
      function collapsibleOpen(object) {
        object.parent().toggleClass('active');
        if (object.parent().hasClass('active')){
          object.siblings('.collapsible-body').stop(true,false).slideDown({ duration: 350, easing: "easeOutQuart", queue: false});
        }
        else{
          object.siblings('.collapsible-body').stop(true,false).slideUp({ duration: 350, easing: "easeOutQuart", queue: false});
        }
      }

      if (defaults.accordion) {

        $panel_headers.each(function () {
          $(this).click(function () {
            accordionOpen($(this));
          });
        });

        // Open first active
        accordionOpen($panel_headers.filter('.active').first());
      }
      else {
        $panel_headers.each(function () {

          // Open any bodies that have the active class
          if ($(this).hasClass('active')) {
            collapsibleOpen($(this));
          }

          $(this).click(function () {
            collapsibleOpen($(this));
          });
        });
      }

    });
  };
}( jQuery ));


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [AVOSCloud setApplicationId:@"gygk6k80xeVgrlVM2PkeEzsW"
                      clientKey:@"PupC2Jsgb9wzzaDOuyW8hExC"];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    DiscoverController *discoverVC = [[DiscoverController alloc]initWithStyle:UITableViewStylePlain];
    UINavigationController *discoverNC = [[UINavigationController alloc]initWithRootViewController:discoverVC];

    UINavigationController *RadioNC = [[UINavigationController alloc]initWithRootViewController:[RadioController new]];
    RadioNC.tabBarItem.title = @"电台";
    RadioNC.tabBarItem.image = [UIImage imageNamed:@"iconfont-svgmoban16"];

    MineController *mineVC = [MineController new];
    UINavigationController *mineNC = [[UINavigationController alloc]initWithRootViewController:mineVC];

    PlayerController *playerVC = [[PlayerController alloc]init];
    UINavigationController *playerNC = [[UINavigationController alloc]initWithRootViewController:playerVC];
    playerVC.title = @"播放";

    //图片必须是镂空的
    UIImage *image4 = [UIImage imageNamed:@"bofangyemian"];
    //图片渲染(保持原有的特性)(如果图片不是镂空的,必须渲染)
    image4 = [image4 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];//翻译;表现  //模式  //原始的;最初的
    playerVC.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"播放" image:image4 selectedImage:image4];

    NSArray *allNC = @[discoverNC,RadioNC,playerNC,mineNC];

    UITabBarController *tabBarVC = [[UITabBarController alloc]init];

    tabBarVC.viewControllers = allNC;

    self.window.rootViewController = tabBarVC;

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end