<commit_before>/**
* See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js)
* and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples.
*
* @class Gui
*/

var Gui = {};

(function() {

    /**
     * Description
     * @method create
     * @param {engine} engine
     * @param {object} options
     * @return {gui} A container for a configured dat.gui
     */
    Gui.create = function(engine, options) {
        var _datGuiSupported = window.dat && window.localStorage,
            _serializer;

        if (!_datGuiSupported) {
            console.log("Could not create GUI. Check dat.gui library is loaded first.");
            return;
        }

        var datGui = new dat.GUI(options);

        if (Resurrect) {
            _serializer = new Resurrect({ prefix: '$' });
            _serializer.parse = _serializer.resurrect;
        } else {
            _serializer = JSON;
        }

        var gui = {
            datGui: datGui,
            amount: 1,
            size: 40,
            sides: 4,
            density: 0.001,
            restitution: 0,
            friction: 0.1,
            frictionAir: 0.01,
            renderer: 'canvas'
        };

        var funcs = {

            addBody: function() {
                var options = {
                    density: gui.density,
                    friction: gui.friction,
                    frictionAir: gui.frictionAir,
                    restitution: gui.restitution
                };

                for (var i = 0; i < gui.amount; i++) {
                    World.add(engine.world, Bodies.polygon(120 + i * gui.size + i * 50, 200, gui.sides, gui.size, options));
                }
            },

            clear: function() {
                World.clear(engine.world, true);
                Engine.clear(engine);

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

                /**
                * Fired after the gui's clear button pressed
                *
                * @event clear
                * @param {} event An event object
                * @param {} event.source The source object of the event
                * @param {} event.name The name of the event
                */
                Events.trigger(gui, 'clear');
            },

            save: function() {
                if (localStorage && _serializer) {
                    localStorage.setItem('world', _serializer.stringify(engine.world));
                }

                /**
                * Fired after the gui's save button pressed
                *
                * @event save
                * @param {} event An event object
                * @param {} event.source The source object of the event
                * @param {} event.name The name of the event
                */
                Events.trigger(gui, 'save');
            },

            load: function() {
                var loadedWorld;

                if (localStorage && _serializer) {
                    loadedWorld = _serializer.parse(localStorage.getItem('world'));
                }

                if (loadedWorld) {
                    Engine.merge(engine, { world: loadedWorld });
                }

                /**
                * Fired after the gui's load button pressed
                *
                * @event load
                * @param {} event An event object
                * @param {} event.source The source object of the event
                * @param {} event.name The name of the event
                */
                Events.trigger(gui, 'load');
            }
        };

        var metrics = datGui.addFolder('Metrics');
        metrics.add(engine.timing, 'fps').listen();

        if (engine.metrics.extended) {
            metrics.add(engine.timing, 'delta').listen();
            metrics.add(engine.timing, 'correction').listen();
            metrics.add(engine.metrics, 'bodies').listen();
            metrics.add(engine.metrics, 'collisions').listen();
            metrics.add(engine.metrics, 'pairs').listen();
            metrics.add(engine.metrics, 'broadEff').listen();
            metrics.add(engine.metrics, 'midEff').listen();
            metrics.add(engine.metrics, 'narrowEff').listen();
            metrics.add(engine.metrics, 'narrowReuse').listen();
            metrics.close();
        } else {
            metrics.open();
        }

        var controls = datGui.addFolder('Add Body');
        controls.add(gui, 'amount', 1, 5).step(1);
        controls.add(gui, 'size', 5, 150).step(1);
        controls.add(gui, 'sides', 1, 8).step(1);
        controls.add(gui, 'density', 0.0001, 0.01).step(0.001);
        controls.add(gui, 'friction', 0, 1).step(0.05);
        controls.add(gui, 'frictionAir', 0, gui.frictionAir * 10).step(gui.frictionAir / 10);
        controls.add(gui, 'restitution', 0, 1).step(0.1);
        controls.add(funcs, 'addBody');
        controls.open();

        var worldGui = datGui.addFolder('World');
        worldGui.add(funcs, 'load');
        worldGui.add(funcs, 'save');
        worldGui.add(funcs, 'clear');
        worldGui.open();

        var gravity = worldGui.addFolder('Gravity');
        gravity.add(engine.world.gravity, 'x', -1, 1).step(0.01);
        gravity.add(engine.world.gravity, 'y', -1, 1).step(0.01);
        gravity.open();

        var physics = datGui.addFolder('Engine');
        physics.add(engine, 'enableSleeping');

        physics.add(engine.broadphase, 'current', ['grid', 'bruteForce'])
            .onFinishChange(function(value) {
                Composite.setModified(engine.world, true, false, false);
            });

        physics.add(engine.timing, 'timeScale', 0, 1.2).step(0.05);
        physics.add(engine, 'velocityIterations', 1, 10).step(1);
        physics.add(engine, 'positionIterations', 1, 10).step(1);
        physics.add(engine, 'enabled');
        physics.open();

        var render = datGui.addFolder('Render');

        render.add(gui, 'renderer', ['canvas', 'webgl'])
            .onFinishChange(function(value) {
                var controller;

                if (value === 'canvas')
                    controller = Render;

                if (value === 'webgl')
                    controller = RenderPixi;

                // remove old canvas
                engine.render.element.removeChild(engine.render.canvas);

                // create new renderer using the same options object
                var options = engine.render.options;

                engine.render = controller.create({
                    element: engine.render.element,
                    options: options
                });

                engine.render.options = options;

                // bind the mouse to the new canvas
                Mouse.setElement(engine.input.mouse, engine.render.canvas);
            });

        render.add(engine.render.options, 'wireframes');
        render.add(engine.render.options, 'showDebug');
        render.add(engine.render.options, 'showPositions');
        render.add(engine.render.options, 'showBroadphase');
        render.add(engine.render.options, 'showBounds');
        render.add(engine.render.options, 'showVelocity');
        render.add(engine.render.options, 'showCollisions');
        render.add(engine.render.options, 'showAxes');
        render.add(engine.render.options, 'showAngleIndicator');
        render.add(engine.render.options, 'showSleeping');
        render.add(engine.render.options, 'showIds');
        render.add(engine.render.options, 'showShadows');
        render.add(engine.render.options, 'enabled');
        render.open();

        //datGui.remember(world)

        return gui;
    };

    /**
     * Description
     * @method update
     * @param {gui} gui
     * @param {datGui} datGui
     */
    Gui.update = function(gui, datGui) {
        var i;
        datGui = datGui || gui.datGui;

        for (i in datGui.__folders) {
            Gui.update(gui, datGui.__folders[i]);
        }

        for (i in datGui.__controllers) {
            var controller = datGui.__controllers[i];
            if (controller.updateDisplay)
                controller.updateDisplay();
        }
    };

    /**
     * Description
     * @method closeAll
     * @param {gui} gui
     */
    Gui.closeAll = function(gui) {
        var datGui = gui.datGui;

        for (var i in datGui.__folders) {
            datGui.__folders[i].close();
        }
    };

})();<commit_msg>added world file saving and loading to Gui<commit_after>/**
* See [Demo.js](https://github.com/liabru/matter-js/blob/master/demo/js/Demo.js)
* and [DemoMobile.js](https://github.com/liabru/matter-js/blob/master/demo/js/DemoMobile.js) for usage examples.
*
* @class Gui
*/

var Gui = {};

(function() {

    /**
     * Description
     * @method create
     * @param {engine} engine
     * @param {object} options
     * @return {gui} A container for a configured dat.gui
     */
    Gui.create = function(engine, options) {
        var _datGuiSupported = window.dat && window.localStorage,
            _serializer;

        if (!_datGuiSupported) {
            console.log("Could not create GUI. Check dat.gui library is loaded first.");
            return;
        }

        var datGui = new dat.GUI(options);

        if (Resurrect) {
            _serializer = new Resurrect({ prefix: '$' });
            _serializer.parse = _serializer.resurrect;
        } else {
            _serializer = JSON;
        }

        var gui = {
            datGui: datGui,
            amount: 1,
            size: 40,
            sides: 4,
            density: 0.001,
            restitution: 0,
            friction: 0.1,
            frictionAir: 0.01,
            renderer: 'canvas'
        };

        var funcs = {

            addBody: function() {
                var options = {
                    density: gui.density,
                    friction: gui.friction,
                    frictionAir: gui.frictionAir,
                    restitution: gui.restitution
                };

                for (var i = 0; i < gui.amount; i++) {
                    World.add(engine.world, Bodies.polygon(120 + i * gui.size + i * 50, 200, gui.sides, gui.size, options));
                }
            },

            clear: function() {
                World.clear(engine.world, true);
                Engine.clear(engine);

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

                /**
                * Fired after the gui's clear button pressed
                *
                * @event clear
                * @param {} event An event object
                * @param {} event.source The source object of the event
                * @param {} event.name The name of the event
                */
                Events.trigger(gui, 'clear');
            },

            save: function() {
                if (localStorage && _serializer) {
                    localStorage.setItem('world', _serializer.stringify(engine.world));
                }

                /**
                * Fired after the gui's save button pressed
                *
                * @event save
                * @param {} event An event object
                * @param {} event.source The source object of the event
                * @param {} event.name The name of the event
                */
                Events.trigger(gui, 'save');
            },

            saveFile: function() {
                if (_serializer) {
                    var json = _serializer.stringify(engine.world);

                    // limit precision of floats
                    json = json.replace(/\d+\.(\d+)/g, function(match, frac) {
                        if (frac.length > 2)
                            return Number.parseFloat(match).toFixed(2);
                        return match;
                    });

                    var blob = new Blob([json], { type: 'application/json' }),
                        anchor = document.createElement('a');

                    anchor.download = "world.json";
                    anchor.href = (window.webkitURL || window.URL).createObjectURL(blob);
                    anchor.dataset.downloadurl = ['application/json', anchor.download, anchor.href].join(':');
                    anchor.click();
                }

                Events.trigger(gui, 'save');
            },

            load: function() {
                var loadedWorld;

                if (localStorage && _serializer) {
                    loadedWorld = _serializer.parse(localStorage.getItem('world'));
                }

                if (loadedWorld) {
                    Engine.merge(engine, { world: loadedWorld });
                }

                /**
                * Fired after the gui's load button pressed
                *
                * @event load
                * @param {} event An event object
                * @param {} event.source The source object of the event
                * @param {} event.name The name of the event
                */
                Events.trigger(gui, 'load');
            },

            loadFile: function() {
                var element = document.createElement('div');
                element.innerHTML = '<input type="file">';
                var fileInput = element.firstChild;

                fileInput.addEventListener('change', function(e) {
                    var file = fileInput.files[0];

                    if (file.name.match(/\.(txt|json)$/)) {
                        var reader = new FileReader();

                        reader.onload = function(e) {
                            var loadedWorld;

                            if (_serializer)
                                loadedWorld = _serializer.parse(reader.result);

                            if (loadedWorld) {
                                Engine.merge(engine, { world: loadedWorld });
                            }

                            Events.trigger(gui, 'load');
                        }

                        reader.readAsText(file);
                    } else {
                        alert("File not supported, JSON text files only");
                    }
                });

                fileInput.click();
            }
        };

        var metrics = datGui.addFolder('Metrics');
        metrics.add(engine.timing, 'fps').listen();

        if (engine.metrics.extended) {
            metrics.add(engine.timing, 'delta').listen();
            metrics.add(engine.timing, 'correction').listen();
            metrics.add(engine.metrics, 'bodies').listen();
            metrics.add(engine.metrics, 'collisions').listen();
            metrics.add(engine.metrics, 'pairs').listen();
            metrics.add(engine.metrics, 'broadEff').listen();
            metrics.add(engine.metrics, 'midEff').listen();
            metrics.add(engine.metrics, 'narrowEff').listen();
            metrics.add(engine.metrics, 'narrowReuse').listen();
            metrics.close();
        } else {
            metrics.open();
        }

        var controls = datGui.addFolder('Add Body');
        controls.add(gui, 'amount', 1, 5).step(1);
        controls.add(gui, 'size', 5, 150).step(1);
        controls.add(gui, 'sides', 1, 8).step(1);
        controls.add(gui, 'density', 0.0001, 0.01).step(0.001);
        controls.add(gui, 'friction', 0, 1).step(0.05);
        controls.add(gui, 'frictionAir', 0, gui.frictionAir * 10).step(gui.frictionAir / 10);
        controls.add(gui, 'restitution', 0, 1).step(0.1);
        controls.add(funcs, 'addBody');
        controls.open();

        var worldGui = datGui.addFolder('World');
        worldGui.add(funcs, 'load');
        worldGui.add(funcs, 'save');
        worldGui.add(funcs, 'loadFile');
        worldGui.add(funcs, 'saveFile');
        worldGui.add(funcs, 'clear');
        worldGui.open();

        var gravity = worldGui.addFolder('Gravity');
        gravity.add(engine.world.gravity, 'x', -1, 1).step(0.01);
        gravity.add(engine.world.gravity, 'y', -1, 1).step(0.01);
        gravity.open();

        var physics = datGui.addFolder('Engine');
        physics.add(engine, 'enableSleeping');

        physics.add(engine.broadphase, 'current', ['grid', 'bruteForce'])
            .onFinishChange(function(value) {
                Composite.setModified(engine.world, true, false, false);
            });

        physics.add(engine.timing, 'timeScale', 0, 1.2).step(0.05);
        physics.add(engine, 'velocityIterations', 1, 10).step(1);
        physics.add(engine, 'positionIterations', 1, 10).step(1);
        physics.add(engine, 'enabled');
        physics.open();

        var render = datGui.addFolder('Render');

        render.add(gui, 'renderer', ['canvas', 'webgl'])
            .onFinishChange(function(value) {
                var controller;

                if (value === 'canvas')
                    controller = Render;

                if (value === 'webgl')
                    controller = RenderPixi;

                // remove old canvas
                engine.render.element.removeChild(engine.render.canvas);

                // create new renderer using the same options object
                var options = engine.render.options;

                engine.render = controller.create({
                    element: engine.render.element,
                    options: options
                });

                engine.render.options = options;

                // bind the mouse to the new canvas
                Mouse.setElement(engine.input.mouse, engine.render.canvas);
            });

        render.add(engine.render.options, 'wireframes');
        render.add(engine.render.options, 'showDebug');
        render.add(engine.render.options, 'showPositions');
        render.add(engine.render.options, 'showBroadphase');
        render.add(engine.render.options, 'showBounds');
        render.add(engine.render.options, 'showVelocity');
        render.add(engine.render.options, 'showCollisions');
        render.add(engine.render.options, 'showAxes');
        render.add(engine.render.options, 'showAngleIndicator');
        render.add(engine.render.options, 'showSleeping');
        render.add(engine.render.options, 'showIds');
        render.add(engine.render.options, 'showShadows');
        render.add(engine.render.options, 'enabled');
        render.open();

        //datGui.remember(world)

        return gui;
    };

    /**
     * Description
     * @method update
     * @param {gui} gui
     * @param {datGui} datGui
     */
    Gui.update = function(gui, datGui) {
        var i;
        datGui = datGui || gui.datGui;

        for (i in datGui.__folders) {
            Gui.update(gui, datGui.__folders[i]);
        }

        for (i in datGui.__controllers) {
            var controller = datGui.__controllers[i];
            if (controller.updateDisplay)
                controller.updateDisplay();
        }
    };

    /**
     * Description
     * @method closeAll
     * @param {gui} gui
     */
    Gui.closeAll = function(gui) {
        var datGui = gui.datGui;

        for (var i in datGui.__folders) {
            datGui.__folders[i].close();
        }
    };

})();<|endoftext|>


<commit_before>import Ember from 'ember';
import Sound from './sound';
import BeatObject from './beat-object';

const {
  computed
} = Ember;

const Beat = Sound.extend({
  numBeats: 4,
  playingTime: 100,

  beats: computed('numBeats', function() {
    const beats = [];
    const numBeats = this.get('numBeats');

    for (let i = 0; i < numBeats; i++) {
      beats.push(BeatObject.create({
        playingTime: this.get('playingTime'),
        duration: this.get('audioBuffer.duration'),
        parentPlay: this.play.bind(this),
        audioContext: this.get('audioContext')
      }));
    }

    return beats;
  }),

  playBeats(bpm) {
    const bps = 60 / bpm;

    this.get('beats').map((beat, beatIndex) => {
      // Get the offset for each beat by multiplying it's index by the beats per second
      beat.play(beatIndex * bps);
    });
  }
});

export default Beat;
<commit_msg>playBeats now takes optional beatLength and beatsInMeasure<commit_after>import Ember from 'ember';
import Sound from './sound';
import BeatObject from './beat-object';

const {
  computed
} = Ember;

const Beat = Sound.extend({
  numBeats: 4,
  playingTime: 100,

  beats: computed('numBeats', function() {
    const beats = [];
    const numBeats = this.get('numBeats');

    for (let i = 0; i < numBeats; i++) {
      beats.push(BeatObject.create({
        playingTime: this.get('playingTime'),
        duration: this.get('audioBuffer.duration'),
        parentPlay: this.play.bind(this),
        audioContext: this.get('audioContext')
      }));
    }

    return beats;
  }),

  playBeats(bpm, beatLength=1/4, beatsInMeasure=4) {
    const bps = 60 / bpm;

    this.get('beats').map((beat, beatIndex) => {
      beat.play(beatIndex * bps * beatLength * beatsInMeasure);
    });
  }
});

export default Beat;
<|endoftext|>


<commit_before>'use strict';
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2015-2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Alan Plum
////////////////////////////////////////////////////////////////////////////////

const _ = require('lodash');
const joi = require('joi');
const assert = require('assert');
const statuses = require('statuses');
const mimeTypes = require('mime-types');
const mediaTyper = require('media-typer');
const joiToJsonSchema = require('joi-to-json-schema');
const il = require('@arangodb/util').inline;
const tokenize = require('@arangodb/foxx/router/tokenize');

const MIME_JSON = 'application/json; charset=utf-8';
const MIME_BINARY = 'application/octet-stream';
const DEFAULT_BODY_SCHEMA = joi.object().unknown().meta({allowInvalid: true}).optional();
const DEFAULT_ERROR_SCHEMA = joi.object().keys({
  error: joi.allow(true).required(),
  errorNum: joi.number().integer().optional(),
  errorMessage: joi.string().optional(),
  code: joi.number().integer().optional()
});

module.exports = exports = class SwaggerContext {
  constructor(path) {
    if (!path) {
      path = '';
    }
    {
      const n = path.length - 1;
      if (path.charAt(n) === '/') {
        path = path.slice(0, n);
      }
      if (path.charAt(0) !== '/') {
        path = `/${path}`;
      }
    }
    this._headers = new Map();
    this._queryParams = new Map();
    this._bodyParam = null;
    this._responses = new Map();
    this._summary = null;
    this._description = null;
    this._deprecated = false;
    this.path = path;
    this._pathParams = new Map();
    this._pathParamNames = [];
    this._pathTokens = tokenize(path, this);
  }

  header(name, schema, description) {
    this._headers.set(name, {schema: schema, description: description});
    return this;
  }

  pathParam(name, schema, description) {
    this._pathParams.set(name, {schema: schema, description: description});
    return this;
  }

  queryParam(name, schema, description) {
    this._queryParams.set(name, {schema: schema, description: description});
    return this;
  }

  body(model, mimes, description) {
    if (
      typeof model === 'string'
      || (Array.isArray(model) && typeof model[0] === 'string')
    ) {
      description = mimes;
      mimes = model;
      model = undefined;
    }

    if (typeof mimes === 'string') {
      description = mimes;
      mimes = undefined;
    }

    let multiple = false;
    if (Array.isArray(model)) {
      if (model.length !== 1) {
        throw new Error(il`
          Model must be a model or schema
          or an array containing exactly one model or schema.
          If you are trying to use multiple schemas
          try using joi.alternatives instead.
        `);
      }
      model = model[0];
      multiple = true;
    }

    if (!mimes) {
      mimes = [];
    }

    if (!mimes.length && model) {
      mimes.push(MIME_JSON);
    }

    const contentTypes = mimes.map(function (mime) {
      if (mime === 'binary') {
        mime = MIME_BINARY;
      }
      const contentType = mimeTypes.contentType(mime) || mime;
      const parsed = mediaTyper.parse(contentType);
      return mediaTyper.format(_.pick(parsed, [
        'type',
        'subtype',
        'suffix'
      ]));
    });

    if (model) {
      if (model.isJoi) {
        model = {schema: model};
      } else {
        model = _.clone(model);
      }
      if (model.schema && !model.schema.isJoi) {
        model.schema = joi.object(model.schema).required();
      }
      assert(!model.forClient || typeof model.forClient === 'function', il`
        Request body model forClient handler must be a function,
        not ${typeof model.forClient}
      `);
      assert(!model.fromClient || typeof model.fromClient === 'function', il`
        Request body model fromClient handler must be a function,
        not ${typeof model.fromClient}
      `);
      if (!model.forClient && typeof model.toClient === 'function') {
        console.log(il`
          Found unexpected "toClient" method on request body model.
          Did you mean "forClient"?
        `);
      }
    }

    this._bodyParam = {
      model: model,
      multiple: multiple,
      contentTypes: contentTypes,
      description: description
    };
    return this;
  }

  response(status, model, mimes, reason) {
    let statusCode = Number(status);

    if (!status || Number.isNaN(statusCode)) {
      reason = mimes;
      mimes = model;
      model = status;
      statusCode = model === null ? 204 : 200;
    }

    if (
      typeof model === 'string'
      || (Array.isArray(model) && typeof model[0] === 'string')
    ) {
      reason = mimes;
      mimes = model;
      model = undefined;
    }

    if (typeof mimes === 'string') {
      reason = mimes;
      mimes = undefined;
    }

    let multiple = false;
    if (Array.isArray(model)) {
      if (model.length !== 1) {
        throw new Error(il`
          Model must be a model or schema
          or an array containing exactly one model or schema.
          If you are trying to use multiple schemas
          try using joi.alternatives instead.
        `);
      }
      model = model[0];
      multiple = true;
    }

    if (!mimes) {
      mimes = [];
    }

    if (!mimes.length && model) {
      mimes.push(MIME_JSON);
    }

    const contentTypes = mimes.map(function (mime) {
      if (mime === 'binary') {
        mime = MIME_BINARY;
      }
      const contentType = mimeTypes.contentType(mime) || mime;
      const parsed = mediaTyper.parse(contentType);
      return mediaTyper.format(_.pick(parsed, [
        'type',
        'subtype',
        'suffix'
      ]));
    });

    if (model) {
      if (model.isJoi) {
        model = {schema: model};
      } else {
        model = _.clone(model);
      }
      if (model.schema && !model.schema.isJoi) {
        model.schema = joi.object(model.schema).required();
      }
      assert(!model.forClient || typeof model.forClient === 'function', il`
        Response body model forClient handler at ${statusCode} must be a function,
        not ${typeof model.forClient}
      `);
      assert(!model.fromClient || typeof model.fromClient === 'function', il`
        Response body model fromClient handler at ${statusCode} must be a function,
        not ${typeof model.fromClient}
      `);
      if (!model.forClient && typeof model.toClient === 'function') {
        console.log(il`
          Found unexpected "toClient" method on response body model at ${statusCode}.
          Did you mean "forClient"?
        `);
      }
    }

    this._responses.set(statusCode, {
      model: model,
      multiple: multiple,
      contentTypes: contentTypes,
      description: reason
    });
    return this;
  }

  error(status, reason) {
    if (typeof status === 'string') {
      status = statuses(status);
    }
    return this.response(
      status,
      DEFAULT_ERROR_SCHEMA,
      null,
      reason
    );
  }

  summary(text) {
    this._summary = text;
    return this;
  }

  description(text) {
    this._description = text;
    return this;
  }

  deprecated(flag) {
    this._deprecated = typeof flag === 'boolean' ? flag : true;
    return this;
  }

  _merge(swaggerObj, pathOnly) {
    if (!pathOnly) {
      for (const header of swaggerObj._headers.entries()) {
        this._headers.set(header[0], header[1]);
      }
      for (const queryParam of swaggerObj._queryParams.entries()) {
        this._queryParams.set(queryParam[0], queryParam[1]);
      }
      for (const response of swaggerObj._responses.entries()) {
        this._responses.set(response[0], response[1]);
      }
      if (swaggerObj._bodyParam) {
        if (!this._bodyParam || swaggerObj._bodyParam.type !== DEFAULT_BODY_SCHEMA) {
          this._bodyParam = swaggerObj._bodyParam;
        }
      }
      this._deprecated = swaggerObj._deprecated || this._deprecated;
      this._description = swaggerObj._description || this._description;
      this._summary = swaggerObj._summary || this._summary;
    }
    if (this.path.charAt(this.path.length - 1) === '*') {
      this.path = this.path.slice(0, this.path.length - 1);
    }
    if (this.path.charAt(this.path.length - 1) === '/') {
      this.path = this.path.slice(0, this.path.length - 1);
    }
    this._pathTokens.pop();
    this._pathTokens = this._pathTokens.concat(swaggerObj._pathTokens);
    for (const pathParam of swaggerObj._pathParams.entries()) {
      let name = pathParam[0];
      const def = pathParam[1];
      if (this._pathParams.has(name)) {
        let baseName = name;
        let i = 2;
        const match = name.match(/(^.+)([0-9]+)$/i);
        if (match) {
          baseName = match[1];
          i = Number(match[2]);
        }
        while (this._pathParams.has(baseName + i)) {
          i++;
        }
        name = baseName + i;
      }
      this._pathParams.set(name, def);
      this._pathParamNames.push(name);
    }
    this.path = tokenize.reverse(this._pathTokens, this._pathParamNames);
  }

  _buildOperation() {
    const operation = {
      produces: [],
      parameters: []
    };
    if (this._deprecated) {
      operation.deprecated = this._deprecated;
    }
    if (this._description) {
      operation.description = this._description;
    }
    if (this._summary) {
      operation.summary = this._summary;
    }
    if (this._bodyParam) {
      operation.consumes = (
        this._bodyParam.contentTypes
        ? this._bodyParam.contentTypes.slice()
        : []
      );
    }
    for (const response of this._responses.values()) {
      if (!response.contentTypes) {
        continue;
      }
      for (const contentType of response.contentTypes) {
        if (operation.produces.indexOf(contentType) === -1) {
          operation.produces.push(contentType);
        }
      }
    }
    if (operation.produces.indexOf('application/json') === -1) {
      // ArangoDB errors use 'application/json'
      operation.produces.push('application/json');
    }

    for (const param of this._pathParams.entries()) {
      const name = param[0];
      const def = param[1];
      const parameter = (
        def.schema
        ? swaggerifyParam(def.schema.isJoi ? def.schema : joi.object(def.schema))
        : {type: 'string'}
      );
      parameter.name = name;
      parameter.in = 'path';
      parameter.required = true;
      if (def.description) {
        parameter.description = def.description;
      }
      operation.parameters.push(parameter);
    }

    for (const param of this._queryParams.entries()) {
      const name = param[0];
      const def = param[1];
      const parameter = (
        def.schema
        ? swaggerifyParam(def.schema.isJoi ? def.schema : joi.object(def.schema))
        : {type: 'string'}
      );
      parameter.name = name;
      parameter.in = 'query';
      if (def.description) {
        parameter.description = def.description;
      }
      operation.parameters.push(parameter);
    }

    for (const param of this._headers.entries()) {
      const name = param[0];
      const def = param[1];
      const parameter = (
        def.schema
        ? swaggerifyParam(def.schema.isJoi ? def.schema : joi.object(def.schema))
        : {type: 'string'}
      );
      parameter.name = name;
      parameter.in = 'header';
      if (def.description) {
        parameter.description = def.description;
      }
      operation.parameters.push(parameter);
    }

    if (this._bodyParam && this._bodyParam.contentTypes) {
      const def = this._bodyParam;
      const schema = (
        def.model
        ? (def.model.isJoi ? def.model : def.model.schema)
        : null
      );
      const parameter = (
        schema
        ? swaggerifyBody(schema, def.multiple)
        : {schema: {type: 'string'}}
      );
      parameter.name = 'body';
      parameter.in = 'body';
      if (def.description) {
        parameter.description = def.description;
      }
      operation.parameters.push(parameter);
    }

    operation.responses = {
      default: {
        description: 'Unexpected error.',
        schema: joi2schema(DEFAULT_ERROR_SCHEMA)
      }
    };

    for (const entry of this._responses.entries()) {
      const code = entry[0];
      const def = entry[1];
      const schema = (
        def.model
        ? (def.model.isJoi ? def.model : def.model.schema)
        : null
      );
      const response = {};
      if (def.contentTypes && def.contentTypes.length) {
        response.schema = (
          schema
          ? joi2schema(schema.isJoi ? schema : joi.object(schema), def.multiple)
          : {type: 'string'}
        );
      }
      if (schema && schema._description) {
        response.description = schema._description;
        delete response.schema.description;
      }
      if (def.description) {
        response.description = def.description;
      }
      if (!response.description) {
        const message = statuses[code];
        response.description = message ? `HTTP ${code} ${message}.` : (
          response.schema
          ? `Nondescript ${code} response.`
          : `Nondescript ${code} response without body.`
        );
      }
      operation.responses[code] = response;
    }

    return operation;
  }
};

exports.DEFAULT_BODY_SCHEMA = DEFAULT_BODY_SCHEMA;

function swaggerifyType(joi) {
  switch (joi._type) {
    default:
      return ['string'];
    case 'binary':
      return ['string', 'binary'];
    case 'boolean':
      return ['boolean'];
    case 'date':
      return ['string', 'date-time'];
    case 'func':
      return ['string'];
    case 'number':
      if (joi._tests.some(function (test) {
        return test.name === 'integer';
      })) {
        return ['integer'];
      }
      return ['number'];
    case 'array':
      return ['array'];
    case 'object':
      return ['object'];
    case 'string':
      if (joi._meta.some(function (meta) {
        return meta.secret;
      })) {
        return ['string', 'password'];
      }
      return ['string'];
  }
}

function swaggerifyParam(joi) {
  const param = {
    required: joi._presence === 'required',
    description: joi._description
  };
  let item = param;
  if (joi._meta.some(function (meta) {
    return meta.allowMultiple;
  })) {
    param.type = 'array';
    param.collectionFormat = 'multi';
    param.items = {};
    item = param.items;
  }
  const type = swaggerifyType(joi);
  item.type = type[0];
  if (type.length > 1) {
    item.format = type[1];
  }
  if (joi._valids._set && joi._valids._set.length) {
    item.enum = joi._valids._set;
  }
  if (joi._flags.hasOwnProperty('default')) {
    item.default = joi._flags.default;
  }
  return param;
}

function swaggerifyBody(joi, multiple) {
  return {
    required: joi._presence === 'required',
    description: joi._description,
    schema: joi2schema(joi, multiple)
  };
}

function joi2schema(schema, multiple) {
  if (multiple) {
    schema = joi.array().items(schema);
  }
  return joiToJsonSchema(schema);
}
<commit_msg>Fix empty descriptions in swagger<commit_after>'use strict';
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2015-2016 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Alan Plum
////////////////////////////////////////////////////////////////////////////////

const _ = require('lodash');
const joi = require('joi');
const assert = require('assert');
const statuses = require('statuses');
const mimeTypes = require('mime-types');
const mediaTyper = require('media-typer');
const joiToJsonSchema = require('joi-to-json-schema');
const il = require('@arangodb/util').inline;
const tokenize = require('@arangodb/foxx/router/tokenize');

const MIME_JSON = 'application/json; charset=utf-8';
const MIME_BINARY = 'application/octet-stream';
const DEFAULT_BODY_SCHEMA = joi.object().unknown().meta({allowInvalid: true}).optional();
const DEFAULT_ERROR_SCHEMA = joi.object().keys({
  error: joi.allow(true).required(),
  errorNum: joi.number().integer().optional(),
  errorMessage: joi.string().optional(),
  code: joi.number().integer().optional()
});

module.exports = exports = class SwaggerContext {
  constructor(path) {
    if (!path) {
      path = '';
    }
    {
      const n = path.length - 1;
      if (path.charAt(n) === '/') {
        path = path.slice(0, n);
      }
      if (path.charAt(0) !== '/') {
        path = `/${path}`;
      }
    }
    this._headers = new Map();
    this._queryParams = new Map();
    this._bodyParam = null;
    this._responses = new Map();
    this._summary = null;
    this._description = null;
    this._deprecated = false;
    this.path = path;
    this._pathParams = new Map();
    this._pathParamNames = [];
    this._pathTokens = tokenize(path, this);
  }

  header(name, schema, description) {
    this._headers.set(name, {schema, description});
    return this;
  }

  pathParam(name, schema, description) {
    this._pathParams.set(name, {schema, description});
    return this;
  }

  queryParam(name, schema, description) {
    this._queryParams.set(name, {schema, description});
    return this;
  }

  body(model, mimes, description) {
    if (
      typeof model === 'string'
      || (Array.isArray(model) && typeof model[0] === 'string')
    ) {
      description = mimes;
      mimes = model;
      model = undefined;
    }

    if (typeof mimes === 'string') {
      description = mimes;
      mimes = undefined;
    }

    let multiple = false;
    if (Array.isArray(model)) {
      if (model.length !== 1) {
        throw new Error(il`
          Model must be a model or schema
          or an array containing exactly one model or schema.
          If you are trying to use multiple schemas
          try using joi.alternatives instead.
        `);
      }
      model = model[0];
      multiple = true;
    }

    if (!mimes) {
      mimes = [];
    }

    if (!mimes.length && model) {
      mimes.push(MIME_JSON);
    }

    const contentTypes = mimes.map(function (mime) {
      if (mime === 'binary') {
        mime = MIME_BINARY;
      }
      const contentType = mimeTypes.contentType(mime) || mime;
      const parsed = mediaTyper.parse(contentType);
      return mediaTyper.format(_.pick(parsed, [
        'type',
        'subtype',
        'suffix'
      ]));
    });

    if (model) {
      if (model.isJoi) {
        model = {schema: model};
      } else {
        model = _.clone(model);
      }
      if (model.schema && !model.schema.isJoi) {
        model.schema = joi.object(model.schema).required();
      }
      assert(!model.forClient || typeof model.forClient === 'function', il`
        Request body model forClient handler must be a function,
        not ${typeof model.forClient}
      `);
      assert(!model.fromClient || typeof model.fromClient === 'function', il`
        Request body model fromClient handler must be a function,
        not ${typeof model.fromClient}
      `);
      if (!model.forClient && typeof model.toClient === 'function') {
        console.log(il`
          Found unexpected "toClient" method on request body model.
          Did you mean "forClient"?
        `);
      }
    }

    this._bodyParam = {
      model,
      multiple,
      contentTypes,
      description
    };
    return this;
  }

  response(status, model, mimes, reason) {
    let statusCode = Number(status);

    if (!status || Number.isNaN(statusCode)) {
      reason = mimes;
      mimes = model;
      model = status;
      statusCode = model === null ? 204 : 200;
    }

    if (
      typeof model === 'string'
      || (Array.isArray(model) && typeof model[0] === 'string')
    ) {
      reason = mimes;
      mimes = model;
      model = undefined;
    }

    if (typeof mimes === 'string') {
      reason = mimes;
      mimes = undefined;
    }

    let multiple = false;
    if (Array.isArray(model)) {
      if (model.length !== 1) {
        throw new Error(il`
          Model must be a model or schema
          or an array containing exactly one model or schema.
          If you are trying to use multiple schemas
          try using joi.alternatives instead.
        `);
      }
      model = model[0];
      multiple = true;
    }

    if (!mimes) {
      mimes = [];
    }

    if (!mimes.length && model) {
      mimes.push(MIME_JSON);
    }

    const contentTypes = mimes.map(function (mime) {
      if (mime === 'binary') {
        mime = MIME_BINARY;
      }
      const contentType = mimeTypes.contentType(mime) || mime;
      const parsed = mediaTyper.parse(contentType);
      return mediaTyper.format(_.pick(parsed, [
        'type',
        'subtype',
        'suffix'
      ]));
    });

    if (model) {
      if (model.isJoi) {
        model = {schema: model};
      } else {
        model = _.clone(model);
      }
      if (model.schema && !model.schema.isJoi) {
        model.schema = joi.object(model.schema).required();
      }
      assert(!model.forClient || typeof model.forClient === 'function', il`
        Response body model forClient handler at ${statusCode} must be a function,
        not ${typeof model.forClient}
      `);
      assert(!model.fromClient || typeof model.fromClient === 'function', il`
        Response body model fromClient handler at ${statusCode} must be a function,
        not ${typeof model.fromClient}
      `);
      if (!model.forClient && typeof model.toClient === 'function') {
        console.log(il`
          Found unexpected "toClient" method on response body model at ${statusCode}.
          Did you mean "forClient"?
        `);
      }
    }

    this._responses.set(statusCode, {
      model,
      multiple,
      contentTypes,
      description: reason
    });
    return this;
  }

  error(status, reason) {
    if (typeof status === 'string') {
      status = statuses(status);
    }
    return this.response(
      status,
      DEFAULT_ERROR_SCHEMA,
      null,
      reason
    );
  }

  summary(text) {
    this._summary = text;
    return this;
  }

  description(text) {
    this._description = text;
    return this;
  }

  deprecated(flag) {
    this._deprecated = typeof flag === 'boolean' ? flag : true;
    return this;
  }

  _merge(swaggerObj, pathOnly) {
    if (!pathOnly) {
      for (const header of swaggerObj._headers.entries()) {
        this._headers.set(header[0], header[1]);
      }
      for (const queryParam of swaggerObj._queryParams.entries()) {
        this._queryParams.set(queryParam[0], queryParam[1]);
      }
      for (const response of swaggerObj._responses.entries()) {
        this._responses.set(response[0], response[1]);
      }
      if (swaggerObj._bodyParam) {
        if (!this._bodyParam || swaggerObj._bodyParam.type !== DEFAULT_BODY_SCHEMA) {
          this._bodyParam = swaggerObj._bodyParam;
        }
      }
      this._deprecated = swaggerObj._deprecated || this._deprecated;
      this._description = swaggerObj._description || this._description;
      this._summary = swaggerObj._summary || this._summary;
    }
    if (this.path.charAt(this.path.length - 1) === '*') {
      this.path = this.path.slice(0, this.path.length - 1);
    }
    if (this.path.charAt(this.path.length - 1) === '/') {
      this.path = this.path.slice(0, this.path.length - 1);
    }
    this._pathTokens.pop();
    this._pathTokens = this._pathTokens.concat(swaggerObj._pathTokens);
    for (const pathParam of swaggerObj._pathParams.entries()) {
      let name = pathParam[0];
      const def = pathParam[1];
      if (this._pathParams.has(name)) {
        let baseName = name;
        let i = 2;
        const match = name.match(/(^.+)([0-9]+)$/i);
        if (match) {
          baseName = match[1];
          i = Number(match[2]);
        }
        while (this._pathParams.has(baseName + i)) {
          i++;
        }
        name = baseName + i;
      }
      this._pathParams.set(name, def);
      this._pathParamNames.push(name);
    }
    this.path = tokenize.reverse(this._pathTokens, this._pathParamNames);
  }

  _buildOperation() {
    const operation = {
      produces: [],
      parameters: []
    };
    if (this._deprecated) {
      operation.deprecated = this._deprecated;
    }
    if (this._description) {
      operation.description = this._description;
    }
    if (this._summary) {
      operation.summary = this._summary;
    }
    if (this._bodyParam) {
      operation.consumes = (
        this._bodyParam.contentTypes
        ? this._bodyParam.contentTypes.slice()
        : []
      );
    }
    for (const response of this._responses.values()) {
      if (!response.contentTypes) {
        continue;
      }
      for (const contentType of response.contentTypes) {
        if (operation.produces.indexOf(contentType) === -1) {
          operation.produces.push(contentType);
        }
      }
    }
    if (operation.produces.indexOf('application/json') === -1) {
      // ArangoDB errors use 'application/json'
      operation.produces.push('application/json');
    }

    for (const param of this._pathParams.entries()) {
      const name = param[0];
      const def = param[1];
      const parameter = (
        def.schema
        ? swaggerifyParam(def.schema.isJoi ? def.schema : joi.object(def.schema))
        : {type: 'string'}
      );
      parameter.name = name;
      parameter.in = 'path';
      parameter.required = true;
      if (def.description) {
        parameter.description = def.description;
      }
      operation.parameters.push(parameter);
    }

    for (const param of this._queryParams.entries()) {
      const name = param[0];
      const def = param[1];
      const parameter = (
        def.schema
        ? swaggerifyParam(def.schema.isJoi ? def.schema : joi.object(def.schema))
        : {type: 'string'}
      );
      parameter.name = name;
      parameter.in = 'query';
      if (def.description) {
        parameter.description = def.description;
      }
      operation.parameters.push(parameter);
    }

    for (const param of this._headers.entries()) {
      const name = param[0];
      const def = param[1];
      const parameter = (
        def.schema
        ? swaggerifyParam(def.schema.isJoi ? def.schema : joi.object(def.schema))
        : {type: 'string'}
      );
      parameter.name = name;
      parameter.in = 'header';
      if (def.description) {
        parameter.description = def.description;
      }
      operation.parameters.push(parameter);
    }

    if (this._bodyParam && this._bodyParam.contentTypes) {
      const def = this._bodyParam;
      const schema = (
        def.model
        ? (def.model.isJoi ? def.model : def.model.schema)
        : null
      );
      const parameter = (
        schema
        ? swaggerifyBody(schema, def.multiple)
        : {schema: {type: 'string'}}
      );
      parameter.name = 'body';
      parameter.in = 'body';
      if (def.description) {
        parameter.description = def.description;
      }
      operation.parameters.push(parameter);
    }

    operation.responses = {
      default: {
        description: 'Unexpected error.',
        schema: joi2schema(DEFAULT_ERROR_SCHEMA)
      }
    };

    for (const entry of this._responses.entries()) {
      const code = entry[0];
      const def = entry[1];
      const schema = (
        def.model
        ? (def.model.isJoi ? def.model : def.model.schema)
        : null
      );
      const response = {};
      if (def.contentTypes && def.contentTypes.length) {
        response.schema = (
          schema
          ? joi2schema(schema.isJoi ? schema : joi.object(schema), def.multiple)
          : {type: 'string'}
        );
      }
      if (schema && schema._description) {
        response.description = schema._description;
        delete response.schema.description;
      }
      if (def.description) {
        response.description = def.description;
      }
      if (!response.description) {
        const message = statuses[code];
        response.description = message ? `HTTP ${code} ${message}.` : (
          response.schema
          ? `Nondescript ${code} response.`
          : `Nondescript ${code} response without body.`
        );
      }
      operation.responses[code] = response;
    }

    return operation;
  }
};

exports.DEFAULT_BODY_SCHEMA = DEFAULT_BODY_SCHEMA;

function swaggerifyType(joi) {
  switch (joi._type) {
    default:
      return ['string'];
    case 'binary':
      return ['string', 'binary'];
    case 'boolean':
      return ['boolean'];
    case 'date':
      return ['string', 'date-time'];
    case 'func':
      return ['string'];
    case 'number':
      if (joi._tests.some(function (test) {
        return test.name === 'integer';
      })) {
        return ['integer'];
      }
      return ['number'];
    case 'array':
      return ['array'];
    case 'object':
      return ['object'];
    case 'string':
      if (joi._meta.some(function (meta) {
        return meta.secret;
      })) {
        return ['string', 'password'];
      }
      return ['string'];
  }
}

function swaggerifyParam(joi) {
  const param = {
    required: joi._presence === 'required',
    description: joi._description || undefined
  };
  let item = param;
  if (joi._meta.some(function (meta) {
    return meta.allowMultiple;
  })) {
    param.type = 'array';
    param.collectionFormat = 'multi';
    param.items = {};
    item = param.items;
  }
  const type = swaggerifyType(joi);
  item.type = type[0];
  if (type.length > 1) {
    item.format = type[1];
  }
  if (joi._valids._set && joi._valids._set.length) {
    item.enum = joi._valids._set;
  }
  if (joi._flags.hasOwnProperty('default')) {
    item.default = joi._flags.default;
  }
  return param;
}

function swaggerifyBody(joi, multiple) {
  return {
    required: joi._presence === 'required',
    description: joi._description || undefined,
    schema: joi2schema(joi, multiple)
  };
}

function joi2schema(schema, multiple) {
  if (multiple) {
    schema = joi.array().items(schema);
  }
  return joiToJsonSchema(schema);
}
<|endoftext|>


<commit_before>({
  appDir: 'www',
  dir: 'www-built',
  baseUrl: '.',
  fileExclusionRegExp: /(^example)|(.git)$/,
  map: {
    '*': {
      less: 'require-less/less',
      css: 'require-css/css'
    }
  },
  paths: {
    c: 'less'
  },
  modules: [
    {
      name: 'core-components',
      create: true,
      include: ['components/component', 'css'],
      excludeShallow: ['require-css/css-builder', 'require-less/lessc-server', 'require-less/lessc']
    },
    {
      name: 'app',
      exclude: ['core-components', 'less']
    }
  ]
})
<commit_msg>build update<commit_after>({
  appDir: 'www',
  dir: 'www-built',
  baseUrl: '.',
  fileExclusionRegExp: /(^example)|(.git)$/,
  map: {
    '*': {
      less: 'require-less/less',
      css: 'require-css/css'
    }
  },
  paths: {
    c: 'less'
  },
  modules: [
    {
      name: 'core-components',
      create: true,
      include: ['components/component', 'css'],
      excludeShallow: ['require-css/css-builder', 'require-less/lessc-server']
    },
    {
      name: 'app',
      exclude: ['core-components', 'less']
    }
  ]
})
<|endoftext|>


<commit_before>const matchAll = require("../lib");

var s = "Hello _World_ and _Mars_";
console.log(matchAll(s, /_([a-z]+)_/gi).toArray());
// => [ "World", "Mars" ]

// Get matches one by one
var m = matchAll(s, /_([a-z]+)_/gi);
console.log(m.next());
// => "World"

console.log(m.next());
// => "Mars"

console.log(m.next());
// => null

var m2 = matchAll("Hello _World_, _Mars_, _Pluto_ and _Moon_!", /_([a-z]+)_/gi);
console.log(m2.next());
// => "World"

// Reset the match index
m2.reset();

console.log(m2.next());
// => "World"

console.log(m2.next());
// => "Mars"

// Set the match index to 20
m2.reset(20);

console.log(m2.next());
// => "Pluto"
<commit_msg>Update index.js<commit_after>const matchAll = require("../lib");

var s = "Hello _World_ and _Mars_";
console.log(matchAll(s, /_([a-z]+)_/gi).toArray());
// => [ "World", "Mars" ]

// Get matches one by one
var m = matchAll(s, /_([a-z]+)_/gi);
console.log(m.next());
// => "World"

console.log(m.next());
// => "Mars"

console.log(m.next());
// => null

var multipleGroup = "Hello _World001_ and _World002_";
console.log(matchAll(multipleGroup, /_([a-z]+([0-9]+))_/gi).toArray());
// => [ "World", "Mars" ]

// Get matches one by one
var multipleMatch = matchAll(multipleGroup, /_([a-z]+([0-9]+))_/gi);
console.log(multipleMatch.nextRaw());
// => [..., "World001", "001"]

console.log(multipleMatch.nextRaw());
// => [..., "World002", "002"]

var m2 = matchAll("Hello _World_, _Mars_, _Pluto_ and _Moon_!", /_([a-z]+)_/gi);
console.log(m2.next());
// => "World"

// Reset the match index
m2.reset();

console.log(m2.next());
// => "World"

console.log(m2.next());
// => "Mars"

// Set the match index to 20
m2.reset(20);

console.log(m2.next());
// => "Pluto"
<|endoftext|>


<commit_before>const types = require("../lib");

// Create a new listener
var listener = new types.Listener("some event");

listener.addComponent(new types.DataHandler("someMethod", {
    to: "some-instance"
  , data: {
        key: "value"
    }
}));

console.log(listener);
<commit_msg>Examples<commit_after>const types = require("../lib");

// Create a new listener
var listener = new types.Listener("some event", "error event", "end event");

listener.addData(new types.DataHandler("someMethod", {
    to: "some-instance"
  , data: {
        key: "value"
    }
}));

console.log(listener);
// => Listener {
//   event_name: 'some event',
//   data:
//    [ DataHandler {
//        method: 'someMethod',
//        once: false,
//        to: 'some-instance',
//        data: {} } ],
//   error: 'error event',
//   end: 'end event' }
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import {App} from './App';
import './app.css';

const appRoot = document.createElement('div');

appRoot.id = 'app';
document.body.appendChild(appRoot);
ReactDOM.render(<App />, appRoot);
<commit_msg>Wrap Example app in React.Strict<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import {App} from './App';
import './app.css';

const appRoot = document.createElement('div');

appRoot.id = 'app';
document.body.appendChild(appRoot);
ReactDOM.render(<React.StrictMode><App /></React.StrictMode>, appRoot);
<|endoftext|>


<commit_before>import git from 'simple-git';

import * as env from './utils/env';

/**
 * Clone Repository
 *
 * @param {string} repoPath repository path
 * @param {string} cloneDir local path for clone
 * @return {Promise}
 */
export function cloneRepo(repoPath, cloneDir) {
  return new Promise((resolve, reject) => {
    git().clone(repoPath, cloneDir, err => {
      if (err) {
        reject(err);
      } else {
        resolve({repo: git(cloneDir)});
      }
    });
  });
}

/**
 * Get Repository name from remote path
 *
 * @param {string} repoPath repository path
 * @return {string}
 */
export function getRepoNameFromRemotePath(repoPath) {
  return repoPath.split('/').slice(-1)[0].split('.git')[0];
}

/**
 * Get Repository
 *
 * @param {string} repoPath repository path
 * @param {string} cloneDir local path for clone
 * @return {Promise}
 */
export function getRepo(repoPath, {cloneDir} = {}) {
  if (/^(?:(?:https?|ftps?|ssh|git|rsync):\/\/)/.test(repoPath)) {
    return cloneRepo(repoPath, cloneDir || getRepoNameFromRemotePath(repoPath));
  }
  return new Promise(resolve => {
    resolve({repo: git(repoPath)});
  });
}

/**
 * Get Diff Strings
 *
 * @param {Object} repo repository object of simple-git
 * @param {String[]} opts diff options for Git command
 * @return {Promise}
 */
export function getDiff(repo, ...opts) {
  return new Promise((resolve, reject) => {
    if (opts.length === 0) {
      opts.push('HEAD~1');
    }
    repo.diff(opts, (err, diff) => {
      if (err) {
        reject(err);
      } else {
        resolve(diff);
      }
    });
  });
}

/**
 * Get Diff Strings for Pages
 *
 * @param {Object} repo repository object of simple-git
 * @param {Object[]} pages pages
 * @return {Promise}
 */
export function getDiffPages(repo, ...pages) {
  return Promise.all(pages.map(page => {
    return getDiff(repo, `${page.sha}~1`).then(diff => ({page, diff}));
  }));
}

/**
 * Get remote repository path from payload object
 *
 * @param {Object} [payload] GitHub Webhook payload
 * @return {string}
 */
export function getRepoPathFromPayload(payload) {
  const repo = payload.repository;

  /**
   * @param {string} url repository path
   * @return {string}
   */
  function replace(url) {
    return url.replace(/\.git$/, '.wiki.git');
  }

  if (!repo.private) {
    return replace(repo.clone_url);
  }
  const token = env.get('GITHUB_TOKEN');
  if (token) {
    return replace(`https://${token}:@${repo.clone_url.split('https://')[0]}`);
  }
  return replace(repo.ssh_url);
}
<commit_msg>fix(repository): Fix diff of specific commit<commit_after>import git from 'simple-git';

import * as env from './utils/env';

/**
 * Clone Repository
 *
 * @param {string} repoPath repository path
 * @param {string} cloneDir local path for clone
 * @return {Promise}
 */
export function cloneRepo(repoPath, cloneDir) {
  return new Promise((resolve, reject) => {
    git().clone(repoPath, cloneDir, err => {
      if (err) {
        reject(err);
      } else {
        resolve({repo: git(cloneDir)});
      }
    });
  });
}

/**
 * Get Repository name from remote path
 *
 * @param {string} repoPath repository path
 * @return {string}
 */
export function getRepoNameFromRemotePath(repoPath) {
  return repoPath.split('/').slice(-1)[0].split('.git')[0];
}

/**
 * Get Repository
 *
 * @param {string} repoPath repository path
 * @param {string} cloneDir local path for clone
 * @return {Promise}
 */
export function getRepo(repoPath, {cloneDir} = {}) {
  if (/^(?:(?:https?|ftps?|ssh|git|rsync):\/\/)/.test(repoPath)) {
    return cloneRepo(repoPath, cloneDir || getRepoNameFromRemotePath(repoPath));
  }
  return new Promise(resolve => {
    resolve({repo: git(repoPath)});
  });
}

/**
 * Get Diff Strings
 *
 * @param {Object} repo repository object of simple-git
 * @param {String[]} opts diff options for Git command
 * @return {Promise}
 */
export function getDiff(repo, ...opts) {
  return new Promise((resolve, reject) => {
    repo.show(opts, (err, diff) => {
      if (err) {
        reject(err);
      } else {
        resolve(diff);
      }
    });
  });
}

/**
 * Get Diff Strings for Pages
 *
 * @param {Object} repo repository object of simple-git
 * @param {Object[]} pages pages
 * @return {Promise}
 */
export function getDiffPages(repo, ...pages) {
  return Promise.all(pages.map(page => {
    return getDiff(repo, `${page.sha}`, '--format=%N').then(diff => ({page, diff}));
  }));
}

/**
 * Get remote repository path from payload object
 *
 * @param {Object} [payload] GitHub Webhook payload
 * @return {string}
 */
export function getRepoPathFromPayload(payload) {
  const repo = payload.repository;

  /**
   * @param {string} url repository path
   * @return {string}
   */
  function replace(url) {
    return url.replace(/\.git$/, '.wiki.git');
  }

  if (!repo.private) {
    return replace(repo.clone_url);
  }
  const token = env.get('GITHUB_TOKEN');
  if (token) {
    return replace(`https://${token}:@${repo.clone_url.split('https://')[0]}`);
  }
  return replace(repo.ssh_url);
}
<|endoftext|>


<commit_before>import React from 'react';
import {
    BooleanField,
    BooleanInput,
    CheckboxGroupInput,
    ChipField,
    Create,
    Datagrid,
    DateField,
    DateInput,
    DisabledInput,
    Edit,
    EditButton,
    Filter,
    FormTab,
    ImageField,
    ImageInput,
    List,
    LongTextInput,
    NumberField,
    NumberInput,
    ReferenceArrayField,
    ReferenceManyField,
    ReferenceArrayInput,
    Responsive,
    RichTextField,
    SelectArrayInput,
    SelectField,
    SelectInput,
    Show,
    ShowButton,
    SimpleForm,
    SimpleList,
    SimpleShowLayout,
    SingleFieldList,
    Tab,
    TabbedForm,
    TabbedShowLayout,
    TextField,
    TextInput,
    minValue,
    number,
    required,
    translate,
} from 'admin-on-rest';
import RichTextInput from 'aor-rich-text-input';
import Chip from 'material-ui/Chip';

export PostIcon from 'material-ui/svg-icons/action/book';

const QuickFilter = translate(({ label, translate }) => <Chip style={{ marginBottom: 8 }}>{translate(label)}</Chip>);

const PostFilter = ({ ...props }) => (
    <Filter {...props}>
        <TextInput label="post.list.search" source="q" alwaysOn />
        <TextInput source="title" defaultValue="Qui tempore rerum et voluptates" />
        <QuickFilter label="resources.posts.fields.commentable" source="commentable" defaultValue={true} />
    </Filter>
);

const titleFieldStyle = { maxWidth: '20em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' };
export const PostList = ({ ...props }) => (
    <List {...props} filters={<PostFilter />} sort={{ field: 'published_at', order: 'DESC' }}>
        <Responsive
            small={
                <SimpleList
                    primaryText={record => record.title}
                    secondaryText={record => `${record.views} views`}
                    tertiaryText={record => new Date(record.published_at).toLocaleDateString()}
                />
            }
            medium={
                <Datagrid>
                    <TextField source="id" />
                    <TextField source="title" style={titleFieldStyle} />
                    <DateField source="published_at" style={{ fontStyle: 'italic' }} />
                    <BooleanField source="commentable" label="resources.posts.fields.commentable_short" />
                    <NumberField source="views" />
                    <ReferenceArrayField label="Tags" reference="tags" source="tags">
                        <SingleFieldList>
                            <ChipField source="name" />
                        </SingleFieldList>
                     </ReferenceArrayField>
                    <EditButton />
                    <ShowButton />
                </Datagrid>
            }
        />
    </List>
);

const PostTitle = translate(({ record, translate }) => {
    return {record ? translate('post.edit.title', { title: record.title }) : ''};
});

export const PostCreate = ({ ...props }) => (
    <Create {...props} afterSuccess="show">
        <SimpleForm defaultValue={{ average_note: 0 }} validate={(values) => {
            const errors = {};
            ['title', 'teaser'].forEach((field) => {
                if (!values[field]) {
                    errors[field] = ['Required field'];
                }
            });

            if (values.average_note < 0 || values.average_note > 5) {
                errors.average_note = ['Should be between 0 and 5'];
            }

            return errors;
        }}>
            <TextInput source="title" />
            <TextInput source="password" type="password" />
            <TextInput source="teaser" options={{ multiLine: true }} />
            <RichTextInput source="body" />
            <DateInput source="published_at" defaultValue={() => new Date()} />
            <NumberInput source="average_note" />
            <BooleanInput source="commentable" defaultValue={true} />
        </SimpleForm>
    </Create>
);

export const PostEdit = ({ ...props }) => (
    <Edit title={<PostTitle />} {...props}>
        <TabbedForm defaultValue={{ average_note: 0 }}>
            <FormTab label="post.form.summary">
                <DisabledInput source="id" />
                <TextInput source="title" validate={required} />
                <CheckboxGroupInput
                    source="notifications"
                    choices={[
                        { id: 12, name: 'Ray Hakt' },
                        { id: 31, name: 'Ann Gullar' },
                        { id: 42, name: 'Sean Phonee' },
                    ]}
                />
                <LongTextInput source="teaser" validate={required} />
                <ImageInput multiple source="pictures" accept="image/*">
                    <ImageField source="src" title="title" />
                </ImageInput>
            </FormTab>
            <FormTab label="post.form.body">
                <RichTextInput source="body" label="" validate={required} addLabel={false} />
            </FormTab>
            <FormTab label="post.form.miscellaneous">
                <ReferenceArrayInput source="tags" reference="tags" allowEmpty>
                    <SelectArrayInput optionText="name" options={{ fullWidth: true }} />
                </ReferenceArrayInput>
                <DateInput source="published_at" options={{ locale: 'pt' }} />
                <SelectInput source="category" choices={[
                    { name: 'Tech', id: 'tech' },
                    { name: 'Lifestyle', id: 'lifestyle' },
                ]} />
                <NumberInput source="average_note" validate={[number, minValue(0)]} />
                <BooleanInput source="commentable" defaultValue />
                <DisabledInput source="views" />
            </FormTab>
            <FormTab label="post.form.comments">
                <ReferenceManyField reference="comments" target="post_id" addLabel={false}>
                    <Datagrid>
                        <DateField source="created_at" />
                        <TextField source="author.name" />
                        <TextField source="body" />
                        <EditButton />
                    </Datagrid>
                </ReferenceManyField>
            </FormTab>
        </TabbedForm>
    </Edit>
);

export const PostShow = ({ ...props }) => (
    <Show title={<PostTitle />} {...props}>
        <TabbedShowLayout>
            <Tab label="post.form.summary">
                <TextField source="id" />
                <TextField source="title" />
                <TextField source="teaser" stripTags={false} />
            </Tab>
            <Tab label="post.form.body">
                <RichTextField source="body" label="" addLabel={false} />
            </Tab>
            <Tab label="post.form.miscellaneous">
                <ReferenceArrayField reference="tags" source="tags">
                    <SingleFieldList>
                        <ChipField source="name" />
                    </SingleFieldList>
                </ReferenceArrayField>
                <DateField source="published_at" />
                <TextField source="category" />
                <NumberField source="average_note" validate={[number, minValue(0)]} />
                <BooleanField source="commentable" defaultValue />
                <TextField source="views" />
            </Tab>
            <Tab label="post.form.comments">
                <ReferenceManyField label="resources.posts.fields.comments" reference="comments" target="post_id" sort={{ field: 'created_at', order: 'DESC' }}>
                    <Datagrid selectable={false}>
                        <DateField source="created_at" />
                        <TextField source="author.name" />
                        <TextField source="body" />
                        <EditButton />
                    </Datagrid>
                </ReferenceManyField>
            </Tab>
        </TabbedShowLayout>
    </Show>
);
<commit_msg>example<commit_after>import React from 'react';
import {
    BooleanField,
    BooleanInput,
    CheckboxGroupInput,
    ChipField,
    Create,
    Datagrid,
    DateField,
    DateInput,
    DisabledInput,
    Edit,
    EditButton,
    Filter,
    FormTab,
    ImageField,
    ImageInput,
    List,
    LongTextInput,
    NumberField,
    NumberInput,
    ReferenceArrayField,
    ReferenceManyField,
    ReferenceArrayInput,
    Responsive,
    RichTextField,
    SelectArrayInput,
    SelectField,
    SelectInput,
    Show,
    ShowButton,
    SimpleForm,
    SimpleList,
    SimpleShowLayout,
    SingleFieldList,
    Tab,
    TabbedForm,
    TabbedShowLayout,
    TextField,
    TextInput,
    minValue,
    number,
    required,
    translate,
    SaveButton,
} from 'admin-on-rest';
import RichTextInput from 'aor-rich-text-input';
import Chip from 'material-ui/Chip';
import Toolbar from 'admin-on-rest/mui/form/Toolbar';

export PostIcon from 'material-ui/svg-icons/action/book';

const QuickFilter = translate(({ label, translate }) => <Chip style={{ marginBottom: 8 }}>{translate(label)}</Chip>);

const PostFilter = ({ ...props }) => (
    <Filter {...props}>
        <TextInput label="post.list.search" source="q" alwaysOn />
        <TextInput source="title" defaultValue="Qui tempore rerum et voluptates" />
        <QuickFilter label="resources.posts.fields.commentable" source="commentable" defaultValue={true} />
    </Filter>
);

const titleFieldStyle = { maxWidth: '20em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' };
export const PostList = ({ ...props }) => (
    <List {...props} filters={<PostFilter />} sort={{ field: 'published_at', order: 'DESC' }}>
        <Responsive
            small={
                <SimpleList
                    primaryText={record => record.title}
                    secondaryText={record => `${record.views} views`}
                    tertiaryText={record => new Date(record.published_at).toLocaleDateString()}
                />
            }
            medium={
                <Datagrid>
                    <TextField source="id" />
                    <TextField source="title" style={titleFieldStyle} />
                    <DateField source="published_at" style={{ fontStyle: 'italic' }} />
                    <BooleanField source="commentable" label="resources.posts.fields.commentable_short" />
                    <NumberField source="views" />
                    <ReferenceArrayField label="Tags" reference="tags" source="tags">
                        <SingleFieldList>
                            <ChipField source="name" />
                        </SingleFieldList>
                     </ReferenceArrayField>
                    <EditButton />
                    <ShowButton />
                </Datagrid>
            }
        />
    </List>
);

const PostTitle = translate(({ record, translate }) => {
    return {record ? translate('post.edit.title', { title: record.title }) : ''};
});

const PostCreateToolbar = props => <Toolbar {...props} >
    <SaveButton label="Save and show" redirect="show" />
    <SaveButton />
</Toolbar>;

export const PostCreate = ({ ...props }) => (
    <Create {...props}>
        <SimpleForm toolbar={<PostCreateToolbar />} defaultValue={{ average_note: 0 }} validate={(values) => {
            const errors = {};
            ['title', 'teaser'].forEach((field) => {
                if (!values[field]) {
                    errors[field] = ['Required field'];
                }
            });

            if (values.average_note < 0 || values.average_note > 5) {
                errors.average_note = ['Should be between 0 and 5'];
            }

            return errors;
        }}>
            <TextInput source="title" />
            <TextInput source="password" type="password" />
            <TextInput source="teaser" options={{ multiLine: true }} />
            <RichTextInput source="body" />
            <DateInput source="published_at" defaultValue={() => new Date()} />
            <NumberInput source="average_note" />
            <BooleanInput source="commentable" defaultValue={true} />
        </SimpleForm>
    </Create>
);

export const PostEdit = ({ ...props }) => (
    <Edit title={<PostTitle />} {...props}>
        <TabbedForm defaultValue={{ average_note: 0 }}>
            <FormTab label="post.form.summary">
                <DisabledInput source="id" />
                <TextInput source="title" validate={required} />
                <CheckboxGroupInput
                    source="notifications"
                    choices={[
                        { id: 12, name: 'Ray Hakt' },
                        { id: 31, name: 'Ann Gullar' },
                        { id: 42, name: 'Sean Phonee' },
                    ]}
                />
                <LongTextInput source="teaser" validate={required} />
                <ImageInput multiple source="pictures" accept="image/*">
                    <ImageField source="src" title="title" />
                </ImageInput>
            </FormTab>
            <FormTab label="post.form.body">
                <RichTextInput source="body" label="" validate={required} addLabel={false} />
            </FormTab>
            <FormTab label="post.form.miscellaneous">
                <ReferenceArrayInput source="tags" reference="tags" allowEmpty>
                    <SelectArrayInput optionText="name" options={{ fullWidth: true }} />
                </ReferenceArrayInput>
                <DateInput source="published_at" options={{ locale: 'pt' }} />
                <SelectInput source="category" choices={[
                    { name: 'Tech', id: 'tech' },
                    { name: 'Lifestyle', id: 'lifestyle' },
                ]} />
                <NumberInput source="average_note" validate={[number, minValue(0)]} />
                <BooleanInput source="commentable" defaultValue />
                <DisabledInput source="views" />
            </FormTab>
            <FormTab label="post.form.comments">
                <ReferenceManyField reference="comments" target="post_id" addLabel={false}>
                    <Datagrid>
                        <DateField source="created_at" />
                        <TextField source="author.name" />
                        <TextField source="body" />
                        <EditButton />
                    </Datagrid>
                </ReferenceManyField>
            </FormTab>
        </TabbedForm>
    </Edit>
);

export const PostShow = ({ ...props }) => (
    <Show title={<PostTitle />} {...props}>
        <TabbedShowLayout>
            <Tab label="post.form.summary">
                <TextField source="id" />
                <TextField source="title" />
                <TextField source="teaser" stripTags={false} />
            </Tab>
            <Tab label="post.form.body">
                <RichTextField source="body" label="" addLabel={false} />
            </Tab>
            <Tab label="post.form.miscellaneous">
                <ReferenceArrayField reference="tags" source="tags">
                    <SingleFieldList>
                        <ChipField source="name" />
                    </SingleFieldList>
                </ReferenceArrayField>
                <DateField source="published_at" />
                <TextField source="category" />
                <NumberField source="average_note" validate={[number, minValue(0)]} />
                <BooleanField source="commentable" defaultValue />
                <TextField source="views" />
            </Tab>
            <Tab label="post.form.comments">
                <ReferenceManyField label="resources.posts.fields.comments" reference="comments" target="post_id" sort={{ field: 'created_at', order: 'DESC' }}>
                    <Datagrid selectable={false}>
                        <DateField source="created_at" />
                        <TextField source="author.name" />
                        <TextField source="body" />
                        <EditButton />
                    </Datagrid>
                </ReferenceManyField>
            </Tab>
        </TabbedShowLayout>
    </Show>
);
<|endoftext|>


<commit_before>'use strict';

/*
 * scout moves around to provide visibility
 *
 * Pre observer the scout moves through surrounding rooms
 */

roles.scout = {};
roles.scout.settings = {
  layoutString: 'M',
  maxLayoutAmount: 1,
};

function onBorder(creep) {
  return creep.pos.x === 49 || creep.pos.x === 0 ||
    creep.pos.y === 49 || creep.pos.y === 0;
}

function haveNotSeen(creep, room) {
  return creep.memory.search.seen.indexOf(room) === -1 &&
    creep.memory.skip.indexOf(room) === -1;
}

roles.scout.execute = function(creep) {
  if (creep.memory.skip === undefined) {
    creep.memory.skip = [];
  }
  let breadthFirstSearch = function(creep) {
    let setNewTarget = function(creep) {
      for (let room of creep.memory.search.levels[creep.memory.search.level]) {
        if (haveNotSeen(creep, room)) {
          creep.memory.search.target = room;
          return true;
        }
      }
      return false;
    };
    if (!creep.memory.search) {
      creep.memory.search = {};
      creep.memory.search.seen = [creep.room.name];
      creep.memory.search.level = 1;
      creep.memory.search.levels = [
        [creep.room.name],
        []
      ];
      let rooms = Game.map.describeExits(creep.room.name);
      for (let direction in rooms) {
        creep.memory.search.levels[1].push(rooms[direction]);
        creep.memory.search.target = rooms[direction];
      }
    }

    if (creep.memory.scoutSkip || creep.room.name === creep.memory.search.target) {
      if (creep.memory.scoutSkip) {
        creep.memory.skip.push(creep.memory.search.target);
        delete creep.memory.scoutSkip;
      } else {
        creep.memory.search.seen.push(creep.room.name);
      }
      if (!setNewTarget(creep)) {
        creep.memory.search.levels.push([]);
        for (let room of creep.memory.search.levels[creep.memory.search.level]) {
          let rooms = Game.map.describeExits(room);
          for (let direction in rooms) {
            let roomNext = rooms[direction];
            if (haveNotSeen(creep, roomNext)) {
              creep.memory.search.levels[creep.memory.search.level + 1].push(roomNext);
              creep.memory.search.target = roomNext;
            }
          }
        }
        creep.memory.search.level++;
      }
    }

    if (!creep.memory.search.target) {
      creep.log('Suiciding: ' + JSON.stringify(creep.memory.search));
      creep.suicide();
      return true;
    }
    let targetPosObject = new RoomPosition(25, 25, creep.memory.search.target);

    let search;

    try {
      search = PathFinder.search(
        creep.pos, {
          pos: targetPosObject,
          range: 20
        }, {
          roomCallback: creep.room.getCostMatrixCallback(targetPosObject, true, false, true)
        }
      );

    } catch (e) {
      if (e !== null) {
        creep.log(`search: ${targetPosObject} ${e} ${e.stack}`);
      } else {
        creep.log(`search: ${targetPosObject} ${e}`);
      }
      // creep.memory.search.seen.push(creep.memory.search.target);
      // // TODO extract to a method
      // if (!setNewTarget(creep)) {
      //   creep.memory.search.levels.push([]);
      //   for (let room of creep.memory.search.levels[creep.memory.search.level]) {
      //     let rooms = Game.map.describeExits(room);
      //     for (let direction in rooms) {
      //       let roomNext = rooms[direction];
      //       if (haveNotSeen(creep, roomNext)) {
      //         creep.memory.search.levels[creep.memory.search.level + 1].push(roomNext);
      //         creep.memory.search.target = roomNext;
      //       }
      //     }
      //   }
      //   creep.memory.search.level++;
      // }
      return false;
    }

    if (creep.pos.roomName !== creep.memory.last.pos3.roomName) {
      creep.moveTo(25, 25);
      return true;
    }

    if (creep.isStuck()) {
      creep.moveRandom();
      creep.say('ImStuck', true);
      creep.log('Scout Stuck, Randomly Moving: ' + JSON.stringify(creep.memory.last) + ' ' + JSON.stringify(creep.isStuck()));
      return true;
    }

    if (search.path.length === 0 || (creep.inBase() && creep.room.memory.misplacedSpawn)) {
      creep.say('hello', true);
      //       creep.log(creep.pos + ' ' + targetPosObject + ' ' + JSON.stringify(search));
      if (creep.isStuck() && onBorder(creep)) {
        creep.say('imstuck at the border', true);
        if (config.room.scoutSkipWhenStuck) {
          creep.say('skipping', true);
          creep.memory.scoutSkip = true;
          delete creep.memory.last; // Delete to reset stuckness.
        }
      }
      //if (search.path.length > 0) {
      //creep.move(creep.pos.getDirectionTo(search.path[0]));
      //} else {
      let returnCode = creep.moveTo(targetPosObject, {
        ignoreCreeps: true,
        costCallback: creep.room.getCostMatrixCallback()
      });
      //}
      return true;
    }
    creep.say(creep.pos.getDirectionTo(search.path[0]));
    let returnCode = creep.move(creep.pos.getDirectionTo(search.path[0]));
  };

  creep.notifyWhenAttacked(false);
  return breadthFirstSearch(creep);
};
<commit_msg>fix scout<commit_after>'use strict';

/*
 * scout moves around to provide visibility
 *
 * Pre observer the scout moves through surrounding rooms
 */

roles.scout = {};
roles.scout.settings = {
  layoutString: 'M',
  maxLayoutAmount: 1,
};

function onBorder(creep) {
  return creep.pos.x === 49 || creep.pos.x === 0 ||
    creep.pos.y === 49 || creep.pos.y === 0;
}

function haveNotSeen(creep, room) {
  return creep.memory.search.seen.indexOf(room) === -1 &&
    creep.memory.skip.indexOf(room) === -1;
}

roles.scout.execute = function(creep) {
  if (creep.memory.skip === undefined) {
    creep.memory.skip = [];
  }
  let breadthFirstSearch = function(creep) {
    let setNewTarget = function(creep) {
      for (let room of creep.memory.search.levels[creep.memory.search.level]) {
        if (haveNotSeen(creep, room)) {
          creep.memory.search.target = room;
          return true;
        }
      }
      return false;
    };
    if (!creep.memory.search) {
      creep.memory.search = {};
      creep.memory.search.seen = [creep.room.name];
      creep.memory.search.level = 1;
      creep.memory.search.levels = [
        [creep.room.name],
        []
      ];
      let rooms = Game.map.describeExits(creep.room.name);
      for (let direction in rooms) {
        creep.memory.search.levels[1].push(rooms[direction]);
        creep.memory.search.target = rooms[direction];
      }
    }

    if (creep.memory.scoutSkip || creep.room.name === creep.memory.search.target) {
      if (creep.memory.scoutSkip) {
        creep.memory.skip.push(creep.memory.search.target);
        delete creep.memory.scoutSkip;
      } else {
        creep.memory.search.seen.push(creep.room.name);
      }
      if (!setNewTarget(creep)) {
        creep.memory.search.levels.push([]);
        for (let room of creep.memory.search.levels[creep.memory.search.level]) {
          let rooms = Game.map.describeExits(room);
          for (let direction in rooms) {
            let roomNext = rooms[direction];
            if (haveNotSeen(creep, roomNext)) {
              creep.memory.search.levels[creep.memory.search.level + 1].push(roomNext);
              creep.memory.search.target = roomNext;
            }
          }
        }
        creep.memory.search.level++;
      }
    }

    if (!creep.memory.search.target) {
      creep.log('Suiciding: ' + JSON.stringify(creep.memory.search));
      creep.suicide();
      return true;
    }
    let targetPosObject = new RoomPosition(25, 25, creep.memory.search.target);

    let search;

    try {
      search = PathFinder.search(
        creep.pos, {
          pos: targetPosObject,
          range: 20
        }, {
          roomCallback: creep.room.getCostMatrixCallback(targetPosObject, true, false, true)
        }
      );

    } catch (e) {
      if (e !== null) {
        creep.log(`search: ${targetPosObject} ${e} ${e.stack}`);
      } else {
        creep.log(`search: ${targetPosObject} ${e}`);
      }
      // creep.memory.search.seen.push(creep.memory.search.target);
      // // TODO extract to a method
      // if (!setNewTarget(creep)) {
      //   creep.memory.search.levels.push([]);
      //   for (let room of creep.memory.search.levels[creep.memory.search.level]) {
      //     let rooms = Game.map.describeExits(room);
      //     for (let direction in rooms) {
      //       let roomNext = rooms[direction];
      //       if (haveNotSeen(creep, roomNext)) {
      //         creep.memory.search.levels[creep.memory.search.level + 1].push(roomNext);
      //         creep.memory.search.target = roomNext;
      //       }
      //     }
      //   }
      //   creep.memory.search.level++;
      // }
      return false;
    }

    if (creep.memory.last && creep.memory.last.pos3 && creep.pos.roomName !== creep.memory.last.pos3.roomName) {
      creep.moveTo(25, 25);
      return true;
    }

    if (creep.isStuck()) {
      creep.moveRandom();
      creep.say('ImStuck', true);
      creep.log('Scout Stuck, Randomly Moving: ' + JSON.stringify(creep.memory.last) + ' ' + JSON.stringify(creep.isStuck()));
      return true;
    }

    if (search.path.length === 0 || (creep.inBase() && creep.room.memory.misplacedSpawn)) {
      creep.say('hello', true);
      //       creep.log(creep.pos + ' ' + targetPosObject + ' ' + JSON.stringify(search));
      if (creep.isStuck() && onBorder(creep)) {
        creep.say('imstuck at the border', true);
        if (config.room.scoutSkipWhenStuck) {
          creep.say('skipping', true);
          creep.memory.scoutSkip = true;
          delete creep.memory.last; // Delete to reset stuckness.
        }
      }
      //if (search.path.length > 0) {
      //creep.move(creep.pos.getDirectionTo(search.path[0]));
      //} else {
      let returnCode = creep.moveTo(targetPosObject, {
        ignoreCreeps: true,
        costCallback: creep.room.getCostMatrixCallback()
      });
      //}
      return true;
    }
    creep.say(creep.pos.getDirectionTo(search.path[0]));
    let returnCode = creep.move(creep.pos.getDirectionTo(search.path[0]));
  };

  creep.notifyWhenAttacked(false);
  return breadthFirstSearch(creep);
};
<|endoftext|>


<commit_before>var Parsimmon = require('./../index');
var string = Parsimmon.string;
var regex = Parsimmon.regex;
var succeed = Parsimmon.succeed;

var json = (function() {
  var escapes = {
    b: '\b',
    f: '\f',
    n: '\n',
    r: '\r',
    t: '\t'
  }

  var stringLiteral = regex(/^"(\\.|.)*?"/).map(function(str) {
    return str.slice(1, -1).replace(/\\u(\d{4})/, function(_, hex) {
      return String.fromCharCode(parseInt(hex, 16));
    }).replace(/\\(.)/, function(_, ch) {
      return escapes.hasOwnProperty(ch) ? escapes[ch] : ch
    });
  });

  var numberLiteral = regex(/^\d+(([.]|e[+-]?)\d+)?/i).map(parseFloat)

  function commaSep(parser) {
    return parser.then(function(x) {
      return regex(/^,\s*/m).then(parser).many().map(function(xs) {
        return [x].concat(xs);
      });
    }).or(succeed([]));
  }

  var array = regex(/^\[\s*/m).then(function() {
    return commaSep(json).skip(string(']'));
  });

  var pair = stringLiteral.then(function(key) {
    return regex(/^\s*:\s*/m).then(json).map(function(res) { return [key, res]; });
  });

  var object = regex(/^[{]\s*/m).then(commaSep(pair)).skip(string('}'))
    .map(function(pairs) {
      var out = {};
      for (var i = pairs.length-1; i >= 0; i -= 1) {
        out[pairs[i][0]] = pairs[i][1]
      }
      return out;
    });

  var nullLiteral = string('null').result(null);
  var trueLiteral = string('true').result(true);
  var falseLiteral = string('false').result(false);

  var json = object
    .or(array)
    .or(stringLiteral)
    .or(numberLiteral)
    .or(nullLiteral)
    .or(trueLiteral)
    .or(falseLiteral)
    .skip(regex(/^\s*/m));

  return json;
})();

console.log(json.parse(require('fs').readFileSync(__dirname+'/../package.json', 'utf-8')));
<commit_msg>json example: parse the file given as an argument<commit_after>var Parsimmon = require('./../index');
var string = Parsimmon.string;
var regex = Parsimmon.regex;
var succeed = Parsimmon.succeed;

var json = (function() {
  var escapes = {
    b: '\b',
    f: '\f',
    n: '\n',
    r: '\r',
    t: '\t'
  }

  var stringLiteral = regex(/^"(\\.|.)*?"/).map(function(str) {
    return str.slice(1, -1).replace(/\\u(\d{4})/, function(_, hex) {
      return String.fromCharCode(parseInt(hex, 16));
    }).replace(/\\(.)/, function(_, ch) {
      return escapes.hasOwnProperty(ch) ? escapes[ch] : ch
    });
  });

  var numberLiteral = regex(/^\d+(([.]|e[+-]?)\d+)?/i).map(parseFloat)

  function commaSep(parser) {
    return parser.then(function(x) {
      return regex(/^,\s*/m).then(parser).many().map(function(xs) {
        return [x].concat(xs);
      });
    }).or(succeed([]));
  }

  var array = regex(/^\[\s*/m).then(function() {
    return commaSep(json).skip(string(']'));
  });

  var pair = stringLiteral.then(function(key) {
    return regex(/^\s*:\s*/m).then(json).map(function(res) { return [key, res]; });
  });

  var object = regex(/^[{]\s*/m).then(commaSep(pair)).skip(string('}'))
    .map(function(pairs) {
      var out = {};
      for (var i = pairs.length-1; i >= 0; i -= 1) {
        out[pairs[i][0]] = pairs[i][1]
      }
      return out;
    });

  var nullLiteral = string('null').result(null);
  var trueLiteral = string('true').result(true);
  var falseLiteral = string('false').result(false);

  var json = object
    .or(array)
    .or(stringLiteral)
    .or(numberLiteral)
    .or(nullLiteral)
    .or(trueLiteral)
    .or(falseLiteral)
    .skip(regex(/^\s*/m));

  return json;
})();

var source = process.argv[2] || __dirname+'/../package.json';
var result = json.parse(require('fs').readFileSync(source, 'utf-8'));

console.log(result);
<|endoftext|>


<commit_before>function regex_del( key, regex_pattern ) {

}<commit_msg>Delete keys.js<commit_after><|endoftext|>


<commit_before>let router = require('express').Router;
let users = require('./users');
let authentication = require('./authentication');
let frontEndLogRoutes = require('./frontEndLog');
let groupRoutes = require('./groups');
let creditCards = require('./creditCards');

let routes = router();

// non authenticated routes
routes.use('/users/authenticate', authentication.routes);
routes.use('/log', frontEndLogRoutes);
routes.use('/users', users.userUnauthenticatedRoutes);

// authenticated routes
routes.use(authentication.authenticationGuard);
routes.use('/users', users.userAuthenticatedRoutes);
routes.use('/credit-cards', creditCards.creditCardAuthenticatedRoutes);

// admin routes
routes.use(authentication.adminGuard);
routes.use('/users', users.userAdminRoutes);
routes.use('/groups', groupRoutes);
routes.use('/credit-cards', creditCards.creditCardAdminRoutes);

module.exports = routes;<commit_msg>Modify authenticate route<commit_after>let router = require('express').Router;
let users = require('./users');
let authentication = require('./authentication');
let frontEndLogRoutes = require('./frontEndLog');
let groupRoutes = require('./groups');
let creditCards = require('./creditCards');

let routes = router();

// non authenticated routes
routes.use('/authenticate', authentication.routes);
routes.use('/log', frontEndLogRoutes);
routes.use('/users', users.userUnauthenticatedRoutes);

// authenticated routes
routes.use(authentication.authenticationGuard);
routes.use('/users', users.userAuthenticatedRoutes);
routes.use('/credit-cards', creditCards.creditCardAuthenticatedRoutes);

// admin routes
routes.use(authentication.adminGuard);
routes.use('/users', users.userAdminRoutes);
routes.use('/groups', groupRoutes);
routes.use('/credit-cards', creditCards.creditCardAdminRoutes);

module.exports = routes;<|endoftext|>


<commit_before>/*global define:true requirejs:true*/
/* jshint strict: false */
requirejs.config({
    paths: {
        'jquery': 'jquery/jquery',
        'gpaginate': 'gpaginate'
    }
});

define(['gpaginate', 'jquery'], function (GPaginate, $) {
    console.log('Loading');
	var gpaginate = new GPaginate();
	gpaginate.init();
});<commit_msg>EXAMPLE: Updating example<commit_after>/*global define:true requirejs:true*/
/* jshint strict: false */
requirejs.config({
    paths: {
        'gpaginate': 'gpaginate',
        'extend': 'gextend/extend'
    }
});

define(['gpaginate'], function(GPaginate) {
    console.log('Loading');
    var pager = new GPaginate({
        data: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        pageSize: 5
    });

    console.log(pager.page())
    console.log(pager.next())
    console.log(pager.next())
});<|endoftext|>


<commit_before>/* jshint ignore:start */
// jscs: disable

'use strict';

var car = {
  start: function (afterStartCallback) {
    // Dispatch `start` event.
    this.dispatchEvent({type: 'start', message: 'Start engines'});
    afterStartCallback && afterStartCallback(this);
  },
  stop: function () {
    // Dispatch `stop` event.
    this.dispatchEvent({type: 'stop', message: 'Stop engines'});
  }
};

function startEngines(event) {
  console.log(event.message);
}

function stopEngines(event) {
  console.log(event.message);
}

// Apply `eventDispatcher` methods to the prototype of the event target.
eventDispatcher.apply(Object.getPrototypeOf(car));

// Register event listeners to event target.
car
  .addEventListener('start', startEngines)
  .addEventListener('afterStart', startEngines)
  .addEventListener('stop', stopEngines);

// `start` event fires first, then `afterStart` and finally
// after two seconds `stop` events fires.

car.start(function (self) {
  // Dispatch `afterStart` event.
  self.dispatchEvent({type: 'afterStart', message: 'Car has started'});
});

console.log(car.hasEventListener('start', startEngines));      // -> true
console.log(car.hasEventListener('afterStart', startEngines)); // -> true
console.log(car.hasEventListener('stop', startEngines));       // -> false
console.log(car.hasEventListener('stop', stopEngines));        // -> true

setTimeout(function () {
  car.stop();

  // Remove all event listeners from event target.
  car
    .removeEventListener('start', startEngines)
    .removeEventListener('afterStart', startEngines)
    .removeEventListener('stop', stopEngines);
}, 2000);
<commit_msg>update example<commit_after>/* eslint-disable no-console */

(function () {
  'use strict';

  var car = {
    start: function (afterStartCallback) {
      // Dispatch `start` event.
      this.dispatchEvent({type: 'start', message: 'Start engines'});
      afterStartCallback && afterStartCallback(this);
    },
    stop: function () {
      // Dispatch `stop` event.
      this.dispatchEvent({type: 'stop', message: 'Stop engines'});
    }
  };

  function startEngines(event) {
    console.log(event.message);
  }

  function stopEngines(event) {
    console.log(event.message);
  }

  // Apply `eventDispatcher` methods to the prototype of the event target.
  eventDispatcher.apply(Object.getPrototypeOf(car));

  // Register event listeners to event target.
  car
    .addEventListener('start', startEngines)
    .addEventListener('afterStart', startEngines)
    .addEventListener('stop', stopEngines);

  // `start` event fires first, then `afterStart` and finally
  // after two seconds `stop` events fires.

  car.start(function (self) {
    // Dispatch `afterStart` event.
    self.dispatchEvent({type: 'afterStart', message: 'Car has started'});
  });

  console.log(car.hasEventListener('start', startEngines));      // -> true
  console.log(car.hasEventListener('afterStart', startEngines)); // -> true
  console.log(car.hasEventListener('stop', startEngines));       // -> false
  console.log(car.hasEventListener('stop', stopEngines));        // -> true

  setTimeout(function () {
    car.stop();

    // Remove all event listeners from event target.
    car
      .removeEventListener('start', startEngines)
      .removeEventListener('afterStart', startEngines)
      .removeEventListener('stop', stopEngines);
  }, 2000);
}());
<|endoftext|>