text:
(function ($) {
  // register namespace
  $.extend(true, window, {
    "Slick": {
      "CellRangeSelector": CellRangeSelector
    }
  });

  function CellRangeSelector(options) {
    var _grid;
    var _canvas;
    var _dragging;
    var _decorator;
    var _self = this;
    var _handler = new Slick.EventHandler();
    var _defaults = {
      selectionCss: {
        "border": "2px dashed blue"
      }
    };

    function init(grid) {
      options = $.extend(true, {}, _defaults, options);
      _decorator = new Slick.CellRangeDecorator(grid, options);
      _grid = grid;
      _canvas = _grid.getCanvasNode();
      _handler
        .subscribe(_grid.onDragInit, handleDragInit)
        .subscribe(_grid.onDragStart, handleDragStart)
        .subscribe(_grid.onDrag, handleDrag)
        .subscribe(_grid.onDragEnd, handleDragEnd);
    }

    function destroy() {
      _handler.unsubscribeAll();
    }

    function handleDragInit(e, dd) {
      // prevent the grid from cancelling drag'n'drop by default
      e.stopImmediatePropagation();
    }

    function handleDragStart(e, dd) {
      var cell = _grid.getCellFromEvent(e);
      if (_self.onBeforeCellRangeSelected.notify(cell) !== false) {
        if (_grid.canCellBeSelected(cell.row, cell.cell)) {
          _dragging = true;
          e.stopImmediatePropagation();
        }
      }
      if (!_dragging) {
        return;
      }

      _grid.focus();

      var start = _grid.getCellFromPoint(
          dd.startX - $(_canvas).offset().left,
          dd.startY - $(_canvas).offset().top);

      dd.range = {start: start, end: {}};

      return _decorator.show(new Slick.Range(start.row, start.cell));
    }

    function handleDrag(e, dd) {
      if (!_dragging) {
        return;
      }
      e.stopImmediatePropagation();

      var end = _grid.getCellFromPoint(
          e.pageX - $(_canvas).offset().left,
          e.pageY - $(_canvas).offset().top);

      if (!_grid.canCellBeSelected(end.row, end.cell)) {
        return;
      }

      dd.range.end = end;
      _decorator.show(new Slick.Range(dd.range.start.row, dd.range.start.cell, end.row, end.cell));
    }

    function handleDragEnd(e, dd) {
      if (!_dragging) {
        return;
      }

      _dragging = false;
      e.stopImmediatePropagation();

      _decorator.hide();
      _self.onCellRangeSelected.notify({
        range: new Slick.Range(
            dd.range.start.row,
            dd.range.start.cell,
            dd.range.end.row,
            dd.range.end.cell
        )
      });
    }

    $.extend(this, {
      "init": init,
      "destroy": destroy,

      "onBeforeCellRangeSelected": new Slick.Event(),
      "onCellRangeSelected": new Slick.Event()
    });
  }
})(jQuery);


text:
cask "deezer" do
  version "5.30.370-rc.0"
  sha256 "3b3cd805573f1e7d69734456115e3e72b923c40507d233e3f97d78867c16a29a"

  url "https://www.deezer.com/desktop/download/artifact/darwin/x64/#{version}"
  name "Deezer"
  desc "Music player"
  homepage "https://www.deezer.com/download"

  livecheck do
    url "https://www.deezer.com/desktop/download?platform=darwin&architecture=x64"
    strategy :header_match
  end

  auto_updates true
  depends_on macos: ">= :high_sierra"

  app "Deezer.app"

  zap trash: [
    "~/Library/Application Support/Caches/deezer-desktop-updater",
    "~/Library/Application Support/deezer-desktop",
    "~/Library/Caches/com.deezer.deezer*",
    "~/Library/Logs/Deezer",
    "~/Library/Logs/deezer-desktop",
    "~/Library/Preferences/ByHost/com.deezer.*",
    "~/Library/Preferences/com.deezer.deezer-desktop.plist",
    "~/Library/Saved Application State/com.deezer.deezer-desktop.savedState",
  ]
end

redpajama_set_name: RedPajamaGithub


text:
namespace GeodesicDist
{

    class CExactOneToAll
    {
    protected:
        void* m_pVertices;
        uint32_t* m_pIndices;
        uint32_t* m_pAdj;
        size_t m_dwNumBytesPerVertex;
        size_t m_dwNumFaces;
        size_t  m_dwNumVertices;
        uint32_t m_dwSrcVertexIdx;

        EdgeWindow m_AnotherNewWindow;
        EdgeWindow m_NewExistingWindow;

        TypeEdgeWindowsHeap m_EdgeWindowsHeap;

        virtual void CutHeapTopData(EdgeWindow& EdgeWindowOut);
        void ProcessNewWindow(EdgeWindow* pNewEdgeWindow);
        void IntersectWindow(EdgeWindow* pExistingWindow,
            EdgeWindow* pNewWindow,
            bool* pExistingWindowChanged,
            bool* pNewWindowChanged,
            bool* pExistingWindowNotAvailable,
            bool* pNewWindowNotAvailable);
        void GenerateWindowsAroundSaddleOrBoundaryVertex(const EdgeWindow& WindowToBePropagated,
            const uint32_t dwSaddleOrBoundaryVertexId,
            std::vector<EdgeWindow>& WindowsOut);
        void InternalRun();
        void AddWindowToHeapAndEdge(const EdgeWindow& WindowToAdd);

    public:
        TypeEdgeList m_EdgeList;
        TypeFaceList m_FaceList;
        TypeVertexList m_VertexList;

        EdgeWindow tmpWindow0; // window that is to be processed (to be inserted on edge and into heap)
        EdgeWindow WindowToBePropagated; // window that is just popped off the heap

        CExactOneToAll();
        virtual ~CExactOneToAll() = default;

        // set the source vertex index before run
        void SetSrcVertexIdx(const uint32_t dwSrcVertexIdx);

        // run the algorithm
        void Run();
    };

}


text:
using System;
using System.Linq;
using Microsoft.WindowsAzure.Management.Automation.Models;

namespace Microsoft.WindowsAzure.Management.Automation.Models
{
    /// <summary>
    /// The parameters supplied to the create connection type operation.
    /// </summary>
    public partial class ConnectionTypeCreateParameters
    {
        private string _name;

        /// <summary>
        /// Required. Gets or sets the name of the connection type.
        /// </summary>
        public string Name
        {
            get { return this._name; }
            set { this._name = value; }
        }

        private ConnectionTypeCreateProperties _properties;

        /// <summary>
        /// Required. Gets or sets the value of the connection type.
        /// </summary>
        public ConnectionTypeCreateProperties Properties
        {
            get { return this._properties; }
            set { this._properties = value; }
        }

        /// <summary>
        /// Initializes a new instance of the ConnectionTypeCreateParameters
        /// class.
        /// </summary>
        public ConnectionTypeCreateParameters()
        {
        }

        /// <summary>
        /// Initializes a new instance of the ConnectionTypeCreateParameters
        /// class with required arguments.
        /// </summary>
        public ConnectionTypeCreateParameters(string name, ConnectionTypeCreateProperties properties)
            : this()
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }
            this.Name = name;
            this.Properties = properties;
        }
    }
}


text:
package org.schors.vertx.telegram.bot.api.methods;

public class DeleteWebhook extends TelegramMethod {
    @Override
    public String getMethod() {
        return "deleteWebhook";
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Example</title>

  <link href="../../dist/modular/css/core.css" rel="stylesheet" type="text/css">
  <link href="../../dist/modular/css/grid.css" rel="stylesheet" type="text/css">

 <button class="gj-button-md" id="btnRemove">Remove</button>


text:
@interface HomeTwoViewController ()

@property (strong, nonatomic) HomeTwoViewModel *viewModel;
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *pwd;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@end

@implementation HomeTwoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    RAC(self.viewModel, userName) = self.userName.rac_textSignal;
    RAC(self.viewModel, pwd) = self.pwd.rac_textSignal;

    __weak typeof(self) weakSelf = self;
    [[self.loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [[weakSelf.viewModel fetchLogin] subscribeNext:^(id x) {

        } error:^(NSError *error) {

        }];
    }];

}

- (void)dealloc {
    DDLogMethod();
}

- (HomeTwoViewModel *)viewModel {
    if (_viewModel == nil) {
        _viewModel = [[HomeTwoViewModel alloc] init];
    }

    return _viewModel;
}

@end


text:
/// <reference path="~/Client/Vendor/knockout.js"/>
/// <reference path="~/Client/Vendor/moment.js"/>
/// <reference path="~/Client/Shared/ko/validation/objectWithValidateableProperties.js"/>
/// <reference path="~/Client/Shared/Modal.js" />
/// <reference path="~/Client/Shared/Base.js" />

var AddReminderForm = Base.inherit({
    init: function (viewData, http) {
        this.http = http;
        this.addCommand = viewData.add;
        this.initInputs();
        this.initValidation();
    },

    templateId: "Client/Vehicles/Reminders/AddReminderForm.htm",

    initInputs: function () {
        this.title = ko.observable();
        this.remarks = ko.observable();
        this.dueDate = ko.observable();
        this.dueDistance = ko.observable();
    },

    initValidation: function () {
        this.title.extend({
            validation: { required: "Title is required" }
        });
        this.dueDistance.extend({
            validation: {}
        });
    },

    show: function () {
        this.modal = Modal.create(this);
        return this.modal.result;
    },

    close: function (reminderData) {
        this.modal.closeWithResult(reminderData);
    },

    submit: function () {
        if (!this.validate()) return;
        var formData = this.formData();
        this.http(this.addCommand, formData)
            .pipe(this.getCreatedReminder.bind(this))
            .done(this.close.bind(this))
            .fail(this.submitFailed.bind(this));
    },

    getCreatedReminder: function (response, status, xhr) {
        var reminderUrl = xhr.getResponseHeader("Location");
        return this.http({ method: "get", url: reminderUrl });
    },

    formData: function () {
        var dueDistance = this.dueDistance();
        var dueDate = this.dueDate();
        var data = {
            title: this.title(),
            remarks: this.remarks()
        };
        if (dueDate) data.dueDate = moment(dueDate).format("YYYY-MM-DD");
        if (dueDistance) data.dueDistance = dueDistance;
        return data;
    },

    cancel: function () {
        this.modal.close();
    },

    submitFailed: function (response) {
        if (response.validationErrors) {
            Object.keys(response.validationErrors).forEach(function (key) {
                var property = this[key];
                if (property && property.validation) {
                    property.validation.message(response.validationErrors[key].join(". "));
                }
            }, this);
        } else {
            alert("There was a problem adding the reminder. Please try again.");
        }
    }
}).mixin(objectWithValidateableProperties);


text:
<?php

namespace Magium\Mail;

use Magium\AbstractConfigurableElement;
use Magium\Mail\Api\MissingAPIKeyException;
use Zend\Uri\Http;

class Configuration extends AbstractConfigurableElement
{

    const LOCATOR = 'Magium\Mail\Configuration';

    protected $apiKey;
    protected $apiEndpointUrl = 'https://magiumlib.com/mail/api/generateAccount';
    protected $webmailEndpointUrl = 'https://magiumlib.com/mail/webmail';

    /**
     * @return string
     */
    public function getApiKey()
    {
        return $this->apiKey;
    }

    /**
     * @return string
     */
    public function getApiEndpointUrl()
    {
        return $this->buildUrl($this->apiEndpointUrl);
    }

    /**
     * @return string
     */
    public function getWebmailEndpointUrl()
    {
        return $this->buildUrl($this->webmailEndpointUrl);
    }

    protected function buildUrl($url)
    {
        if (!$this->apiKey) {
            throw new MissingAPIKeyException('Missing the API key.  Please either call setApiKey(), set the API key as a dependency parameter, or create a Magium/Mail/GeneratorConfiguration.php file to set the API key');
        }
        $uri = new Http($url);
        $uri->setQuery(['key' => $this->apiKey]);
        return $uri->toString();
    }

    /**
     * @param string $apiEndpointUrl
     */
    public function setApiEndpointUrl($apiEndpointUrl)
    {
        $this->apiEndpointUrl = $apiEndpointUrl;
    }

    /**
     * @param mixed $apiKey
     */
    public function setApiKey($apiKey)
    {
        $this->apiKey = $apiKey;
    }

    /**
     * @param string $webmailEndpointUrl
     */
    public function setWebmailEndpointUrl($webmailEndpointUrl)
    {
        $this->webmailEndpointUrl = $webmailEndpointUrl;
    }

}


text:
(function() {

    // Matter aliases
    var Engine = Matter.Engine,
        World = Matter.World,
        Bodies = Matter.Bodies,
        Body = Matter.Body,
        Composite = Matter.Composite,
        Composites = Matter.Composites,
        Common = Matter.Common,
        Constraint = Matter.Constraint,
        RenderPixi = Matter.RenderPixi,
        Events = Matter.Events,
        Bounds = Matter.Bounds,
        Vector = Matter.Vector,
        Vertices = Matter.Vertices,
        MouseConstraint = Matter.MouseConstraint,
        Mouse = Matter.Mouse,
        Query = Matter.Query;

    // MatterTools aliases
    if (window.MatterTools) {
        var Gui = MatterTools.Gui,
            Inspector = MatterTools.Inspector;
    }

    var Demo = {};

    var _engine,
        _gui,
        _inspector,
        _sceneName,
        _mouseConstraint,
        _sceneEvents = [],
        _useInspector = window.location.hash.indexOf('-inspect') !== -1,
        _isMobile = /(ipad|iphone|ipod|android)/gi.test(navigator.userAgent);

    // initialise the demo

    Demo.init = function() {
        var container = document.getElementById('canvas-container');

        // some example engine options
        var options = {
            positionIterations: 6,
            velocityIterations: 4,
            enableSleeping: false
        };

        // create a Matter engine
        // NOTE: this is actually Matter.Engine.create(), see the aliases at top of this file
        _engine = Engine.create(container, options);

        // add a mouse controlled constraint
        _mouseConstraint = MouseConstraint.create(_engine);
        World.add(_engine.world, _mouseConstraint);

        // run the engine
        Engine.run(_engine);

        // default scene function name
        _sceneName = 'mixed';

        // get the scene function name from hash
        if (window.location.hash.length !== 0)
            _sceneName = window.location.hash.replace('#', '').replace('-inspect', '');

        // set up a scene with bodies
        Demo[_sceneName]();

        // set up demo interface (see end of this file)
        Demo.initControls();
    };

    // call init when the page has loaded fully

    if (window.addEventListener) {
        window.addEventListener('load', Demo.init);
    } else if (window.attachEvent) {
        window.attachEvent('load', Demo.init);
    }

    // each demo scene is set up in its own function, see below

    Demo.mixed = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(20, 20, 15, 4, 0, 0, function(x, y, column, row) {
            var sides = Math.round(Common.random(1, 8));

            // triangles can be a little unstable, so avoid until fixed
            // TODO: make triangles more stable
            sides = (sides === 3) ? 4 : sides;

            // round the edges of some bodies
            var chamfer = null;
            if (sides > 2 && Math.random() > 0.7) {
                chamfer = {
                    radius: 10
                };
            }

            switch (Math.round(Common.random(0, 1))) {
            case 0:
                if (Math.random() < 0.8) {
                    return Bodies.rectangle(x, y, Common.random(25, 50), Common.random(25, 50), { chamfer: chamfer });
                } else {
                    return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(25, 30), { chamfer: chamfer });
                }
                break;
            case 1:
                return Bodies.polygon(x, y, sides, Common.random(25, 50), { chamfer: chamfer });
            }
        });

        World.add(_world, stack);

        var renderOptions = _engine.render.options;
    };

    Demo.rounded = function() {
        var _world = _engine.world;

        Demo.reset();

        World.add(_world, [
            Bodies.rectangle(200, 200, 100, 100, {
                chamfer:  {
                    radius: 20
                }
            }),

            Bodies.rectangle(300, 200, 100, 100, {
                chamfer:  {
                    radius: [90, 0, 0, 0]
                }
            }),

            Bodies.rectangle(400, 200, 200, 200, {
                chamfer:  {
                    radius: [150, 20, 40, 20]
                }
            }),

            Bodies.rectangle(200, 200, 200, 200, {
                chamfer:  {
                    radius: [150, 20, 150, 20]
                }
            }),

            Bodies.rectangle(300, 200, 200, 50, {
                chamfer:  {
                    radius: [25, 25, 0, 0]
                }
            }),

            Bodies.polygon(200, 100, 8, 80, {
                chamfer:  {
                    radius: 30
                }
            }),

            Bodies.polygon(300, 100, 5, 80, {
                chamfer:  {
                    radius: [10, 40, 20, 40, 10]
                }
            }),

            Bodies.polygon(400, 200, 3, 50, {
                chamfer:  {
                    radius: [20, 0, 20]
                }
            })
        ]);

        var renderOptions = _engine.render.options;
        renderOptions.showAxes = true;
        renderOptions.showCollisions = true;
    };

    Demo.views = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(20, 20, 15, 4, 0, 0, function(x, y, column, row) {
            switch (Math.round(Common.random(0, 1))) {

            case 0:
                if (Math.random() < 0.8) {
                    return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50));
                } else {
                    return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30));
                }
                break;
            case 1:
                var sides = Math.round(Common.random(1, 8));
                sides = (sides === 3) ? 4 : sides;
                return Bodies.polygon(x, y, sides, Common.random(20, 50));
            }
        });

        World.add(_world, stack);

        // get the centre of the viewport
        var viewportCentre = {
            x: _engine.render.options.width * 0.5,
            y: _engine.render.options.height * 0.5
        };

        // make the world bounds a little bigger than the render bounds
        _world.bounds.min.x = -300;
        _world.bounds.min.y = -300;
        _world.bounds.max.x = 1100;
        _world.bounds.max.y = 900;

        // keep track of current bounds scale (view zoom)
        var boundsScaleTarget = 1,
            boundsScale = {
                x: 1,
                y: 1
            };

        // use the engine tick event to control our view
        _sceneEvents.push(
            Events.on(_engine, 'beforeTick', function() {
                var world = _engine.world,
                    mouse = _engine.input.mouse,
                    render = _engine.render,
                    translate;

                // mouse wheel controls zoom
                var scaleFactor = mouse.wheelDelta * -0.1;
                if (scaleFactor !== 0) {
                    if ((scaleFactor < 0 && boundsScale.x >= 0.6) || (scaleFactor > 0 && boundsScale.x <= 1.4)) {
                        boundsScaleTarget += scaleFactor;
                    }
                }

                // if scale has changed
                if (Math.abs(boundsScale.x - boundsScaleTarget) > 0.01) {
                    // smoothly tween scale factor
                    scaleFactor = (boundsScaleTarget - boundsScale.x) * 0.2;
                    boundsScale.x += scaleFactor;
                    boundsScale.y += scaleFactor;

                    // scale the render bounds
                    render.bounds.max.x = render.bounds.min.x + render.options.width * boundsScale.x;
                    render.bounds.max.y = render.bounds.min.y + render.options.height * boundsScale.y;

                    // translate so zoom is from centre of view
                    translate = {
                        x: render.options.width * scaleFactor * -0.5,
                        y: render.options.height * scaleFactor * -0.5
                    };

                    Bounds.translate(render.bounds, translate);

                    // update mouse
                    Mouse.setScale(mouse, boundsScale);
                    Mouse.setOffset(mouse, render.bounds.min);
                }

                // get vector from mouse relative to centre of viewport
                var deltaCentre = Vector.sub(mouse.absolute, viewportCentre),
                    centreDist = Vector.magnitude(deltaCentre);

                // translate the view if mouse has moved over 50px from the centre of viewport
                if (centreDist > 50) {
                    // create a vector to translate the view, allowing the user to control view speed
                    var direction = Vector.normalise(deltaCentre),
                        speed = Math.min(10, Math.pow(centreDist - 50, 2) * 0.0002);

                    translate = Vector.mult(direction, speed);

                    // prevent the view moving outside the world bounds
                    if (render.bounds.min.x + translate.x < world.bounds.min.x)
                        translate.x = world.bounds.min.x - render.bounds.min.x;

                    if (render.bounds.max.x + translate.x > world.bounds.max.x)
                        translate.x = world.bounds.max.x - render.bounds.max.x;

                    if (render.bounds.min.y + translate.y < world.bounds.min.y)
                        translate.y = world.bounds.min.y - render.bounds.min.y;

                    if (render.bounds.max.y + translate.y > world.bounds.max.y)
                        translate.y = world.bounds.max.y - render.bounds.max.y;

                    // move the view
                    Bounds.translate(render.bounds, translate);

                    // we must update the mouse too
                    Mouse.setOffset(mouse, render.bounds.min);
                }
            })
        );

        // must enable renderOptions.hasBounds for views to work
        var renderOptions = _engine.render.options;
        renderOptions.hasBounds = true;
    };

    Demo.mixedSolid = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(50, 50, 12, 3, 0, 0, function(x, y, column, row) {
            switch (Math.round(Common.random(0, 1))) {

            case 0:
                if (Math.random() < 0.8) {
                    return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50));
                } else {
                    return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30));
                }
                break;
            case 1:
                return Bodies.polygon(x, y, Math.round(Common.random(1, 8)), Common.random(20, 50));

            }
        });

        World.add(_world, stack);

        var renderOptions = _engine.render.options;
        renderOptions.wireframes = false;
        renderOptions.showAngleIndicator = false;

        if (window.chrome)
            renderOptions.showShadows = true;
    };

    Demo.chains = function() {
        var _world = _engine.world,
            groupId = Body.nextGroupId();

        Demo.reset();

        var ropeA = Composites.stack(200, 100, 5, 2, 10, 10, function(x, y, column, row) {
            return Bodies.rectangle(x, y, 50, 20, { groupId: groupId });
        });

        Composites.chain(ropeA, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 });
        Composite.add(ropeA, Constraint.create({
            bodyB: ropeA.bodies[0],
            pointB: { x: -25, y: 0 },
            pointA: { x: 200, y: 100 },
            stiffness: 0.5
        }));

        World.add(_world, ropeA);

        groupId = Body.nextGroupId();

        var ropeB = Composites.stack(500, 100, 5, 2, 10, 10, function(x, y, column, row) {
            return Bodies.circle(x, y, 20, { groupId: groupId });
        });

        Composites.chain(ropeB, 0.5, 0, -0.5, 0, { stiffness: 0.8, length: 2 });
        Composite.add(ropeB, Constraint.create({
            bodyB: ropeB.bodies[0],
            pointB: { x: -20, y: 0 },
            pointA: { x: 500, y: 100 },
            stiffness: 0.5
        }));

        World.add(_world, ropeB);
    };

    Demo.bridge = function() {
        var _world = _engine.world,
            groupId = Body.nextGroupId();

        Demo.reset();

        var bridge = Composites.stack(150, 300, 9, 1, 10, 10, function(x, y, column, row) {
            return Bodies.rectangle(x, y, 50, 20, { groupId: groupId });
        });

        Composites.chain(bridge, 0.5, 0, -0.5, 0, { stiffness: 0.9 });

        var stack = Composites.stack(200, 40, 6, 3, 0, 0, function(x, y, column, row) {
            return Bodies.polygon(x, y, Math.round(Common.random(1, 8)), Common.random(20, 40));
        });

        World.add(_world, [
            bridge,
            Bodies.rectangle(80, 440, 120, 280, { isStatic: true }),
            Bodies.rectangle(720, 440, 120, 280, { isStatic: true }),
            Constraint.create({ pointA: { x: 140, y: 300 }, bodyB: bridge.bodies[0], pointB: { x: -25, y: 0 } }),
            Constraint.create({ pointA: { x: 660, y: 300 }, bodyB: bridge.bodies[8], pointB: { x: 25, y: 0 } }),
            stack
        ]);
    };

    Demo.car = function() {
        var _world = _engine.world,
            scale;

        Demo.reset();

        scale = 0.9;
        World.add(_world, Composites.car(150, 100, 100 * scale, 40 * scale, 30 * scale));

        scale = 0.8;
        World.add(_world, Composites.car(350, 300, 100 * scale, 40 * scale, 30 * scale));

        World.add(_world, [
            Bodies.rectangle(200, 150, 650, 20, { isStatic: true, angle: Math.PI * 0.06 }),
            Bodies.rectangle(500, 350, 650, 20, { isStatic: true, angle: -Math.PI * 0.06 }),
            Bodies.rectangle(340, 580, 700, 20, { isStatic: true, angle: Math.PI * 0.04 })
        ]);

        var renderOptions = _engine.render.options;
        renderOptions.showAngleIndicator = true;
        renderOptions.showCollisions = true;
    };

    Demo.friction = function() {
        var _world = _engine.world;

        Demo.reset();

        World.add(_world, [
            Bodies.rectangle(300, 180, 700, 20, { isStatic: true, angle: Math.PI * 0.06 }),
            Bodies.rectangle(300, 70, 40, 40, { friction: 0.001 })
        ]);

        World.add(_world, [
            Bodies.rectangle(300, 350, 700, 20, { isStatic: true, angle: Math.PI * 0.06 }),
            Bodies.rectangle(300, 250, 40, 40, { friction: 0.0005 })
        ]);

        World.add(_world, [
            Bodies.rectangle(300, 520, 700, 20, { isStatic: true, angle: Math.PI * 0.06 }),
            Bodies.rectangle(300, 430, 40, 40, { friction: 0 })
        ]);

        var renderOptions = _engine.render.options;
        renderOptions.showAngleIndicator = true;
        renderOptions.showCollisions = true;
    };

    Demo.airFriction = function() {
        var _world = _engine.world;

        Demo.reset();

        World.add(_world, [
            Bodies.rectangle(200, 100, 60, 60, { frictionAir: 0.001 }),
            Bodies.rectangle(400, 100, 60, 60, { frictionAir: 0.05 }),
            Bodies.rectangle(600, 100, 60, 60, { frictionAir: 0.1 })
        ]);

        var renderOptions = _engine.render.options;
        renderOptions.showAngleIndicator = true;
        renderOptions.showCollisions = true;
    };

    Demo.sleeping = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(50, 50, 12, 3, 0, 0, function(x, y, column, row) {
            switch (Math.round(Common.random(0, 1))) {

            case 0:
                if (Math.random() < 0.8) {
                    return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50));
                } else {
                    return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30));
                }
                break;
            case 1:
                return Bodies.polygon(x, y, Math.round(Common.random(1, 8)), Common.random(20, 50));

            }
        });

        World.add(_world, stack);

        _engine.enableSleeping = true;

        var renderOptions = _engine.render.options;
    };

    Demo.broadphase = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(20, 20, 20, 5, 0, 0, function(x, y, column, row) {
            switch (Math.round(Common.random(0, 1))) {

            case 0:
                if (Math.random() < 0.8) {
                    return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50));
                } else {
                    return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30));
                }
                break;
            case 1:
                return Bodies.polygon(x, y, Math.round(Common.random(1, 8)), Common.random(20, 50));

            }
        });

        World.add(_world, stack);

        var renderOptions = _engine.render.options;
        renderOptions.showBroadphase = true;
    };

    Demo.gravity = function() {
        var _world = _engine.world;

        Demo.reset();

        _engine.world.gravity.y = -1;

        var stack = Composites.stack(20, 20, 20, 5, 0, 0, function(x, y, column, row) {
            switch (Math.round(Common.random(0, 1))) {

            case 0:
                if (Math.random() < 0.8) {
                    return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50));
                } else {
                    return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30));
                }
                break;
            case 1:
                return Bodies.polygon(x, y, Math.round(Common.random(1, 8)), Common.random(20, 50));

            }
        });

        World.add(_world, stack);

        var renderOptions = _engine.render.options;
    };

    Demo.avalanche = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(20, 20, 20, 5, 0, 0, function(x, y, column, row) {
            return Bodies.circle(x, y, Common.random(10, 20), { friction: 0.00001, restitution: 0.5, density: 0.001 });
        });

        World.add(_world, stack);

        World.add(_world, [
            Bodies.rectangle(200, 150, 700, 20, { isStatic: true, angle: Math.PI * 0.06 }),
            Bodies.rectangle(500, 350, 700, 20, { isStatic: true, angle: -Math.PI * 0.06 }),
            Bodies.rectangle(340, 580, 700, 20, { isStatic: true, angle: Math.PI * 0.04 })
        ]);
    };

    Demo.newtonsCradle = function() {
        var _world = _engine.world;

        Demo.reset();

        var cradle = Composites.newtonsCradle(280, 100, 5, 30, 200);
        World.add(_world, cradle);
        Body.translate(cradle.bodies[0], { x: -180, y: -100 });

        cradle = Composites.newtonsCradle(280, 380, 7, 20, 140);
        World.add(_world, cradle);
        Body.translate(cradle.bodies[0], { x: -140, y: -100 });

        var renderOptions = _engine.render.options;
        renderOptions.showVelocity = true;
    };

    Demo.timescale = function() {
        var _world = _engine.world;

        Demo.reset();

        var explosion = function(engine) {
            var bodies = Composite.allBodies(engine.world);

            for (var i = 0; i < bodies.length; i++) {
                var body = bodies[i];

                if (!body.isStatic && body.position.y >= 500) {
                    var forceMagnitude = 0.04 * body.mass;

                    Body.applyForce(body, { x: 0, y: 0 }, {
                        x: (forceMagnitude + Math.random() * forceMagnitude) * Common.choose([1, -1]),
                        y: -forceMagnitude + Math.random() * -forceMagnitude
                    });
                }
            }
        };

        var timeScaleTarget = 1,
            counter = 0;

        _sceneEvents.push(
            Events.on(_engine, 'tick', function(event) {
                // tween the timescale for bullet time slow-mo
                _engine.timing.timeScale += (timeScaleTarget - _engine.timing.timeScale) * 0.05;

                counter += 1;

                // every 1.5 sec
                if (counter >= 60 * 1.5) {

                    // flip the timescale
                    if (timeScaleTarget < 1) {
                        timeScaleTarget = 1;
                    } else {
                        timeScaleTarget = 0.05;
                    }

                    // create some random forces
                    explosion(_engine);

                    // reset counter
                    counter = 0;
                }
            })
        );

        var bodyOptions = {
            frictionAir: 0,
            friction: 0.0001,
            restitution: 0.8
        };

        // add some small bouncy circles... remember Swordfish?
        World.add(_world, Composites.stack(20, 100, 15, 3, 20, 40, function(x, y, column, row) {
            return Bodies.circle(x, y, Common.random(10, 20), bodyOptions);
        }));

        // add some larger random bouncy objects
        World.add(_world, Composites.stack(50, 50, 8, 3, 0, 0, function(x, y, column, row) {
            switch (Math.round(Common.random(0, 1))) {

            case 0:
                if (Math.random() < 0.8) {
                    return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50), bodyOptions);
                } else {
                    return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30), bodyOptions);
                }
                break;
            case 1:
                return Bodies.polygon(x, y, Math.round(Common.random(4, 8)), Common.random(20, 50), bodyOptions);

            }
        }));

        var renderOptions = _engine.render.options;
    };

    Demo.stack = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(100, 100, 10, 5, 0, 0, function(x, y, column, row) {
            return Bodies.rectangle(x, y, 40, 40);
        });

        World.add(_world, stack);

        var renderOptions = _engine.render.options;
    };

    Demo.circleStack = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(100, 100, 10, 10, 20, 0, function(x, y, column, row) {
            return Bodies.circle(x, y, 20);
        });

        World.add(_world, stack);

        var renderOptions = _engine.render.options;
    };

    Demo.wreckingBall = function() {
        var _world = _engine.world;

        Demo.reset();

        var rows = 10,
            yy = 600 - 21 - 40 * rows;

        var stack = Composites.stack(400, yy, 5, rows, 0, 0, function(x, y, column, row) {
            return Bodies.rectangle(x, y, 40, 40, { friction: 0.9, restitution: 0.1 });
        });

        World.add(_world, stack);

        var ball = Bodies.circle(100, 400, 50, { density: 0.07, frictionAir: 0.001});

        World.add(_world, ball);
        World.add(_world, Constraint.create({
            pointA: { x: 300, y: 100 },
            bodyB: ball
        }));

        if (!_isMobile) {
            var renderOptions = _engine.render.options;
            renderOptions.showCollisions = true;
            renderOptions.showVelocity = true;
        }
    };

    Demo.ballPool = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(100, 50, 10, 15, 10, 10, function(x, y, column, row) {
            return Bodies.circle(x, y, Common.random(15, 30), { restitution: 0.6, friction: 0.1 });
        });

        World.add(_world, [
            stack,
            Bodies.polygon(200, 560, 3, 60),
            Bodies.polygon(400, 560, 5, 60),
            Bodies.rectangle(600, 560, 80, 80)
        ]);

        var renderOptions = _engine.render.options;
    };

    Demo.stress = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(90, 30, 18, 15, 0, 0, function(x, y, column, row) {
            return Bodies.rectangle(x, y, 35, 35);
        });

        World.add(_world, stack);

        var renderOptions = _engine.render.options;
        renderOptions.showAngleIndicator = false;
    };

    Demo.stress2 = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(100, 120, 25, 18, 0, 0, function(x, y, column, row) {
            return Bodies.rectangle(x, y, 25, 25);
        });

        World.add(_world, stack);

        var renderOptions = _engine.render.options;
        renderOptions.showAngleIndicator = false;
    };

    Demo.pyramid = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.pyramid(100, 100, 15, 10, 0, 0, function(x, y, column, row) {
            return Bodies.rectangle(x, y, 40, 40);
        });

        World.add(_world, stack);

        var renderOptions = _engine.render.options;
    };

    Demo.restitution = function() {
        var _world = _engine.world;

        Demo.reset();

        var rest = 0.9,
            space = 600 / 5;

        World.add(_world, [
            Bodies.rectangle(100 + space * 0, 150, 50, 50, { restitution: rest }),
            Bodies.rectangle(100 + space * 1, 150, 50, 50, { restitution: rest, angle: -Math.PI * 0.15 }),
            Bodies.rectangle(100 + space * 2, 150, 50, 50, { restitution: rest, angle: -Math.PI * 0.25 }),
            Bodies.circle(100 + space * 3, 150, 25, { restitution: rest }),
            Bodies.rectangle(100 + space * 5, 150, 180, 20, { restitution: rest, angle: -Math.PI * 0.5 })
        ]);

        var renderOptions = _engine.render.options;
        renderOptions.showCollisions = true;
        renderOptions.showVelocity = true;
        renderOptions.showAngleIndicator = true;
    };

    Demo.softBody = function() {
        var _world = _engine.world;

        Demo.reset();

        var particleOptions = { render: { visible: true } };

        World.add(_world, [
            Composites.softBody(250, 100, 5, 5, 0, 0, true, 18, particleOptions),
            Composites.softBody(250, 300, 8, 3, 0, 0, true, 15, particleOptions),
            Composites.softBody(250, 400, 4, 4, 0, 0, true, 15, particleOptions)
        ]);

        var renderOptions = _engine.render.options;
        renderOptions.showAngleIndicator = false;
    };

    Demo.cloth = function() {
        var _world = _engine.world;

        Demo.reset();

        var groupId = Body.nextGroupId(),
            particleOptions = { friction: 0.00001, groupId: groupId, render: { visible: false }},
            cloth = Composites.softBody(200, 200, 20, 12, 5, 5, false, 8, particleOptions);

        for (var i = 0; i < 20; i++) {
            cloth.bodies[i].isStatic = true;
        }

        World.add(_world, [
            cloth,
            Bodies.circle(300, 500, 80, { isStatic: true }),
            Bodies.rectangle(500, 480, 80, 80, { isStatic: true })
        ]);
    };

    Demo.catapult = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(250, 255, 1, 6, 0, 0, function(x, y, column, row) {
            return Bodies.rectangle(x, y, 30, 30);
        });

        var catapult = Bodies.rectangle(400, 520, 320, 20, {  });

        World.add(_world, [
            stack,
            catapult,
            Bodies.rectangle(250, 555, 20, 50, { isStatic: true }),
            Bodies.circle(560, 100, 50, { density: 0.005 }),
            Constraint.create({ bodyA: catapult, pointB: { x: 390, y: 580 } }),
            Constraint.create({ bodyA: catapult, pointB: { x: 410, y: 580 } })
        ]);

        var renderOptions = _engine.render.options;
        renderOptions.showCollisions = true;
        renderOptions.showVelocity = true;
        renderOptions.showAngleIndicator = true;
    };

    Demo.beachBalls = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(0, 100, 5, 1, 20, 0, function(x, y, column, row) {
            return Bodies.circle(x, y, 75, { restitution: 0.9 });
        });

        World.add(_world, stack);
    };

    Demo.events = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(50, 100, 8, 4, 50, 50, function(x, y, column, row) {
            return Bodies.circle(x, y, 15, { restitution: 1, render: { strokeStyle: '#777' } });
        });

        World.add(_world, stack);

        var renderOptions = _engine.render.options;
        renderOptions.wireframes = false;

        var shakeScene = function(engine) {
            var bodies = Composite.allBodies(engine.world);

            for (var i = 0; i < bodies.length; i++) {
                var body = bodies[i];

                if (!body.isStatic && body.position.y >= 500) {
                    var forceMagnitude = 0.01 * body.mass;

                    Body.applyForce(body, { x: 0, y: 0 }, {
                        x: (forceMagnitude + Math.random() * forceMagnitude) * Common.choose([1, -1]),
                        y: -forceMagnitude + Math.random() * -forceMagnitude
                    });
                }
            }
        };

        _sceneEvents.push(

            // an example of using beforeUpdate event on an engine
            Events.on(_engine, 'beforeUpdate', function(event) {
                var engine = event.source;

                // apply random forces every 5 secs
                if (event.timestamp % 5000 < 50)
                    shakeScene(engine);
            })

        );

        _sceneEvents.push(

            // an example of using collisionStart event on an engine
            Events.on(_engine, 'collisionStart', function(event) {
                var pairs = event.pairs;

                // change object colours to show those starting a collision
                for (var i = 0; i < pairs.length; i++) {
                    var pair = pairs[i];
                    pair.bodyA.render.fillStyle = '#bbbbbb';
                    pair.bodyB.render.fillStyle = '#bbbbbb';
                }
            })

        );

        _sceneEvents.push(

            // an example of using collisionActive event on an engine
            Events.on(_engine, 'collisionActive', function(event) {
                var pairs = event.pairs;

                // change object colours to show those in an active collision (e.g. resting contact)
                for (var i = 0; i < pairs.length; i++) {
                    var pair = pairs[i];
                    pair.bodyA.render.fillStyle = '#aaaaaa';
                    pair.bodyB.render.fillStyle = '#aaaaaa';
                }
            })

        );

        _sceneEvents.push(

            // an example of using collisionEnd event on an engine
            Events.on(_engine, 'collisionEnd', function(event) {
                var pairs = event.pairs;

                // change object colours to show those ending a collision
                for (var i = 0; i < pairs.length; i++) {
                    var pair = pairs[i];
                    pair.bodyA.render.fillStyle = '#999999';
                    pair.bodyB.render.fillStyle = '#999999';
                }
            })

        );

        _sceneEvents.push(

            // an example of using mouse events on an engine.input.mouse
            Events.on(_engine, 'mousedown', function(event) {
                var mousePosition = event.mouse.position;
                console.log('mousedown at ' + mousePosition.x + ' ' + mousePosition.y);
                _engine.render.options.background = 'cornsilk';
                shakeScene(_engine);
            })

        );

        _sceneEvents.push(

            // an example of using mouse events on an engine.input.mouse
            Events.on(_engine, 'mouseup', function(event) {
                var mousePosition = event.mouse.position;
                _engine.render.options.background = "white";
                console.log('mouseup at ' + mousePosition.x + ' ' + mousePosition.y);
            })

        );
    };

    Demo.sprites = function() {
        var _world = _engine.world,
            offset = 10,
            options = {
                isStatic: true,
                render: {
                    visible: false
                }
            };

        Demo.reset();
        _world.bodies = [];

        // these static walls will not be rendered in this sprites example, see options
        World.add(_world, [
            Bodies.rectangle(400, -offset, 800.5 + 2 * offset, 50.5, options),
            Bodies.rectangle(400, 600 + offset, 800.5 + 2 * offset, 50.5, options),
            Bodies.rectangle(800 + offset, 300, 50.5, 600.5 + 2 * offset, options),
            Bodies.rectangle(-offset, 300, 50.5, 600.5 + 2 * offset, options)
        ]);

        var stack = Composites.stack(20, 20, 15, 4, 0, 0, function(x, y, column, row) {
            if (Math.random() > 0.35) {
                return Bodies.rectangle(x, y, 64, 64, {
                    render: {
                        strokeStyle: '#ffffff',
                        sprite: {
                            texture: './img/box.png'
                        }
                    }
                });
            } else {
                return Bodies.circle(x, y, 46, {
                    density: 0.0005,
                    frictionAir: 0.06,
                    restitution: 0.3,
                    friction: 0.01,
                    render: {
                        sprite: {
                            texture: './img/ball.png'
                        }
                    }
                });
            }
        });

        World.add(_world, stack);

        var renderOptions = _engine.render.options;
        renderOptions.background = './img/wall-bg.jpg';
        renderOptions.showAngleIndicator = false;
        renderOptions.wireframes = false;
    };

    Demo.raycasting = function() {
        var _world = _engine.world;

        Demo.reset();

        var stack = Composites.stack(20, 20, 15, 4, 0, 0, function(x, y, column, row) {
            switch (Math.round(Common.random(0, 1))) {

            case 0:
                if (Math.random() < 0.8) {
                    return Bodies.rectangle(x, y, Common.random(20, 50), Common.random(20, 50));
                } else {
                    return Bodies.rectangle(x, y, Common.random(80, 120), Common.random(20, 30));
                }
                break;
            case 1:
                var sides = Math.round(Common.random(1, 8));
                sides = (sides === 3) ? 4 : sides;
                return Bodies.polygon(x, y, sides, Common.random(20, 50));
            }
        });

        World.add(_world, stack);

        _sceneEvents.push(
            Events.on(_engine, 'afterRender', function() {
                var mouse = _engine.input.mouse,
                    context = _engine.render.context,
                    bodies = Composite.allBodies(_engine.world),
                    startPoint = { x: 400, y: 100 },
                    endPoint = mouse.position;

                var collisions = Query.ray(bodies, startPoint, endPoint);

                context.beginPath();
                context.moveTo(startPoint.x, startPoint.y);
                context.lineTo(endPoint.x, endPoint.y);
                if (collisions.length > 0) {
                    context.strokeStyle = '#fff';
                } else {
                    context.strokeStyle = '#555';
                }
                context.lineWidth = 0.5;
                context.stroke();

                for (var i = 0; i < collisions.length; i++) {
                    var collision = collisions[i];
                    context.rect(collision.bodyA.position.x - 4.5, collision.bodyA.position.y - 4.5, 8, 8);
                }

                context.fillStyle = 'rgba(255,165,0,0.7)';
                context.fill();
            })
        );

        var renderOptions = _engine.render.options;
    };

    // the functions for the demo interface and controls below

    Demo.initControls = function() {
        var demoSelect = document.getElementById('demo-select'),
            demoReset = document.getElementById('demo-reset');

        // create a Matter.Gui
        if (!_isMobile && Gui) {
            _gui = Gui.create(_engine);

            // need to add mouse constraint back in after gui clear or load is pressed
            Events.on(_gui, 'clear load', function() {
                _mouseConstraint = MouseConstraint.create(_engine);
                World.add(_engine.world, _mouseConstraint);
            });
        }

        // create a Matter.Inspector
        if (!_isMobile && Inspector && _useInspector) {
            _inspector = Inspector.create(_engine);

            Events.on(_inspector, 'import', function() {
                _mouseConstraint = MouseConstraint.create(_engine);
                World.add(_engine.world, _mouseConstraint);
            });

            Events.on(_inspector, 'play', function() {
                _mouseConstraint = MouseConstraint.create(_engine);
                World.add(_engine.world, _mouseConstraint);
            });

            Events.on(_inspector, 'selectStart', function() {
                _mouseConstraint.constraint.render.visible = false;
            });

            Events.on(_inspector, 'selectEnd', function() {
                _mouseConstraint.constraint.render.visible = true;
            });
        }

        // go fullscreen when using a mobile device
        if (_isMobile) {
            var body = document.body;

            body.className += ' is-mobile';
            _engine.render.canvas.addEventListener('touchstart', Demo.fullscreen);

            var fullscreenChange = function() {
                var fullscreenEnabled = document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled;

                // delay fullscreen styles until fullscreen has finished changing
                setTimeout(function() {
                    if (fullscreenEnabled) {
                        body.className += ' is-fullscreen';
                    } else {
                        body.className = body.className.replace('is-fullscreen', '');
                    }
                }, 2000);
            };

            document.addEventListener('webkitfullscreenchange', fullscreenChange);
            document.addEventListener('mozfullscreenchange', fullscreenChange);
            document.addEventListener('fullscreenchange', fullscreenChange);
        }

        // initialise demo selector
        demoSelect.value = _sceneName;

        demoSelect.addEventListener('change', function(e) {
            Demo[_sceneName = e.target.value]();
            Gui.update(_gui);

            var scrollY = window.scrollY;
            window.location.hash = _sceneName;
            window.scrollY = scrollY;
        });

        demoReset.addEventListener('click', function(e) {
            Demo[_sceneName]();
            Gui.update(_gui);
        });
    };

    Demo.fullscreen = function(){
        var _fullscreenElement = _engine.render.canvas;

        if (!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement) {
            if (_fullscreenElement.requestFullscreen) {
                _fullscreenElement.requestFullscreen();
            } else if (_fullscreenElement.mozRequestFullScreen) {
                _fullscreenElement.mozRequestFullScreen();
            } else if (_fullscreenElement.webkitRequestFullscreen) {
                _fullscreenElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
            }
        }
    };

    Demo.reset = function() {
        var _world = _engine.world;

        World.clear(_world);
        Engine.clear(_engine);

        // clear scene graph (if defined in controller)
        var renderController = _engine.render.controller;
        if (renderController.clear)
            renderController.clear(_engine.render);

        // clear all scene events
        for (var i = 0; i < _sceneEvents.length; i++)
            Events.off(_engine, _sceneEvents[i]);
        _sceneEvents = [];

        // reset id pool
        Common._nextId = 0;

        // reset mouse offset and scale (only required for Demo.views)
        Mouse.setScale(_engine.input.mouse, { x: 1, y: 1 });
        Mouse.setOffset(_engine.input.mouse, { x: 0, y: 0 });

        _engine.enableSleeping = false;
        _engine.world.gravity.y = 1;
        _engine.world.gravity.x = 0;
        _engine.timing.timeScale = 1;

        var offset = 5;
        World.add(_world, [
            Bodies.rectangle(400, -offset, 800.5 + 2 * offset, 50.5, { isStatic: true }),
            Bodies.rectangle(400, 600 + offset, 800.5 + 2 * offset, 50.5, { isStatic: true }),
            Bodies.rectangle(800 + offset, 300, 50.5, 600.5 + 2 * offset, { isStatic: true }),
            Bodies.rectangle(-offset, 300, 50.5, 600.5 + 2 * offset, { isStatic: true })
        ]);

        _mouseConstraint = MouseConstraint.create(_engine);
        World.add(_world, _mouseConstraint);

        var renderOptions = _engine.render.options;
        renderOptions.wireframes = true;
        renderOptions.hasBounds = false;
        renderOptions.showDebug = false;
        renderOptions.showBroadphase = false;
        renderOptions.showBounds = false;
        renderOptions.showVelocity = false;
        renderOptions.showCollisions = false;
        renderOptions.showAxes = false;
        renderOptions.showPositions = false;
        renderOptions.showAngleIndicator = true;
        renderOptions.showIds = false;
        renderOptions.showShadows = false;
        renderOptions.background = '#fff';

        if (_isMobile)
            renderOptions.showDebug = true;
    };

})();


text:
using namespace std;

ListCycle::CycleState ListCycle::findCycle(ListNode *n)
{
    unordered_map<ListNode*, char> nodes;
    do {
        auto itr = nodes.find(n);

        if (itr == nodes.end()) // not found
            nodes[n] = n->mData;
        else
            return CycleState::CYCLE;

        if (mVerbose)
            n->print();

        n = n->mNext;
    } while (n != nullptr);
    return CycleState::TERMINATES;
}

UnitTest::TestResult ListCycle::test()
{
    ListNode *z = new ListNode('z');
    ListNode *y = new ListNode('y', z);
    ListNode *x = new ListNode('x', y);
    ListNode *w = new ListNode('w', x);

    if (findCycle(w) != CycleState::TERMINATES)
        return TestResult::FAIL;

    z->mNext = x;

    if (findCycle(w) != CycleState::CYCLE)
        return TestResult::FAIL;

    return TestResult::PASS;
}

ListNode::ListNode(char iData) : mData(iData), mNext(nullptr)
{
}

ListNode::ListNode(char iData, ListNode *iNext) : mData(iData), mNext(iNext)
{
}

void ListNode::print()
{
    cout << mData << " ";
}

void ListNode::printRecursive()
{
    print();
    if (mNext != nullptr)
        mNext->printRecursive();
}


text:
#pragma once

#include "antlr4-common.h"

namespace antlr4 {
namespace atn {

  /// <summary>
  /// This is the base class for gathering detailed information about prediction
  /// events which occur during parsing.
  ///
  /// Note that we could record the parser call stack at the time this event
  /// occurred but in the presence of left recursive rules, the stack is kind of
  /// meaningless. It's better to look at the individual configurations for their
  /// individual stacks. Of course that is a <seealso cref="PredictionContext"/> object
  /// not a parse tree node and so it does not have information about the extent
  /// (start...stop) of the various subtrees. Examining the stack tops of all
  /// configurations provide the return states for the rule invocations.
  /// From there you can get the enclosing rule.
  ///
  /// @since 4.3
  /// </summary>
  class ANTLR4CPP_PUBLIC DecisionEventInfo {
  public:
    /// <summary>
    /// The invoked decision number which this event is related to.
    /// </summary>
    /// <seealso cref= ATN#decisionToState </seealso>
    const size_t decision;

    /// <summary>
    /// The configuration set containing additional information relevant to the
    /// prediction state when the current event occurred, or {@code null} if no
    /// additional information is relevant or available.
    /// </summary>
    const ATNConfigSet *configs;

    /// <summary>
    /// The input token stream which is being parsed.
    /// </summary>
    const TokenStream *input;

    /// <summary>
    /// The token index in the input stream at which the current prediction was
    /// originally invoked.
    /// </summary>
    const size_t startIndex;

    /// <summary>
    /// The token index in the input stream at which the current event occurred.
    /// </summary>
    const size_t stopIndex;

    /// <summary>
    /// {@code true} if the current event occurred during LL prediction;
    /// otherwise, {@code false} if the input occurred during SLL prediction.
    /// </summary>
    const bool fullCtx;

    DecisionEventInfo(size_t decision, ATNConfigSet *configs, TokenStream *input, size_t startIndex,
                      size_t stopIndex, bool fullCtx);
  };

} // namespace atn
} // namespace antlr4


text:
import pygame
from PygameComponent import PygameComponent
from pickle import load

class TreeStructure(PygameComponent):
    """
    Pygame Component representing a tree of shards.
    The topology of the tree is stored in shardGen objects, which contain the
    constructor arguments for a shard and a list of its children.
    Supports addition, deletion, selection, deselection and relabelling of
    nodes via messages to its inbox. Sending 'generate' to its inbox will
    cause it to generate the code the shard tree represents and write it to
    a default filename (currently ~/<root shard name>.py)

    TODO: allow supplying of filepath, node rearranging
    """

    configuration = {
       "transparency" : "Colour to be made transparent. None == no colour transparent",
       "boxsize" : "(width,height) representing size of the boxes",
       "width" : "width of the boxes (yes, I know, this *is* in /Sketches right now",
       "height" : "height of the boxes (yes, I know, this *is* in /Sketches right now",
       "hspacing" : "minimum spacing between boxes horizontally",
       "vspacing" : "minimum spacing between boxes vertically",
    }
    transparency = 0xffffff
    boxsize = (100,50)
    width = 100
    hspacing = 10
    height = 50
    vspacing = 50

    # assumes use of the following attributes:
    #boxes: shardGen: (x, y) coordinate of box
    #root : root shardgen object
    #selected: shardGen object selected, if any

    def writeFile(self, filepath = None):
        if not self.root:
            return None
        else:
            file = self.root.writeFile(filepath)
            print 'hierarchy saved to', file.name
            return file

    def generate(self, filepath = None):
        if not self.root:
            return None
        else:
            shard = self.root.makeShard()
            file = shard.writeFile(filepath)
            text = 'code written to '+ file.name + ':\n\n\n'
            text += ''.join(shard.code)
            # display message format for textbox: ['disp', boxtext]
            self.send(['disp', text], 'outbox')

            return shard

    def removeNode(self, parent, node):
        if node in parent.children:
            parent.children.remove(node)
            for child in parent.children:
                self.removeNode(child, node)

    def reDoTopology(self):
        self.clearDisplay()
        if self.root:
            self.boxes = {}
            self.layout_tree(self.root, 0,100)
            self.drawBox(self.root)
        self.flip()

    def layout_tree(self, box, wx, wy):
        left = wx
        nw = self.width
        row_below = wy+self.height+self.vspacing
        for subbox in box.children:
            nw = self.layout_tree(subbox, left, row_below)
            left = left + nw+self.hspacing
        if left != wx:
            nw = left-wx-self.hspacing
        self.boxes[box] = wx+(nw/2), wy
        return nw

    def clickInBox(self, pos):
        for box in self.boxes:
            if self.boxes[box][0] <= pos[0] <= self.boxes[box][0]+self.boxsize[0]:
                if self.boxes[box][1] <= pos[1] <= self.boxes[box][1]+self.boxsize[1]:
                    return box
        return None # explicit better than implicit

    def select(self, nodeid):
        self.selected = nodeid
        self.send(["SELECT", self.selected ], "outbox")
        self.reDoTopology()

    def deselect(self):
        self.selected = None
        self.send(["DESELECT"], "outbox")
        self.reDoTopology()

    def mousedown_handler(self,*events, **eventd):
        selected = self.selected
        for event in events:
            if event.button == 1:
                nodeid= self.clickInBox(event.pos)
                if nodeid:
                    self.select(nodeid)
                else:
                    self.deselect()

    def main(self):
        """Main loop."""
        yield self.doRequestDisplay((1024, 768))
        self.addHandler(pygame.MOUSEBUTTONDOWN, self.mousedown_handler)

        self.selected = None
        self.reDoTopology()
        while True:
            self._dispatch()
            while self.dataReady("inbox"):
                command = self.recv("inbox")

                if command[0] == "add":
                    sg, labeltext, parent = command[1:]
                    sg.label = labeltext
                    if not parent:
                        self.root = sg
                    else:
                        parent.children.append(sg)

                elif command == 'generate':
                    self.generate()

                elif command[0] == "relabel":
                    node, newlabel = command[1:]
                    node.label = newlabel

                elif command[0] == "select":
                    nodeid, = command[1:]
                    self.select(nodeid)

                elif command[0] == "deselect":
                    self.deselect()

                elif command[0] == "del":
                    if command[1] == "all":
                        self.selected = None
                        self.root = None
                        self.boxes = {}
                    if command[1] == "node":
                        try:
                            del self.boxes[command[2]]
                        except KeyError:
                            pass
                        self.removeNode(self.root, command[2])

                elif command[0] == 'SAVE':
                    # save hierarchy, command format ['SAVE', <to path>], path optional
                    path = None
                    if len(command) > 1:
                        path = command[1]
                    self.writeFile(path)

                self.reDoTopology()
            yield 1

class TreeDraw(object):
    # assumes self.display, self.boxes attributes

    def drawBox(self, box):
        if not hasattr(box, 'label'):
            box.label = box.shard.__name__
        colour = 0xaaaaaa
        if box == self.selected :
            colour = 0xff8888

        pygame.draw.rect(self.display, colour, (self.boxes[box],self.boxsize), 0)
        cx = self.boxes[box][0]+self.boxsize[0]/2
        cy = self.boxes[box][1]+self.boxsize[1]/2
        image, w,h = self.makeLabel(box.label)
        self.display.blit( image, (cx-w/2,cy-h/2) )
        if box.children:
            self.drawTree(box)

    def makeLabel(self, text):
        font = pygame.font.Font(None, 14)
        textimage = font.render(text,True, (0,0,0),)
        (w,h) = textimage.get_size()
        return textimage, w,h

    def drawLine(self, line):
        pygame.draw.line(self.display, 0,line[0],line[1],2)

    def drawTree(self, tree): #being added but not drawn
        box = tree
        w = self.boxsize[0]
        h = self.boxsize[1]
        x,y = self.boxes[box]
        paths = []
        for subbox in box.children:
            self.drawBox(subbox)
            ax,ay = self.boxes[subbox]
            paths.append(
                    [
                        (((x+w/2), y+h) , ((x+w/2), y+h+((ay-(y+h))/2) )),  # DOWN
                        (((x+w/2), y+h+((ay-(y+h))/2) ), ((ax+w/2), ay-(ay-(y+h))/2 )), # ACROSS
                        (((ax+w/2), ay-(ay-(y+h))/2 ), ((ax+w/2), ay)),  # DOWN
                    ],
            )

        for path in paths:
            self.drawPath(path)

    def drawPath(self, path):
        for line in path:
            self.drawLine(line)

class Tree(TreeStructure, TreeDraw):

    @staticmethod
    def rootFromPath(path):
        file = open(path, 'r')
        return load(file)

    boxes = {}
    root = None
    selected = None

    def __init__(self, root = None):
        super(Tree, self).__init__()
        self.root = root

if __name__ == '__main__':

    import sys

    # example for ShardGen.py: mouse handler from MagnaDoodle
    from MagnaGen import *
    from ShardGen import shardGen
    from ExampleMagnaShards import __INIT__ # needs to be specifically imported

    mh = shardGen(switchShard) # mousehandler
    mh.args['name'] = 'mouseHandler'
    mh.args['switchVar'] = 'event.type'
    mh.args['conditions'] = ['pygame.MOUSEBUTTONDOWN', 'pygame.MOUSEBUTTONUP',
                                              'pygame.MOUSEMOTION']
    mh.args['shards'] = [MOUSEBUTTONDOWN_handler, MOUSEBUTTONUP_handler,
                                       MOUSEMOTION_handler]

    # wrap switch in loop that reads from inbox
    pyl = shardGen(forShard) # pyevent loop
    pyl.args['name'] = 'eventhandler'
    pyl.args['forVars'] = ['event']
    pyl.args['inVar'] = r'self.recv("inbox")'
    pyl.children += [mh]

    # wrap event loop in inbox checking loop so that no invalid reads are performed
    ml = shardGen(whileShard) # mainloop
    ml.args['name'] = 'LoopOverPygameEvents'
    ml.args['condition'] = r'self.dataReady("inbox")'
    ml.children += [pyl]

    # test importing from file as well
    ml.writeFile('ml')

    class ImportLoopTree(Tree):
        def __init__(self):
            super(ImportLoopTree, self).__init__(root = Tree.rootFromPath('ml'))

    from ShardCompose import *

    Graphline(
        CLEAR = Button(caption="Clear", msg=["del", "all"], position=(0,690),size=(64,32)),
        GEN= Button(caption="Generate", msg=["GEN"], position=(70,690),size=(64,32)),
        DEL= Button(caption="Del Node", msg=["DEL"], position=(140,690),size=(64,32)),
        RELABEL= Button(caption="Relabel Node", msg=["RELABEL"], position=(210,690),size=(94,32)),
        SAVE= Button(caption="Save", msg=["SAVE"], position=(310,690),size=(64,32)),
        CORELOGIC = CoreLogic(),
        TOPOLOGY = ImportLoopTree(), # sample tree here
        IMP = ImportShardsGUI('/usr/lib/python2.5/site-packages/Kamaelia/Util'),
        CON = ConnectorShardsGUI(items),
        DISP = TextOutputGUI('Generated Code'),
        linkages = {
            ("CLEAR", "outbox"): ("TOPOLOGY","inbox"),
            ("TOPOLOGY","outbox"): ("CORELOGIC", "inbox"),
            ("GEN","outbox"): ("CORELOGIC", "inbox"),
            ("DEL","outbox"): ("CORELOGIC", "inbox"),
            ("RELABEL","outbox"): ("CORELOGIC", "inbox"),
            ("SAVE", "outbox"): ("TOPOLOGY","inbox"),
            ("CORELOGIC","outbox"): ("TOPOLOGY", "inbox"),
            ("IMP","outbox"): ("CORELOGIC", "inbox"),
            ("CON","outbox"): ("CORELOGIC", "inbox"),
            ("CORELOGIC","popup"): ("CON", "inbox"),
            ("CORELOGIC", 'textbox'): ('DISP', 'inbox')
        }
    ).run()


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace QRBuild.Text
{
    public static class StringInterpolator
    {
        public sealed class Options
        {
            public Options()
            {
                EvalChar = '$';
                LParen = '(';
                RParen = ')';
                ThrowOnUnknownKey = true;
            }

            /// EvalChar is the character that indicates
            /// the evaluation of a substitution.
            /// The default value is '$'.
            public char EvalChar { get; set; }

            public char LParen { get; set; }
            public char RParen { get; set; }

            /// If true, then an unknown key in a substitution will cause
            /// an exception to be thrown.
            /// If false, then an empty string will be substituted.
            public bool ThrowOnUnknownKey { get; set; }
        }

        public enum TokenType
        {
            Error,
            Literal,
            Substitution,
        }

        public sealed class Token
        {
            public Token(TokenType type, string value)
            {
                Type = type;
                Value = value;
            }

            public TokenType Type { get; private set; }
            public string Value { get; private set; }
        }

        public static string Interpolate(Options options, IList<Token> tokens, Func<string, string> getValue)
        {
            StringBuilder builder = new StringBuilder();

            foreach (Token token in tokens) {
                if (token.Type == TokenType.Literal) {
                    builder.Append(token.Value);
                }
                else if (token.Type == TokenType.Substitution) {
                    string value = getValue(token.Value);
                    if (value != null) {
                        builder.Append(value);
                    }
                    else {
                        if (options.ThrowOnUnknownKey) {
                            String errorString = String.Format("Missing key '{0}' in substitution.", token.Value);
                            throw new InvalidOperationException(errorString);
                        }
                        else {
                            builder.Append(String.Empty);
                        }
                    }
                }
            }

            return builder.ToString();
        }

        public static IList<Token> Tokenize(Options options, string text)
        {
            List<Token> result = new List<Token>();
            if (String.IsNullOrEmpty(text) || options == null) {
                // return a single empty-string token
                result.Add(new Token(TokenType.Literal, ""));
                return result;
            }

            int i = 0;
            while (i < text.Length) {
                Token literal = ScanLiteral(options, text, ref i);
                if (literal != null) {
                    result.Add(literal);
                }
                if (literal.Type == TokenType.Error) {
                    break;
                }

                Token subst = ScanSubstitution(options, text, ref i);
                if (subst != null) {
                    result.Add(subst);
                }
                if (subst.Type == TokenType.Error) {
                    break;
                }
            }

            return result;
        }

        private static Token ScanLiteral(Options options, string text, ref int i)
        {
            int start = i;
            for (; i < text.Length; i++) {
                char c = text[i];
                if (c == options.EvalChar) {
                    break;
                }
            }
            return MakeLiteral(text, start, i);
        }

        private static Token MakeLiteral(string text, int start, int i)
        {
            string substr = text.Substring(start, i - start);
            return new Token(TokenType.Literal, substr);
        }

        private static Token ScanSubstitution(Options options, string text, ref int i)
        {
            if (i == text.Length) {
                return null;
            }

            int start = i;
            char c0 = text[i];
            if (c0 != options.EvalChar) {
                return null;
            }
            i++;
            if (i == text.Length) {
                // single EvalChar at the end is emitted verbatim
                return MakeLiteral(text, start, i);
            }

            char c1 = text[i];
            if (c1 == options.EvalChar) {
                // two EvalChar in a row is the escape for a literal EvalChar
                i++;
                return MakeLiteral(text, start, 1);
            }
            else if (c1 == options.LParen) {
                i++;

                int identStart = i;
                string ident = ScanIdent(text, ref i);
                if (ident == null ||
                    i == text.Length ||
                    text[i] != options.RParen) {
                    string substr = text.Substring(identStart, i - identStart);
                    return new Token(TokenType.Error, substr);
                }

                // consume the RParen
                i++;
                return new Token(TokenType.Substitution, ident);
            }
            else {
                // EvalChar is followed by insignificant character.
                // Do not consume character at position i.  (there is no i++ here)
                // Emit the EvalChar verbatim.
                return MakeLiteral(text, start, i);
            }
        }

        private static string ScanIdent(string text, ref int i)
        {
            int start = i;
            if (i == text.Length) {
                return null;
            }
            char c0 = text[i++];
            if (!IsIdentChar(c0) || IsNum(c0)) {
                return null;
            }

            for (; i < text.Length; i++) {
                char c = text[i];
                if (!IsIdentChar(c)) {
                    break;
                }
            }

            string substr = text.Substring(start, i - start);
            return substr;
        }

        private static bool IsNum(char c)
        {
            return '0' <= c && c <= '9';
        }
        private static bool IsIdentChar(char c)
        {
            return 'A' <= c && c <= 'Z'
                || 'a' <= c && c <= 'z'
                || c == '_'
                || IsNum(c);
        }
    }
}


text:
<?php defined('SYSPATH') or die('No direct script access.');
/*
 * Заказы
 */
class Controller_Admin_Orders extends Controller_Admin {

    public function before() {
        parent::before();

        // Вывод в шаблон
        $this->template->submenu = Widget::load('menuorders');
    }

    public function action_index() {

        $content = View::factory('admin/orders/v_orders_index')
                ->bind('orders', $orders)
                ->bind('products', $products)
                ->bind('delivery', $delivery)
                ->bind('users', $users)
                ->bind('orders_products', $orders_products);

        $orders = ORM::factory('order')->find_all();

        foreach ($orders as $order)
        {
            $users[$order->id] = ORM::factory('user', $order->user_id);
            $products[$order->id] = $order->products->find_all()->as_array();
            $delivery[$order->id] = $order->delivery->as_array();

            //можно было бы через эту модель получить доступ ко всем другим
            $orders_products[$order->id] = ORM::factory('orderproduct')
                    ->where('order_id', '=' , $order->id)
                    ->find()
                    ->as_array();
        }

        // Вывод в шаблон
        $this->template->page_title = 'Заказы';
        $this->template->block_center = array($content);
    }
}


text:
using LeadPipe.Net.FiniteStateMachine;
using NUnit.Framework;
using System.Linq;

namespace LeadPipe.Net.Tests.FiniteStateMachineTests
{
    /// <summary>
    /// RemoveState method tests.
    /// </summary>
    [TestFixture]
    public class RemoveStateShould
    {
        /// <summary>
        /// The closed state.
        /// </summary>
        private IFiniteState closedState;

        /// <summary>
        /// The close transition.
        /// </summary>
        private IFiniteStateTransition closeTransition;

        /// <summary>
        /// The machine.
        /// </summary>
        private IFiniteStateMachine<FiniteStateMachineHistoryEntry> machine;

        /// <summary>
        /// The open state.
        /// </summary>
        private IFiniteState openState;

        /// <summary>
        /// The open transition.
        /// </summary>
        private IFiniteStateTransition openTransition;

        /// <summary>
        /// The start transition.
        /// </summary>
        private IFiniteStateTransition startTransition;

        /// <summary>
        /// Tests to make sure that a state that is not currently used is removed.
        /// </summary>
        [Test]
        public void RemoveState()
        {
            // Act
            this.machine.RemoveState(this.closedState);

            // Assert
            Assert.IsFalse(this.machine.States.Contains(this.closedState));
        }

        /// <summary>
        /// Tests to make sure that an exception is thrown when trying to remove a state that is in use.
        /// </summary>
        [Test]
        public void ThrowExceptionGivenStateInUse()
        {
            // Act
            Assert.Throws<StateInUseException>(() => this.machine.RemoveState(this.openState));
        }

        /// <summary>
        /// Runs before each test.
        /// </summary>
        [SetUp]
        public void TestSetup()
        {
            // Create our states...
            this.openState = new FiniteState(0, "Open");
            this.closedState = new FiniteState(1, "Closed");

            // Create our transitions...
            this.startTransition = new FiniteStateTransition(0, "New", new FiniteStateMachineTransitionReason("0", "New"), this.openState);

            this.openTransition = new FiniteStateTransition(1, "Open", new FiniteStateMachineTransitionReason("1", "Opened"), this.closedState, this.openState);
            this.closeTransition = new FiniteStateTransition(2, "Close", new FiniteStateMachineTransitionReason("2", "Closed"), this.openState, this.closedState);

            // Add our transitions to our states...
            this.openState.RegisterTransition(this.closeTransition);
            this.closedState.RegisterTransition(this.openTransition);

            // Create our machine...
            this.machine = new FiniteStateMachine.FiniteStateMachine(this.startTransition);

            // Add our states...
            this.machine.RegisterState(this.openState);
            this.machine.RegisterState(this.closedState);
        }
    }
}


text:
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
]]--

function ident(x)
  return x
end

function empty()
  return {torch.zeros(1)}, {torch.zeros(1)}
end

function empty_bp(self, input, gradOutput, name)
  if name == nil then
    name = "gradInput"
  end
  if istable(input) then
    self[name] = {}
    for k, v in pairs(input) do
      self[name][k] = empty_bp(self, v, 0, k)
    end
  elseif type(input) == "number" or
         (type(input) == 'table' and input.__typename == "Instance") then
    if self[name] == nil then
      self[name] = torch.zeros(1)
    end
  elseif torch.isTensor(input) then
    if self[name] == nil then
      self[name] = input:clone():zero()
    end
  else
    print("input")
    print(input)
    print("gradOutput")
    print(gradOutput)
    assert(false)
  end
  assert(self[name] ~= nil)
  return self[name]
end

function empty_type(self, new_type)
  return self
end

function emb(self, ins_node, fun, selection, which)
  local function fp(name, which)
    local function forward(self, ins)
      return fun(ins, name, which)
    end
    return forward
  end
  assert(type(selection) == "table")
  local ret = {}
  for name, desc in pairs(selection) do
    if desc.size > 0 then
      local tmp = new_node(self, ident, fp(name, which), empty_bp, {ins_node})
      table.insert(ret, nn.OneHotIndex(desc.size, name)(tmp))
    end
  end
  return ret
end

function new_node(self, init, fp, bp, input_nodes, name, which)
 local module = safe_merge(table.copy(self), {updateOutput=fp,
                                              updateGradInput=bp,
                                              accGradParameters=empty,
                                              parameters=empty,
                                              type=empty_type})
  init(module)
  setmetatable(module, getmetatable(self))
  module.trace = debug.traceback()
  if name ~= nil then
    module.node_name = name
  end
  if which ~= nil then
    module.which = which
  end
  local node = nngraph.Node({module=module})
  if not istable(input_nodes) then
    input_nodes = {input_nodes}
  end
  for _, input_node in pairs(input_nodes) do
    if torch.typename(input_node) ~= 'nngraph.Node' then
      error('what is this in the input? ' .. tostring(input_node))
    end
    node:add(input_node, true)
  end
  return node
end

local unpack = unpack and unpack or table.unpack

local Module = torch.getmetatable('nn.Module')
local call__ = Module.__call__
function Module:__call__(...)
  local input = {...}
  local ret = call__(unpack(merge({self}, input)))
  if ret.data ~= nil and
     ret.data.module ~= nil then
    ret.data.module.trace = debug.traceback()
  end
  return ret
end


text:
function Sf = get_value_i(p, angle, offset, T2)
%
% function Sf = get_value_i(p, angle, offset, T2)
%
% interpolate Sf values

Sf = interp3(p.offsets, p.angles, p.T2, p.values, offset, angle, T2);
% note order of parameters.  Strange?

if(sum(isnan(Sf)))
  error(sprintf('Requested values not in cache.\nangle = %4d deg, offset = %f Hz, T2 = %f ms', angle, offset, T2*1000))
end


text:
#ifndef DateTimeChooserClient_h
#define DateTimeChooserClient_h

#include "platform/PlatformExport.h"
#include "wtf/text/WTFString.h"

namespace WebCore {

class PLATFORM_EXPORT DateTimeChooserClient {
public:
    virtual ~DateTimeChooserClient();

    // Called when user picked a value.
    virtual void didChooseValue(const String&) = 0;
    // Called when user picked a value.
    virtual void didChooseValue(double) = 0;
    // Called when chooser has ended.
    virtual void didEndChooser() = 0;
};

} // namespace WebCore
#endif // DateTimeChooserClient_h