text:
import olexpControl from './control';
import olexpManager from './manager';
import olexpMenu from './menu';
import olexpSelection from './selection';
import olexpUtil from './util';

/* globals $, ol */

/**
 * @namespace olexp
 */
const olexp = {
  control: olexpControl,
  manager: olexpManager,
  menu: olexpMenu,
  selection: olexpSelection,
  util: olexpUtil,
};

// ==================================================
// Documentation definitions
// --------------------------------------------------

/**
 * jQuery
 * @external jQuery
 * @see {@link https://api.jquery.com}
 */

/**
 * jQuery plugin namespace
 * @memberof external:jQuery
 * @namespace fn
 */

/**
 * ol3 main namespace
 * @external ol
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_html}
 */

/**
 * ol3 Collection
 * @class Collection
 * @memberof external:ol
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_Collection.html}
 */

/**
 * ol3 format namespace
 * @memberof external:ol
 * @namespace format
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_format.html}
 */

/**
 * ol3 Feature
 * @class Feature
 * @memberof external:ol
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_Feature.html}
 */

/**
 * ol3 format feature
 * @class Feature
 * @memberof external:ol.format
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_format_Feature.html}
 */

/**
 * ol3 graticule
 * @class Graticule
 * @memberof external:ol
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_Graticule.html}
 */

/**
 * ol3 interaction namespace
 * @memberof external:ol
 * @namespace interaction
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_interaction.html}
 */

/**
 * ol3 selection interaction
 * @class Select
 * @memberof external:ol.interaction
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_interaction_Select.html}
 */

/**
 * ol3 layer namespace
 * @memberof external:ol
 * @namespace layer
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_layer.html}
 */

/**
 * ol3 layer base class
 * @class Layer
 * @memberof external:ol.layer
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_layer_Layer.html}
 */

/**
 * ol3 map
 * @class Map
 * @memberof external:ol
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_Map.html}
 */

/**
 * ol3 overlay
 * @class Overlay
 * @memberof external:ol
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_Overlay.html}
 */

/**
 * ol3 style namespace
 * @memberof external:ol
 * @namespace style
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_style.html}
 */

/**
 * ol3 Style
 * @class Style
 * @memberof external:ol.style
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_style_Style.html}
 */

/**
 * ol3 view
 * @class View
 * @memberof external:ol
 * @see {@link http://openlayers.org/en/v5.3.0/apidoc/module-ol_View.html}
 */

/**
 * w2ui form
 * @function w2form
 * @memberof external:jQuery.fn
 * @see {@link http://w2ui.com/web/docs/form}
 */

/**
 * w2ui form properties
 * @memberof external:jQuery.fn.w2form
 * @name properties
 * @type object
 * @see {@link http://w2ui.com/web/docs/form/properties}
 */

/**
 * w2ui grid
 * @function w2grid
 * @memberof external:jQuery.fn
 * @see {@link http://w2ui.com/web/docs/grid}
 */

/**
 * w2ui layout
 * @function w2layout
 * @memberof external:jQuery.fn
 * @see {@link http://w2ui.com/web/docs/layout}
 */

/**
 * w2ui layout panels
 * @memberof external:jQuery.fn.w2layout
 * @name panels
 * @type object
 * @see {@link http://w2ui.com/web/docs/w2layout.panels}
 */

/**
 * w2ui popup
 * @function w2popup
 * @memberof external:jQuery.fn
 * @see {@link http://w2ui.com/web/docs/popup}
 */

/**
 * w2ui popup properties
 * @memberof external:jQuery.fn.w2popup
 * @name properties
 * @type object
 * @see {@link http://w2ui.com/web/docs/w2popup.defaults}
 */

/**
 * w2ui sidebar
 * @function w2sidebar
 * @memberof external:jQuery.fn
 * @see {@link http://w2ui.com/web/docs/sidebar}
 */

/**
 * w2ui sidebar nodes
 * @memberof external:jQuery.fn.w2sidebar
 * @name nodes
 * @type object
 * @see {@link http://w2ui.com/web/docs/w2sidebar.nodes}
 */

/**
 * w2ui toolbar
 * @function w2toolbar
 * @memberof external:jQuery.fn
 * @see {@link http://w2ui.com/web/docs/toolbar}
 */

/**
 * w2ui toolbar properties
 * @memberof external:jQuery.fn.w2toolbar
 * @name properties
 * @type object
 * @see {@link http://w2ui.com/web/docs/w2toolbar.items}
 */

/**
 * w2ui common name
 * @external w2ui.common.name
 * @ignore
 * @see {@link http://w2ui.com/web/docs/common.name}
 */

/**
 * @description Advanced settings for customizing various controls and menus
 *              look and feel.
 * @typedef {object} ExplorerSettings
 * @memberOf olexp
 *
 * @property {object} [control] olexp.control settings
 *
 * @property {object} [control.EditSettings] Edit Settings control settings
 * @property {external:jQuery.fn.w2form.properties} [control.EditSettings.form]
 *           w2form properties
 * @property {string} [control.EditSettings.hint='Edit Controls'] Control button
 *           hover hint text
 * @property {external:jQuery.fn.w2popup.properties}
 *           [control.EditSettings.popup] w2popup properties
 * @property {number} [control.EditSettings.span=6] Span size of control fields
 *
 * @property {object} [control.ExportMap] Export Map control settings
 * @property {string} [control.ExportMap.filename='map.png'] Default filename of
 *           saved map
 * @property {string} [control.ExportMap.hint='Export map'] Control button hover
 *           hint text
 *
 * @property {object} [control.Graticule] Graticule control settings
 * @property {boolean} [control.Graticule.enable=false] Enable grid line display
 * @property {external:jQuery.fn.w2form.properties} [control.Graticule.form]
 *           w2form properties
 * @property {string} [control.Graticule.hint='Edit Controls'] Control button
 *           hover hint text
 * @property {object} [control.Graticule.options] ol.style.Stroke options
 * @property {external:jQuery.fn.w2popup.properties} [control.Graticule.popup]
 *           w2popup properties
 * @property {number} [control.Graticule.span=6] Span size of control fields
 *
 * @property {object} [control.LayerControlTile] Layer Control Tile control
 *           settings
 * @property {external:jQuery.fn.w2form.properties}
 *           [control.LayerControlTile.form] w2form properties
 * @property {string} [control.LayerControlTile.hint='Edit Controls'] Control
 *           button hover hint text
 * @property {external:jQuery.fn.w2popup.properties}
 *           [control.LayerControlTile.popup] w2popup properties
 * @property {number} [control.LayerControlTile.span=6] Span size of control
 *           fields
 *
 * @property {object} [control.LayerControlVector] Layer Control Vector control
 *           settings
 * @property {external:jQuery.fn.w2form.properties}
 *           [control.LayerControlVector.form] w2form properties
 * @property {string} [control.LayerControlVector.hint='Edit Controls'] Control
 *           button hover hint text
 * @property {external:jQuery.fn.w2popup.properties}
 *           [control.LayerControlVector.popup] w2popup properties
 * @property {number} [control.LayerControlVector.span=6] Span size of control
 *           fields
 *
 * @property {object} [control.LayerManager] Layer Manager control settings
 * @property {string} [control.LayerManager.hintDetailsHide='Hide details'] Hide
 *           details control button hover hint text
 * @property {string} [control.LayerManager.hintDetailsShow='Show details'] Show
 *           details control button hover hint text
 * @property {string} [control.LayerManager.hintMoveDown='Move item down'] Move
 *           item down control button hover hint text
 * @property {string} [control.LayerManager.hintMoveUp='Move item up'] Move item
 *           up control button hover hint text
 * @property {string} [control.LayerManager.hintOutlineHide='Hide outline'] Hide
 *           outline control button hover hint text
 * @property {string} [control.LayerManager.hintOutlineShow='Show outline'] Show
 *           outline control button hover hint text
 *
 * @property {object} [control.LayerMenu] Layer Menu control settings
 * @property {string} [control.LayerMenu.arrow=true] Display arrow for drop down
 *           menu
 * @property {string} [control.LayerMenu.hint='Item Properties'] Control button
 *           hover hint text
 * @property {string} [control.LayerMenu.text=''] Button text
 *
 * @property {object} [control.Measurement] Measurement control settings
 * @property {string} [control.Measurement.hintArea='Measure area'] Area
 *           measurement control button hover hint text
 * @property {string} [control.Measurement.hintLength='Measure length'] Length
 *           measurement control button hover hint text
 *
 * @property {object} [control.ToolbarHide] Toolbar Hide control settings
 * @property {string} [control.ToolbarHide.hint='Hide toolbar'] Hide toolbar
 *           control button hover hint text
 *
 * @property {object} [measure] olexp.measure settings
 *
 * @property {object} [measure.Tool] Properties menu settings
 * @property {string}
 *           [measure.Tool.continueLineMsg='Click to continue drawing the line']
 *           Message displayed to continue drawing line
 * @property {string}
 *           [measure.Tool.continuePolygonMsg='Click to continue drawing']
 *           Message displayed to continue drawing polygon
 * @property {Array} [measure.Tool.helpTooltipOffset=[20, 0]] Pixel offset of
 *           help tooltip
 * @property {string} [measure.Tool.helpTooltipPositioning='center-left']
 *           Position of help tooltip
 * @property {external:ol.style.Style} [measure.Tool.measuredStyle] Style of a
 *           measurement vector after completed.
 * @property {external:ol.style.Style} [measure.Tool.measuredStyle] Style of a
 *           measurement vector during drawing.
 * @property {Array} [measure.Tool.measureTooltipOffset=[0, -20]] Pixel offset
 *           of measuring tooltip
 * @property {string} [measure.Tool.measureTooltipPositioning='bottom-center']
 *           Position of measuring tooltip
 * @property {string}
 *           [measure.Tool.messageStart='Click to start. Double click to stop.']
 *           Message to display to start drawing.
 *
 * @property {object} [menu] olexp.menu settings
 *
 * @property {object} [menu.Properties] Properties menu settings
 * @property {number} [menu.Properties.field=35] Field size
 * @property {external:jQuery.fn.w2form.properties} [menu.Properties.form]
 *           w2form properties
 * @property {external:jQuery.fn.w2popup.properties} [menu.Properties.popup]
 *           w2popup properties
 * @property {number} [menu.Properties.span=4] Span size of control fields
 * @property {string} [menu.Properties.text='Properties'] Context menu text
 *
 * @property {object} [menu.Remove] Remove menu settings
 * @property {string} [menu.Remove.text='Remove'] Context menu text
 *
 * @property {object} [menu.Zoom] Zoom menu settings
 * @property {string} [menu.Zoom.text='Zoom'] Context menu text
 *
 * @property {object} [ol] olexp.ol settings
 *
 * @property {object} [ol.ToolbarShow] ol3 map control settings
 * @property {string} [ol.ToolbarShow.html='T'] HTML to display in control
 * @property {string} [ol.ToolbarShow.title='Show toolbar'] Control hover hint
 *
 * @property {object} [util] olexp.util settings
 *
 * @property {function} [util.cluster] Function that returns ol.style.Style for
 *           a given cluster size.
 * @property {external:ol.style.Style} [util.Point] Point style
 * @property {external:ol.style.Style} [util.LineString] LineString style
 * @property {external:ol.style.Style} [util.Polygon] Polygon style
 * @property {external:ol.style.Style} [util.MultiPoint] MultiPoint style
 * @property {external:ol.style.Style} [util.MultiLineString] MultiLineString
 *           style
 * @property {external:ol.style.Style} [util.MultiPolygon] MultiPolygon style
 */

// ==================================================
// OpenLayers Explorer
// --------------------------------------------------
/**
 * olexp main module
 */
((olexp) => {
  /**
   * Main OpenLayers Explorer object that provides a layout manager to an
   * Open Layers 3 map.
   * @param {string} id DOM id of the element containing the Explorer.
   * @param {olexp.ExplorerOptions} [options] Explorer options
   * @throws {Error} id must be defined and exist
   */
  const Explorer = function(id, options) {
    // ==================================================
    // Parse arguments
    // --------------------------------------------------

    if (id === undefined) {
      throw new Error('olexp.Explorer: id not defined');
    }
    if ($('#' + id).length === 0) {
      throw new Error('olexp.Explorer: id not found');
    }

    // ==================================================
    // Default options
    // --------------------------------------------------

    // Prefix is used to create DOM ids and w2ui names. This ensures they
    // are unique and can have multiple instances on the same page
    const prefix = 'olexp-' + id;

    /**
     * @description Explorer constructor options to override default
     *              behavior.
     * @typedef {object} ExplorerOptions
     * @memberOf olexp
     *
     * @property {object} [controls] Enables built-in toolbar controls
     * @property {boolean} [controls.editsettings=true] Enable settings
     *           editor control
     * @property {boolean} [controls.exportmap=true] Enable map exporting
     *           control
     * @property {boolean} [controls.graticule=true] Enable graticule
     *           control
     * @property {boolean} [controls.layercontrol=true] Enable Layer Control
     *           control
     * @property {boolean} [controls.layermanager=true] Enable Layer Manager
     *           control
     * @property {boolean} [controls.layermenu=true] Enable Layer Menu
     *           control
     * @property {boolean} [controls.measure=true] Enable measurement
     *           control
     * @property {boolean} [controls.toolbarhide=true] Enable toolbar hide
     *           control
     *
     * @property {external:jQuery.fn.w2layout.panels} [details] Options for
     *           details panel. Below are only those different from w2ui
     *           defaults.
     * @property {boolean} [details.hidden=true] Visibility
     * @property {boolean} [details.resizable=true] Resizability
     * @property {string} [details.size='25%'] Size
     * @property {string} [details.type='preview'] Type of panel
     *
     * @property {external:jQuery.fn.w2sidebar.nodes} [layers] Options for
     *           layers node. Below are only those different from w2ui defaults.
     * @property {boolean} [layers.expanded=true] Indicate if initially
     *           expanded
     * @property {boolean} [layers.group=true] Indicate if a group
     * @property {string} [layers.img='icon-folder'] CSS selector of node
     *           image
     * @property {string} [layers.text='Layers'] Node text
     *
     * @property {external:jQuery.fn.w2layout.panels} [map] Options for map
     *           panel. Below are only those different from w2ui defaults.
     * @property {string} [map.type='main'] Type of panel
     *
     * @property {external:jQuery.fn.w2layout.panels} [navigation] Options
     *           for navigation panel. Below are only those different from
     *           w2ui defaults.
     * @property {boolean} [navigation.resizable=true] Resizability
     * @property {string} [navigation.size='15%'] Size
     * @property {string} [navigation.type='left'] Type of panel
     *
     * @property {object} [olcontrols] Enables OpenLayers map controls
     * @property {boolean} [olcontrols.fullscreen=true] Enable full screen
     * @property {boolean} [olcontrols.mouseposition=true] Enable mouse position
     * @property {boolean} [olcontrols.overviewmap=true] Enable overview map
     * @property {boolean} [olcontrols.rotate=true] Enable rotation
     * @property {boolean} [olcontrols.scaleline=true] Enable scale line
     * @property {boolean} [olcontrols.zoom=true] Enable zoom
     * @property {boolean} [olcontrols.zoomslider=true] Enable zoom slider
     * @property {boolean} [olcontrols.zoomtoextent=true] Enable zoom to extent
     *
     * @property {object} [olinteractions] Enables OpenLayers map interactions
     * @property {boolean} [olinteractions.draganddrop=true] Enable drag-n-drop
     *
     * @property {external:ol.Map} [olmap] Options for ol3 map.
     *           Below are only those different from ol3 defaults.
     * @property {array} [olmap.controls=[]] Controls initially added to the
     *           map.
     * @property {external:ol.View | undefined}
     *           [olmap.view=new ol.View({center: [0,0], zoom: 4})]
     *           The map's initial view.
     *
     * @property {external:jQuery.fn.w2layout.panels} [outline] Options for
     *           outline panel. Below are only those different from w2ui
     *           defaults.
     * @property {string} [outline.type='main'] Type of panel
     *
     * @property {external:jQuery.fn.w2sidebar.nodes} [overlays] Options for
     *           overlays node. Below are only those different from w2ui
     *           defaults.
     * @property {boolean} [overlays.expanded=true] Indicate if initially
     *           expanded
     * @property {boolean} [overlays.group=true] Indicate if a group
     * @property {string} [overlays.img='icon-folder'] CSS selector of node
     *           image
     * @property {string} [overlays.text='Overlays'] Node text
     *
     * @property {olexp.ExplorerSettings} [settings] Advanced settings for
     *           customizing various controls and menus look and feel.
     *
     * @property {external:jQuery.fn.w2layout.panels} [toolbar] Options for
     *           toolbar panel. Below are only those different from w2ui
     *           defaults.
     * @property {string} [toolbar.size='40'] Size
     * @property {string} [toolbar.style='padding: 5px;'] Additional CSS
     *           style
     * @property {string} [toolbar.type='top'] Type of panel
     */
    this.options = {
      controls: {
        editsettings: true,
        exportmap: true,
        graticule: true,
        layercontrol: true,
        layermanager: true,
        layermenu: true,
        measure: true,
        toolbarhide: true,
      },
      details: {
        hidden: true,
        resizable: true,
        size: '25%',
        type: 'preview',
      },
      layers: {
        expanded: true,
        group: true,
        img: 'icon-folder',
        text: 'Layers',
      },
      map: {
        type: 'main',
      },
      navigation: {
        resizable: true,
        size: '15%',
        type: 'left',
      },
      olcontrols: {
        fullscreen: true,
        mouseposition: true,
        overviewmap: true,
        rotate: true,
        scaleline: true,
        zoom: true,
        zoomslider: true,
        zoomtoextent: true,
      },
      olinteractions: {
        draganddrop: true,
      },
      olmap: {
        controls: [],
        view: new ol.View({center: [0, 0], zoom: 3}),
      },
      outline: {
        type: 'main',
      },
      overlays: {
        expanded: true,
        group: true,
        img: 'icon-folder',
        text: 'Overlays',
      },
      settings: {},
      toolbar: {
        size: '40',
        style: 'padding: 5px;',
        type: 'top',
      },
    };

    // Override default options with user options
    $.extend(true, this.options, options);

    /**
     * @description Explorer options the user can not override (DOM ids and
     *              w2ui names)
     * @memberOf olexp
     *
     * @property {object} [explorer] Explorer properties
     * @property {string} [explorer.cls='olexp-explorer-content'] Explorer
     *           div class
     * @property {string} [explorer.id='olexp-' + id +
     *           '-explorer-id-content'] Explorer div id
     * @property {external:w2ui.common.name} [explorer.details='olexp-' + id
     *           + '-explorer-name-details'] w2ui name of details panel
     * @property {external:w2ui.common.name} [explorer.layout='olexp-' + id
     *           + '-explorer-name-layout'] w2ui name of main layout
     * @property {external:w2ui.common.name} [explorer.navigation='olexp-'
     *           + id + '-explorer-name-navigation'] w2ui name of navigation
     *           panel
     * @property {external:w2ui.common.name} [explorer.outline='olexp-' + id
     *           + '-explorer-name-outline'] w2ui name of outline panel
     * @property {external:w2ui.common.name} [explorer.toolbar='olexp-' + id
     *           + '-explorer-name-toolbar'] w2ui name of toolbar
     *
     * @property {external:jQuery.fn.w2sidebar.nodes} [layers] Options for
     *           layers node
     * @property {string} [layers.id='olexp-' + id + '-explorer-id-layers']
     *           Unique ID of node
     *
     * @property {external:jQuery.fn.w2layout.panels} [map] Options for map
     *           panel
     * @property {string} [map.content='<div id="olexp-' + id +
     *           '-explorer-id-map'" class="olexp-explorer-map"></div>']
     *           Panel content. Should be div containing ol.Map and
     *           referenced by olmap.target.
     *
     * @property {external:ol.Map} [olmap] Options for ol3 map
     * @property {Element|string|undefined} [olmap.target=options.map.id]
     *           The container for the map, either the element itself or the
     *           id of the element.
     *
     * @property {external:jQuery.fn.w2sidebar.nodes} [overlays] Options for
     *           overlays node
     * @property {string} [overlays.id='olexp-' + id +
     *           '-explorer-id-overlays'] Unique ID of node
     */
    $.extend(true, this.options, {
      explorer: {
        cls: 'olexp-explorer-content',
        id: prefix + '-explorer-id-content',
        details: prefix + '-explorer-name-details',
        layout: prefix + '-explorer-name-layout',
        navigation: prefix + '-explorer-name-navigation',
        outline: prefix + '-explorer-name-outline',
        toolbar: prefix + '-explorer-name-toolbar',
      },
      layers: {
        id: prefix + '-explorer-id-layers',
      },
      map: {
        content: ('<div id="' + prefix + '-explorer-id-map"' +
            ' class="olexp-explorer-map"></div>'),
      },
      olmap: {
        target: prefix + '-explorer-id-map',
      },
      overlays: {
        id: prefix + '-explorer-id-overlays',
      },
      settings: {
        prefix,
      },
    });

    // ==================================================
    // Store current object
    // --------------------------------------------------
    const self = this;

    // ==================================================
    // Create main layout content div
    // --------------------------------------------------

    const div = $('<div>', {'id': this.options.explorer.id,
      'class': this.options.explorer.cls});
    $('#' + id).append(div);

    // ==================================================
    // Main Layout
    // --------------------------------------------------

    this.layout = $('#' + this.options.explorer.id).w2layout({
      name: this.options.explorer.layout,
      panels: [
        this.options.navigation,
        this.options.map,
        this.options.toolbar,
      ],
    });

    // ==================================================
    // Main Toolbar
    // --------------------------------------------------

    this.toolbar = $('').w2toolbar({
      name: this.options.explorer.toolbar,
    });

    // ==================================================
    // Navigation pane Layout
    // --------------------------------------------------

    this.navigation = $('').w2layout({
      name: this.options.explorer.navigation,
      onResize() {
        if (self.hasOwnProperty('map')) {
          self.map.updateSize();
        }
        if (self.hasOwnProperty('details')) {
          self.details.resize();
        }
      },
      panels: [
        this.options.outline,
        this.options.details,
      ],
    });

    // ==================================================
    // Outline sidebar
    // --------------------------------------------------

    this.outline = $('').w2sidebar({
      name: this.options.explorer.outline,
      nodes: [
        this.options.layers,
        this.options.overlays,
      ],
      onClick(event) {
        const targetId = event.target;
        const records = self.manager.getDetails(targetId);
        self.details.clear();
        self.details.add(records);
        self.manager.onItemSelected(targetId);
      },
      onDblClick(event) {
        const targetId = event.target;
        self.manager.toggleNode(targetId);
        self.manager.onItemSelected(targetId);
      },
      onRender(event) {
        event.onComplete = () => {
          const targetId = self.outline.selected;
          self.manager.onItemSelected(targetId);
        };
      },
    });

    // ==================================================
    // Details table
    // --------------------------------------------------

    this.details = $('').w2grid({
      columns: [{
        field: 'property',
        caption: 'Property',
        size: '100%',
        sortable: true,
      }, {
        field: 'value',
        caption: 'Value',
        size: '100%',
        sortable: true,
      }],
      name: this.options.explorer.details,
    });

    // ==================================================
    // Add Content
    // --------------------------------------------------

    this.navigation.content(this.options.outline.type, this.outline);
    this.navigation.content(this.options.details.type, this.details);
    this.layout.content(this.options.navigation.type, this.navigation);

    // ==================================================
    // Define map
    // --------------------------------------------------

    this.map = new ol.Map(this.options.olmap);

    // ==================================================
    // Layer manager
    // --------------------------------------------------
    this.manager = new olexp.manager.Manager(this.map, this.outline,
        this.details, this.options.layers.id, this.options.overlays.id);

    // ==================================================
    // Create menu items and callbacks in outline
    // --------------------------------------------------

    const settings = this.options.settings;
    const zoom = olexp.menu.zoom(this.manager, settings);
    const properties = olexp.menu.properties(this.manager, settings);
    const remove = olexp.menu.remove(this.manager, settings);

    this.menu = {items: [], callbacks: {}};

    this.menu.items.push(zoom.menu);
    this.menu.items.push(properties.menu);
    this.menu.items.push(remove.menu);

    this.menu.callbacks[zoom.menu.id] = zoom.click;
    this.menu.callbacks[properties.menu.id] = properties.click;
    this.menu.callbacks[remove.menu.id] = remove.click;

    // Add menu items and callbacks to outline
    this.outline.menu = this.menu.items;
    this.outline.onMenuClick = (event) => {
      const targetId = event.menuItem.id;
      if (self.menu.callbacks[targetId] !== undefined) {
        self.menu.callbacks[targetId](event);
      }
    };

    // ==================================================
    // Define map interactions
    // --------------------------------------------------

    this.util = new olexp.util.Util(this.options.settings);

    // Add map interactions
    const interactions = this.util.getInteractions(this.map);
    Object.keys(this.options.olinteractions).forEach((iname) => {
      const interaction = interactions[iname];
      if (self.options.olinteractions[iname]) {
        self.map.addInteraction(interaction);
      }
    });

    // Add map controls
    const controls = this.util.getControls();
    Object.keys(this.options.olcontrols).forEach((cname) => {
      const control = controls[cname];
      self.map.addControl(control);
      control.setMap((self.options.olcontrols[cname] ? self.map : null));
    });

    // ==================================================
    // Feature selector
    // --------------------------------------------------

    this.selector = new olexp.selection.Feature(this.map, this.details);
    this.selector.setEnable(true);

    // ==================================================
    // All layout and map components are defined so we
    // can define the main Explorer API.
    // --------------------------------------------------

    /**
     * @description The objects exposed by the Explorer API
     * @typedef {object} ExplorerAPI
     * @memberOf olexp
     * @property {external:jQuery.fn.w2grid} details Layer details panels.
     *           Display the details of the later that is currently selected
     *           in the outline sidebar.
     * @property {external:jQuery.fn.w2layout} layout Explorer layout
     *           object. Contains the map, toolbar, and navigation panels.
     *           Can maintain up to 3 additional panels that are stretchable
     *           and resizable.
     * @property {olexp.manager.ManagerAPI} manager Explorer item manager
     * @property {external:ol.Map} map ol3 map object used to add layers,
     *           overlays, controls, etc.
     * @property {external:jQuery.fn.w2layout} navigation Layer manager
     *           navigation panel. The panel that contains the outline
     *           sidebar and detail grid.
     * @property {olexp.ExplorerOptions} options Explorer options object
     *           that contains the options argument passed to the explorer
     *           constructor.
     * @property {external:jQuery.fn.w2sidebar} outline Layer manager
     *           outline panel that allows the user to manage the ordering
     *           and properties of the map layers.
     * @property {external:jQuery.fn.w2toolbar} toolbar Explorer toolbar
     *           that contains map and layers controls.
     */
    this.api = {
      details: this.details,
      layout: this.layout,
      manager: this.manager,
      map: this.map,
      navigation: this.navigation,
      options: this.options,
      outline: this.outline,
      toolbar: this.toolbar,
    };

    // ==================================================
    // Add built-in controls to toolbar
    // --------------------------------------------------

    if (this.options.controls.toolbarhide) {
      this.toolbar.add(olexp.control.toolbarHide(this.api, {
        hidden: this.options.toolbar.hidden,
        settings: this.options.settings,
      }));
      this.toolbar.add({id: 'break-toolbar-hide', type: 'break'});
    }

    if (this.options.controls.layermanager) {
      this.toolbar.add(olexp.control.layerManager(this.api, this.manager, {
        details: {checked: !this.options.details.hidden},
        navigation: {checked: !this.options.navigation.hidden},
        settings: this.options.settings,
      }));
      this.toolbar.add({id: 'break-layer-manager', type: 'break'});
    }

    if (this.options.controls.layermenu) {
      this.toolbar.add(olexp.control.layerMenu(this.api, this.manager,
          this.menu, {settings: this.options.settings}));
      this.toolbar.add({id: 'break-item-menu', type: 'break'});
    }

    if (this.options.controls.layercontrol) {
      this.toolbar.add(olexp.control.layerControl(this.api, {
        settings: this.options.settings,
      }));
      this.toolbar.add({id: 'break-layer-control', type: 'break'});
    }

    if (this.options.controls.graticule) {
      this.toolbar.add(olexp.control.graticule(this.api, {
        settings: this.options.settings,
      }));
      this.toolbar.add({id: 'break-graticule', type: 'break'});
    }

    if (this.options.controls.measure) {
      this.toolbar.add(olexp.control.measure(this.api, {
        settings: this.options.settings,
      }));
      this.toolbar.add({id: 'break-measure', type: 'break'});
    }

    if (this.options.controls.exportmap) {
      this.toolbar.add(olexp.control.exportMap(this.api, {
        settings: this.options.settings,
      }));
      this.toolbar.add({id: 'break-export-map', type: 'break'});
    }

    if (this.options.controls.editsettings) {
      this.toolbar.add(olexp.control.editSettings(this.api, {
        settings: this.options.settings,
      }));
      this.toolbar.add({id: 'break-edit-settings', type: 'break'});
    }

    this.layout.set(this.options.toolbar.type, {
      content: '',
      show: {toolbar: true},
      toolbar: this.toolbar,
    });
  };

  /**
   * Destroy all w2ui and openlayer resources. The explorer is no longer
   * valid after calling this method.
   * @memberOf olexp
   * @param {olexp.ExplorerAPI} explorer Explorer API object
   * @public
   */
  olexp.destroy = (explorer) => {
    if (explorer.map !== undefined) {
      explorer.map.setTarget(null);
    }
    if (explorer.details !== undefined) {
      explorer.details.destroy();
    }
    if (explorer.outline !== undefined) {
      explorer.outline.destroy();
    }
    if (explorer.navigation !== undefined) {
      explorer.navigation.destroy();
    }
    if (explorer.toolbar !== undefined) {
      explorer.toolbar.destroy();
    }
    if (explorer.layout !== undefined) {
      explorer.layout.destroy();
    }
  };

  // ==================================================
  // Explorer API
  // --------------------------------------------------

  /**
   * Constructor to create an Explorer.
   * @class Explorer
   * @memberOf olexp
   * @param {string} id DOM id of the element div containing the Explorer.
   * @param {olexp.ExplorerOptions} [options] Explorer options
   * @public
   * @return {olexp.ExplorerAPI} Explorer API
   * @throws {Error} DOM id must be defined and exist
   */
  olexp.Explorer = function(id, options) {
    const explorer = new Explorer(id, options);
    return explorer.api;
  };
})(olexp || {});

export default {
  destroy: olexp.destroy,
  Explorer: olexp.Explorer,
};


text:
options.visualize = true;
options.floating = true;
options.terrain = RigidBodyFlatTerrain();

val_version = 3
if (val_version == 1)
  urdf = fullfile(getDrakePath(),'..','models','valkyrie','V1_sim_shells_reduced_polygon_count_mit.urdf');
  S = load([getDrakePath(), '/../control/matlab/data/valkyrie_fp.mat']);
elseif (val_version == 2)
  urdf = fullfile(getDrakePath(),'..','models','val_description','model.urdf');
  S = load([getDrakePath(), '/../control/matlab/data/valkyrie_fp_june2015.mat']);
else
  urdf = '/home/mfallon/otherprojects/val_description/robots/valkyrie_A.urdf';
  S = load([getDrakePath(), '/../control/matlab/data/valkyrie_fp_june2015.mat']);
end

r = RigidBodyManipulator(urdf,options);
r = r.compile();
v = r.constructVisualizer(); % robot arms spread, pelvise at zero
v = v.enableLCMGLInertiaEllipsoids();
nq = 38;
q_nom = S.xstar(1:nq);

%q_nom = S.xstar(1:65);
v.draw(0,q_nom); % standing configuration with left arm out to side

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Org\Schema\Thing\Place\Landform;

/**
 * Class Volcano
 * A volcano, like Fuji san.
 * @author      AppBels <app.bels@gmail.com>
 * @name        Volcano
 * @namespace   Org\Schema\Thing\Place\Landform
 * @package     Org\Schema
 * @see         https://schema.org/Volcano
 * Date         10/04/2017
 */
class Volcano extends \Org\Schema\Thing\Place\Landform
{

	/**
	 * Volcano constructor.
	 * @access  public
	 * @see     \Org\Schema\Thing\Place\Landform::__construct()
	 */
	public function __construct ()
	{
		parent::__construct();
	}

	/**
	 * Volcano toString.
	 * @access  public
	 * @see     \Org\Schema\Thing\Place\Landform::__toString()
	 *
	 * @return  string
	 */
	public function __toString ()
	{
		return parent::__toString();
	}

	/**
	 * Volcano destructor.
	 * @access  public
	 * @see     \Org\Schema\Thing\Place\Landform::__destruct()
	 */
	public function __destruct ()
	{
		parent::__destruct();
	}

}

?>


text:
<mods xmlns="http://www.loc.gov/mods/v3" xmlns:exslt="http://exslt.org/common" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xlink="http://www.w3.org/1999/xlink" xsi:schemaLocation="http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-3.xsd" version="3.3" ID="P0b002ee18a685007">
<name type="corporate">
 <namePart>United States Government Printing Office</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">printer</roleTerm>
  <roleTerm type="code" authority="marcrelator">prt</roleTerm>
</role>
 <role>
  <roleTerm type="text" authority="marcrelator">distributor</roleTerm>
  <roleTerm type="code" authority="marcrelator">dst</roleTerm>
</role>
</name>
<name type="corporate">
 <namePart>United States</namePart>
 <namePart>United States Court of Appeals for the Tenth Circuit</namePart>
 <role>
  <roleTerm type="text" authority="marcrelator">author</roleTerm>
  <roleTerm type="code" authority="marcrelator">aut</roleTerm>
</role>
 <description>Government Organization</description>
</name>
<typeOfResource>text</typeOfResource>
<genre authority="marcgt">government publication</genre>
<language>
 <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</language>
<extension>
 <collectionCode>USCOURTS</collectionCode>
 <category>Judicial Publications</category>
 <branch>judicial</branch>
 <dateIngested>2014-12-08</dateIngested>
</extension>
<originInfo>
 <publisher>Administrative Office of the United States Courts</publisher>
 <dateIssued encoding="w3cdtf">2013-01-03</dateIssued>
 <issuance>monographic</issuance>
</originInfo>
<physicalDescription>
 <note type="source content type">deposited</note>
 <digitalOrigin>born digital</digitalOrigin>
</physicalDescription>
<classification authority="sudocs">JU 2.11</classification>
<identifier type="uri">http://www.gpo.gov/fdsys/pkg/USCOURTS-ca10-12-05053</identifier>
<identifier type="local">P0b002ee18a685007</identifier>
<recordInfo>
 <recordContentSource authority="marcorg">DGPO</recordContentSource>
 <recordCreationDate encoding="w3cdtf">2014-12-08</recordCreationDate>
 <recordChangeDate encoding="w3cdtf">2014-12-08</recordChangeDate>
 <recordIdentifier source="DGPO">USCOURTS-ca10-12-05053</recordIdentifier>
 <recordOrigin>machine generated</recordOrigin>
 <languageOfCataloging>
  <languageTerm authority="iso639-2b" type="code">eng</languageTerm>
</languageOfCataloging>
</recordInfo>
<accessCondition type="GPO scope determination">fdlp</accessCondition>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ca10-12-05053</accessId>
 <courtType>Appellate</courtType>
 <courtCode>ca10</courtCode>
 <courtCircuit>10th</courtCircuit>
 <courtSortOrder>1100</courtSortOrder>
 <caseNumber>12-05053</caseNumber>
 <natureSuitCode>510</natureSuitCode>
 <natureSuit>Prisoner Petitions - Vacate Sentence</natureSuit>
 <party firstName="Richard" fullName="Richard Dale Montgomery" lastName="Montgomery" middleName="Dale" role="Appellant"></party>
 <party fullName="United States of America" lastName="United States of America" role="Appellee"></party>
</extension>
<titleInfo>
 <title>United States v. Montgomery</title>
 <partNumber>12-05053</partNumber>
</titleInfo>
<location>
 <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/pkg/USCOURTS-ca10-12-05053/content-detail.html</url>
</location>
<classification authority="sudocs">JU 2.11</classification>
<identifier type="preferred citation">12-05053;12-5053</identifier>
<name type="corporate">
 <namePart>United States Court of Appeals for the Tenth Circuit</namePart>
 <namePart>10th Circuit</namePart>
 <namePart></namePart>
 <affiliation>U.S. Courts</affiliation>
 <role>
  <roleTerm authority="marcrelator" type="text">author</roleTerm>
  <roleTerm authority="marcrelator" type="code">aut</roleTerm>
</role>
</name>
<name type="personal">
 <displayForm>Richard Dale Montgomery</displayForm>
 <namePart type="family">Montgomery</namePart>
 <namePart type="given">Richard</namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Appellant</description>
</name>
<name type="personal">
 <displayForm>United States of America</displayForm>
 <namePart type="family">United States of America</namePart>
 <namePart type="given"></namePart>
 <namePart type="termsOfAddress"></namePart>
 <description>Appellee</description>
</name>
<extension>
 <docClass>USCOURTS</docClass>
 <accessId>USCOURTS-ca10-12-05053</accessId>
 <courtType>Appellate</courtType>
 <courtCode>ca10</courtCode>
 <courtCircuit>10th</courtCircuit>
 <courtSortOrder>1100</courtSortOrder>
 <caseNumber>12-05053</caseNumber>
 <natureSuitCode>510</natureSuitCode>
 <natureSuit>Prisoner Petitions - Vacate Sentence</natureSuit>
 <party firstName="Richard" fullName="Richard Dale Montgomery" lastName="Montgomery" middleName="Dale" role="Appellant"></party>
 <party fullName="United States of America" lastName="United States of America" role="Appellee"></party>
</extension>
<relatedItem type="constituent" ID="id-USCOURTS-ca10-12-05053-0" xlink:href="http://www.gpo.gov/fdsys/granule/USCOURTS-ca10-12-05053/USCOURTS-ca10-12-05053-0/mods.xml">
 <titleInfo>
  <title>United States v. Montgomery</title>
  <subTitle>[10032526] COA Denial;Terminated on the merits after submissions without oral hearing; Written, signed, unpublished; Judges Murphy, Ebel (authoring) and Hartz. [12-5053]</subTitle>
  <partNumber>0</partNumber>
</titleInfo>
 <originInfo>
  <dateIssued>2013-01-03</dateIssued>
</originInfo>
 <relatedItem type="otherFormat" xlink:href="http://www.gpo.gov/fdsys/pkg/USCOURTS-ca10-12-05053/pdf/USCOURTS-ca10-12-05053-0.pdf">
  <identifier type="FDsys Unique ID">D09002ee18a6b90bc</identifier>
</relatedItem>
 <identifier type="uri">http://www.gpo.gov/fdsys/granule/USCOURTS-ca10-12-05053/USCOURTS-ca10-12-05053-0</identifier>
 <identifier type="former granule identifier">ca10-12-05053_0.pdf</identifier>
 <location>
  <url access="object in context" displayLabel="Content Detail">http://www.gpo.gov/fdsys/granule/USCOURTS-ca10-12-05053/USCOURTS-ca10-12-05053-0/content-detail.html</url>
  <url access="raw object" displayLabel="PDF rendition">http://www.gpo.gov/fdsys/pkg/USCOURTS-ca10-12-05053/pdf/USCOURTS-ca10-12-05053-0.pdf</url>
</location>
 <extension>
  <searchTitle>USCOURTS 12-05053; United States v. Montgomery; </searchTitle>
  <courtName>United States Court of Appeals for the Tenth Circuit</courtName>
  <accessId>USCOURTS-ca10-12-05053-0</accessId>
  <sequenceNumber>0</sequenceNumber>
  <dateIssued>2013-01-03</dateIssued>
  <docketText>[10032526] COA Denial;Terminated on the merits after submissions without oral hearing; Written, signed, unpublished; Judges Murphy, Ebel (authoring) and Hartz. [12-5053]</docketText>
</extension>
</relatedItem>
</mods>


text:
import argparse
import csv
import os
import zipfile

fl_min_lon = -87.63489605
fl_min_lat = 24.39630799
fl_max_lon = -79.97430602
fl_max_lat = 31.00096799

def build_statewide_file(input_zipfile, out_filename):
    headers_written = False
    out = open(out_filename, 'w')
    writer = csv.writer(out)
    zip_archive = zipfile.ZipFile(input_zipfile)
    for f in zip_archive.infolist():
        filename = f.filename
        if 'STATEWIDE' in filename:
            continue
        local_filename = zip_archive.extract(filename)
        reader = csv.reader(open(local_filename))
        headers = next(reader)
        if not headers_written:
            writer.writerow(headers)
            headers_written = True
        lat_index = headers.index('LAT')
        lon_index = headers.index('LONG')
        for row in reader:
            lat = row[lat_index].strip()
            lon = row[lon_index].strip()
            valid_latlon = lat and lon
            if not valid_latlon:
                continue
            lat_float = float(lat)
            valid_latlon = valid_latlon and lat_float >= fl_min_lat and lat_float <= fl_max_lat
            lon_float = float(lon)
            valid_latlon = valid_latlon and lon_float >= fl_min_lon and lon_float <= fl_max_lon

            valid_latlon = valid_latlon and not (lat_float == int(lat_float) and lon_float == int(lon_float))
            if not valid_latlon:
                row[lat_index] = ''
                row[lon_index] = ''
            writer.writerow(row)
        os.unlink(filename)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('input_filename')
    parser.add_argument('output_filename')

    args = parser.parse_args()
    build_statewide_file(args.input_filename, args.output_filename)


text:
package org.weakref.jmx;

import javax.management.MBeanAttributeInfo;
import javax.management.AttributeNotFoundException;
import javax.management.MBeanException;
import javax.management.ReflectionException;
import javax.management.InvalidAttributeValueException;

public interface MBeanAttribute extends MBeanFeature
{
    MBeanAttributeInfo getInfo();

    String getName();

    Object getValue()
            throws AttributeNotFoundException, MBeanException, ReflectionException;

    void setValue(Object value)
                    throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException;
}


text:
const {
  GraphQLObjectType,
  GraphQLList,
  GraphQLString,
  GraphQLInt,
  GraphQLEnumType,
} = require(`graphql`)
const Remark = require(`remark`)
const select = require(`unist-util-select`)
const sanitizeHTML = require(`sanitize-html`)
const _ = require(`lodash`)
const visit = require(`unist-util-visit`)
const toHAST = require(`mdast-util-to-hast`)
const hastToHTML = require(`hast-util-to-html`)
const mdastToToc = require(`mdast-util-toc`)
const Promise = require(`bluebird`)
const prune = require(`underscore.string/prune`)

let pluginsCacheStr = ``
const astCacheKey = node =>
  `transformer-remark-markdown-ast-${node.internal
    .contentDigest}-${pluginsCacheStr}`
const htmlCacheKey = node =>
  `transformer-remark-markdown-html-${node.internal
    .contentDigest}-${pluginsCacheStr}`
const headingsCacheKey = node =>
  `transformer-remark-markdown-headings-${node.internal
    .contentDigest}-${pluginsCacheStr}`
const tableOfContentsCacheKey = node =>
  `transformer-remark-markdown-toc-${node.internal
    .contentDigest}-${pluginsCacheStr}`

module.exports = (
  { type, store, pathPrefix, getNode, cache },
  pluginOptions
) => {
  if (type.name !== `MarkdownRemark`) {
    return {}
  }

  pluginsCacheStr = pluginOptions.plugins.map(p => p.name).join(``)

  return new Promise((resolve, reject) => {
    // Setup Remark.
    let remark = new Remark().data(`settings`, {
      commonmark: true,
      footnotes: true,
      pedantic: true,
    })

    for (let plugin of pluginOptions.plugins) {
      const requiredPlugin = require(plugin.resolve)
      if (_.isFunction(requiredPlugin.setParserPlugins)) {
        for (let parserPlugin of requiredPlugin.setParserPlugins()) {
          remark = remark.use(parserPlugin)
        }
      }
    }

    async function getAST(markdownNode) {
      const cachedAST = await cache.get(astCacheKey(markdownNode))
      if (cachedAST) {
        return cachedAST
      } else {
        const files = _.values(store.getState().nodes).filter(
          n => n.internal.type === `File`
        )
        const ast = await new Promise((resolve, reject) => {
          Promise.all(
            pluginOptions.plugins.map(plugin => {
              const requiredPlugin = require(plugin.resolve)
              if (_.isFunction(requiredPlugin.mutateSource)) {
                console.log(`running plugin to mutate markdown source`)
                return requiredPlugin.mutateSource(
                  {
                    markdownNode,
                    files,
                    getNode,
                  },
                  plugin.pluginOptions
                )
              } else {
                return Promise.resolve()
              }
            })
          ).then(() => {
            const markdownAST = remark.parse(markdownNode.internal.content)

            // source => parse (can order parsing for dependencies) => typegen
            //
            // source plugins identify nodes, provide id, initial parse, know
            // when nodes are created/removed/deleted
            // get passed cached DataTree and return list of clean and dirty nodes.
            // Also get passed `dirtyNodes` function which they can call with an array
            // of node ids which will then get re-parsed and the inferred schema
            // recreated (if inferring schema gets too expensive, can also
            // cache the schema until a query fails at which point recreate the
            // schema).
            //
            // parse plugins take data from source nodes and extend it, never mutate
            // it. Freeze all nodes once done so typegen plugins can't change it
            // this lets us save off the DataTree at that point as well as create
            // indexes.
            //
            // typegen plugins identify further types of data that should be lazily
            // computed due to their expense, or are hard to infer graphql type
            // (markdown ast), or are need user input in order to derive e.g.
            // markdown headers or date fields.
            //
            // wrap all resolve functions to (a) auto-memoize and (b) cache to disk any
            // resolve function that takes longer than ~10ms (do research on this
            // e.g. how long reading/writing to cache takes), and (c) track which
            // queries are based on which source nodes. Also if connection of what
            // which are always rerun if their underlying nodes change..
            //
            // every node type in DataTree gets a schema type automatically.
            // typegen plugins just modify the auto-generated types to add derived fields
            // as well as computationally expensive fields.
            const files = _.values(store.getState().nodes).filter(
              n => n.internal.type === `File`
            )
            Promise.all(
              pluginOptions.plugins.map(plugin => {
                const requiredPlugin = require(plugin.resolve)
                if (_.isFunction(requiredPlugin)) {
                  return requiredPlugin(
                    {
                      markdownAST,
                      markdownNode,
                      getNode,
                      files,
                      pathPrefix,
                    },
                    plugin.pluginOptions
                  )
                } else {
                  return Promise.resolve()
                }
              })
            ).then(() => {
              resolve(markdownAST)
            })
          })
        })

        // Save new AST to cache and return
        cache.set(astCacheKey(markdownNode), ast)
        return ast
      }
    }

    async function getHeadings(markdownNode) {
      const cachedHeadings = await cache.get(headingsCacheKey(markdownNode))
      if (cachedHeadings) {
        return cachedHeadings
      } else {
        const ast = await getAST(markdownNode)
        const headings = select(ast, `heading`).map(heading => {
          return {
            value: _.first(select(heading, `text`).map(text => text.value)),
            depth: heading.depth,
          }
        })

        cache.set(headingsCacheKey(markdownNode), headings)
        return headings
      }
    }

    async function getTableOfContents(markdownNode) {
      const cachedToc = await cache.get(tableOfContentsCacheKey(markdownNode))
      if (cachedToc) {
        return cachedToc
      } else {
        const ast = await getAST(markdownNode)
        const tocAst = mdastToToc(ast)
        let toc
        if (tocAst.map) {
          toc = hastToHTML(toHAST(tocAst.map))
        } else {
          toc = ``
        }
        cache.set(tableOfContentsCacheKey(markdownNode), toc)
        return toc
      }
    }

    async function getHTML(markdownNode) {
      const cachedHTML = await cache.get(htmlCacheKey(markdownNode))
      if (cachedHTML) {
        return cachedHTML
      } else {
        const html = await new Promise((resolve, reject) => {
          getAST(markdownNode).then(ast => {
            resolve(
              hastToHTML(toHAST(ast, { allowDangerousHTML: true }), {
                allowDangerousHTML: true,
              })
            )
          })
        })

        // Save new HTML to cache and return
        cache.set(htmlCacheKey(markdownNode), html)
        return html
      }
    }

    const HeadingType = new GraphQLObjectType({
      name: `MarkdownHeading`,
      fields: {
        value: {
          type: GraphQLString,
          resolve(heading) {
            return heading.value
          },
        },
        depth: {
          type: GraphQLInt,
          resolve(heading) {
            return heading.depth
          },
        },
      },
    })

    const HeadingLevels = new GraphQLEnumType({
      name: `HeadingLevels`,
      values: {
        h1: { value: 1 },
        h2: { value: 2 },
        h3: { value: 3 },
        h4: { value: 4 },
        h5: { value: 5 },
        h6: { value: 6 },
      },
    })

    return resolve({
      html: {
        type: GraphQLString,
        resolve(markdownNode) {
          return getHTML(markdownNode)
        },
      },
      excerpt: {
        type: GraphQLString,
        args: {
          pruneLength: {
            type: GraphQLInt,
            defaultValue: 140,
          },
        },
        resolve(markdownNode, { pruneLength }) {
          return getAST(markdownNode).then(ast => {
            const textNodes = []
            visit(ast, `text`, textNode => textNodes.push(textNode.value))
            return prune(textNodes.join(` `), pruneLength)
          })
        },
      },
      headings: {
        type: new GraphQLList(HeadingType),
        args: {
          depth: {
            type: HeadingLevels,
          },
        },
        resolve(markdownNode, { depth }) {
          return getHeadings(markdownNode).then(headings => {
            if (typeof depth === `number`) {
              headings = headings.filter(heading => heading.depth === depth)
            }
            return headings
          })
        },
      },
      timeToRead: {
        type: GraphQLInt,
        resolve(markdownNode) {
          return getHTML(markdownNode).then(html => {
            let timeToRead = 0
            const pureText = sanitizeHTML(html, { allowTags: [] })
            const avgWPM = 265
            const wordCount = _.words(pureText).length
            timeToRead = Math.round(wordCount / avgWPM)
            if (timeToRead === 0) {
              timeToRead = 1
            }
            return timeToRead
          })
        },
      },
      tableOfContents: {
        type: GraphQLString,
        resolve(markdownNode) {
          return getTableOfContents(markdownNode)
        },
      },
    })
  })
}


text:
package org.apache.ignite.configuration;

import org.apache.ignite.IgniteAtomicSequence;
import org.apache.ignite.cache.CacheMode;
import org.apache.ignite.cache.affinity.AffinityFunction;
import org.apache.ignite.internal.util.typedef.internal.S;

import static org.apache.ignite.cache.CacheMode.PARTITIONED;

/**
 * Configuration for atomic data structures.
 */
public class AtomicConfiguration {
    /** */
    public static final int DFLT_BACKUPS = 0;

    /** */
    public static final CacheMode DFLT_CACHE_MODE = PARTITIONED;

    /** Default atomic sequence reservation size. */
    public static final int DFLT_ATOMIC_SEQUENCE_RESERVE_SIZE = 1000;

    /** Default batch size for all cache's sequences. */
    private int seqReserveSize = DFLT_ATOMIC_SEQUENCE_RESERVE_SIZE;

    /** Cache mode. */
    private CacheMode cacheMode = DFLT_CACHE_MODE;

    /** Number of backups. */
    private int backups = DFLT_BACKUPS;

    /** Affinity function */
    private AffinityFunction aff;

    /**
     * @return Number of backup nodes.
     */
    public int getBackups() {
        return backups;
    }

    /**
     * @param backups Number of backup nodes.
     * @return {@code this} for chaining.
     */
    public AtomicConfiguration setBackups(int backups) {
        this.backups = backups;

        return this;
    }

    /**
     * @return Cache mode.
     */
    public CacheMode getCacheMode() {
        return cacheMode;
    }

    /**
     * @param cacheMode Cache mode.
     * @return {@code this} for chaining.
     */
    public AtomicConfiguration setCacheMode(CacheMode cacheMode) {
        this.cacheMode = cacheMode;

        return this;
    }

    /**
     * Gets default number of sequence values reserved for {@link IgniteAtomicSequence} instances. After
     * a certain number has been reserved, consequent increments of sequence will happen locally,
     * without communication with other nodes, until the next reservation has to be made.
     * <p>
     * Default value is {@link #DFLT_ATOMIC_SEQUENCE_RESERVE_SIZE}.
     *
     * @return Atomic sequence reservation size.
     */
    public int getAtomicSequenceReserveSize() {
        return seqReserveSize;
    }

    /**
     * Sets default number of sequence values reserved for {@link IgniteAtomicSequence} instances. After a certain
     * number has been reserved, consequent increments of sequence will happen locally, without communication with other
     * nodes, until the next reservation has to be made.
     *
     * @param seqReserveSize Atomic sequence reservation size.
     * @see #getAtomicSequenceReserveSize()
     * @return {@code this} for chaining.
     */
    public AtomicConfiguration setAtomicSequenceReserveSize(int seqReserveSize) {
        this.seqReserveSize = seqReserveSize;

        return this;
    }

    /**
     * Gets atomic cache affinity function.
     *
     * @return Affinity function or null, if not set.
     */
    public AffinityFunction getAffinity() {
        return aff;
    }

    /**
     * Sets atomic cache affinity function.
     *
     * @param aff Affinity function.
     * @return {@code this} for chaining.
     */
    public AtomicConfiguration setAffinity(AffinityFunction aff) {
        this.aff = aff;

        return this;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return S.toString(AtomicConfiguration.class, this);
    }
}


text:
package org.earthtime.ratioDataViews;

import java.awt.Dimension;
import org.earthtime.UPb_Redux.valueModelPanelViews.ValueModelsPanelViewNotEditable;
import org.earthtime.matrices.matrixViews.MatrixGridViewNotEditable;
import org.earthtime.ratioDataModels.AbstractRatiosDataModel;
import org.earthtime.ratioDataModels.tracers.TracerUPbModel;

/**
 *
 * @author James F. Bowring
 */
public class TracerUPbRatiosDataViewNotEditable extends TracerUPbRatiosAbstractDataView {

    private final boolean showTableOnly;

    /**
     *
     *
     * @param ratiosDataModel the value of ratiosDataModel
     * @param parentDimension the value of parentDimension
     * @param showTableOnly the value of showTableOnly
     */
    public TracerUPbRatiosDataViewNotEditable( //
            AbstractRatiosDataModel ratiosDataModel, Dimension parentDimension, boolean showTableOnly) {

        super(ratiosDataModel, parentDimension);
        this.showTableOnly = showTableOnly;
        setupViews();
        initView(false);
    }

    /**
     *
     */
    @Override
    protected final void setupViews() {
        this.valueModelsPanelView = new ValueModelsPanelViewNotEditable(//
                dataModel.getData());

        this.covarianceVarUnctMatrixView = new MatrixGridViewNotEditable(dataModel.getDataCovariancesVarUnct(), showTableOnly);
        this.correlationVarUnctMatrixView = new MatrixGridViewNotEditable(dataModel.getDataCorrelationsVarUnct(), showTableOnly);
    }

    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        AbstractRatiosDataView testView = new TracerUPbRatiosDataViewNotEditable(TracerUPbModel.getET535ModelInstance(), null, false);

        testView.displayModelInFrame();

    }
}


text:
<?php

namespace app\models;

use Yii;

use app\models\Houses;

/**
 * This is the model class for table "pictures".
 *
 * @property integer $PictureID
 * @property string $PictureName
 * @property string $PictureDescription
 * @property integer $HouseID
 * @property string $PictureType
 *
 * @property Houses $house
 */
class Pictures extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'pictures';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['PictureDescription', 'HouseID'], 'required'],
            [['HouseID'], 'integer'],
            [['PictureDescription'], 'string', 'max' => 50],
            [['PictureType'], 'safe']
            //[['PictureType'], 'string', 'max' => 100]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'PictureID' => 'Picture ID',
            'PictureName' => 'Picture Name',
            'PictureDescription' => 'Picture Description',
            'HouseID' => 'House ID',
            'PictureType' => 'Picture Type',
            'HouseName' => 'House Name'
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getHouse()
    {
        return $this->hasOne(Houses::className(), ['HouseID' => 'HouseID']);
    }

    public function getHouseName()
    {
        Yii::info($this->house, __METHOD__);
        return $this->house->HouseName;
    }
}


text:
<?php

namespace Application\Sonata\ClientOperationsBundle\DQL;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;

/**
 * REPLACE(str, from_str, to_str)
 * "REPLACE" "(" StringPrimary "," StringPrimary "," StringPrimary ")"
 */
class ReplaceFunction extends FunctionNode
{
    protected $stringStr, $stringFromStr, $stringToStr;

    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)  {
        return sprintf(
            'REPLACE(%s, %s, %s)',
            $sqlWalker->walkStringPrimary($this->stringStr),
            $sqlWalker->walkStringPrimary($this->stringFromStr),
            $sqlWalker->walkStringPrimary($this->stringToStr)
        );
    }

	public function parse(\Doctrine\ORM\Query\Parser $parser) {
        $parser->match(Lexer::T_IDENTIFIER);                // REPLACE
        $parser->match(Lexer::T_OPEN_PARENTHESIS);
        $this->stringStr = $parser->StringPrimary();        // str
        $parser->match(Lexer::T_COMMA);
        $this->stringFromStr = $parser->StringPrimary();    // from_str
        $parser->match(Lexer::T_COMMA);
        $this->stringToStr = $parser->StringPrimary();      // to_str
        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }
}


text:
package com.dianping.cat.message.storage;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import java.io.ByteArrayOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.GZIPOutputStream;

import org.unidal.lookup.annotation.Inject;

import com.dianping.cat.Cat;
import com.dianping.cat.message.internal.MessageId;
import com.dianping.cat.message.spi.MessageCodec;
import com.dianping.cat.message.spi.MessageTree;
import com.dianping.cat.message.spi.internal.DefaultMessageTree;

public class LocalMessageBucket implements MessageBucket {
	public static final String ID = "local";

	private static final int MAX_BLOCK_SIZE = 1 << 16; // 64K

	@Inject
	private MessageCodec m_codec;

	private File m_baseDir = new File(".");

	private MessageBlockReader m_reader;

	private MessageBlockWriter m_writer;

	private AtomicBoolean m_dirty = new AtomicBoolean();

	private String m_dataFile;

	private long m_lastAccessTime;

	private GZIPOutputStream m_out;

	private ByteArrayOutputStream m_buf;

	private MessageBlock m_block;

	private int m_blockSize;

	@Override
	public void close() throws IOException {
		synchronized (this) {
			if (m_reader != null) {
				m_reader.close();
				m_writer.close();
				m_out.close();
				m_buf.close();
				m_out = null;
				m_buf = null;
				m_reader = null;
				m_writer = null;
			}
		}
	}

	@Override
	public MessageTree findById(String messageId) throws IOException {
		int index = MessageId.parse(messageId).getIndex();

		return findByIndex(index);
	}

	public MessageTree findByIndex(int index) throws IOException {
		try {
			m_lastAccessTime = System.currentTimeMillis();

			byte[] data = m_reader.readMessage(index);
			ByteBuf buf = ByteBufAllocator.DEFAULT.buffer(data.length);
			MessageTree tree = new DefaultMessageTree();

			buf.writeBytes(data);
			m_codec.decode(buf, tree);
			return tree;
		} catch (EOFException e) {
			Cat.logError(e);
			return null;
		}
	}

	public MessageBlock flushBlock() throws IOException {
		if (m_dirty.get()) {
			synchronized (this) {
				m_out.close();
				byte[] data = m_buf.toByteArray();

				try {
					m_block.setData(data);
					m_blockSize = 0;
					m_buf.reset();
					m_out = new GZIPOutputStream(m_buf);
					m_dirty.set(false);

					return m_block;
				} finally {
					m_block = new MessageBlock(m_dataFile);
				}
			}
		}
		return null;
	}

	@Override
	public long getLastAccessTime() {
		return m_lastAccessTime;
	}

	public MessageBlockWriter getWriter() {
		return m_writer;
	}

	@Override
	public void initialize(String dataFile) throws IOException {
		m_dataFile = dataFile;

		File file = new File(m_baseDir, dataFile);

		m_writer = new MessageBlockWriter(file);
		m_reader = new MessageBlockReader(file);
		m_block = new MessageBlock(m_dataFile);
		m_buf = new ByteArrayOutputStream(16384);
		m_out = new GZIPOutputStream(m_buf);
	}

	public void setBaseDir(File baseDir) {
		m_baseDir = baseDir;
	}

	public void setMessageCodec(MessageCodec codec) {
		m_codec = codec;
	}

	public MessageBlock storeMessage(final ByteBuf buf, final MessageId id) throws IOException {
		synchronized (this) {
			int size = buf.readableBytes();

			m_dirty.set(true);
			m_lastAccessTime = System.currentTimeMillis();
			m_blockSize += size;
			m_block.addIndex(id.getIndex(), size);
			buf.getBytes(0, m_out, size); // write buffer and compress it

			if (m_blockSize >= MAX_BLOCK_SIZE) {
				return flushBlock();
			} else {
				return null;
			}
		}
	}

}


text:
@implementation UILabel (Masonry)

+(UILabel *)getLabelWithFontSize:(NSInteger)size textColor:(UIColor *)color superView:(UIView *)superView
{
    return [UILabel getLabelWithFont:[UIFont systemFontOfSize:size] textColor:color superView:superView];
}

+(UILabel *)getLabelWithFontSize:(NSInteger)size textColorHex:(NSString *)colorHex superView:(UIView *)superView
{
    return [UILabel getLabelWithFont:[UIFont systemFontOfSize:size] textColor:[UIColor colorFromHexString:colorHex] superView:superView ];
}

+(UILabel *)getLabelWithFont:(UIFont *)font textColor:(UIColor *)color superView:(UIView *)superView{
    UILabel *label = [[UILabel alloc] init];
    label.font = font;
    label.textColor = color;
    label.translatesAutoresizingMaskIntoConstraints = NO;
    [superView addSubview:label];
    return label;
}

@end


text:
package com.orasi.api.soapServices;

import org.testng.Assert;
import org.testng.annotations.Test;

import com.orasi.api.APIBaseTest;

import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.allure.annotations.Title;

public class TestSoapServiceCommands extends APIBaseTest {

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("addAttribute")
    @Test(groups = { "regression", "smoke" })
    public void addAttribute() {
        Assert.assertTrue(SoapServiceCommands.addAttribute("blah").equals("fx:addattribute;blah"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("addNode")
    @Test(groups = { "regression", "smoke" })
    public void addNode() {
        Assert.assertTrue(SoapServiceCommands.addNode("blah").equals("fx:addnode;blah"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("addNodes")
    @Test(groups = { "regression", "smoke" })
    public void addNodes() {
        Assert.assertTrue(SoapServiceCommands.addNodes("blah/blah2/blah3").equals("fx:addnodes;blah/blah2/blah3"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("addNamespace")
    @Test(groups = { "regression", "smoke" })
    public void addNamespaceNode() {
        Assert.assertTrue(SoapServiceCommands.addNamespace("blah").equals("fx:addnamespace;blah"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("getDateDefault")
    @Test(groups = { "regression", "smoke" })
    public void getDateDefault() {
        Assert.assertTrue(SoapServiceCommands.getDate().equals("fx:getdate;0"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("getDateSpecific")
    @Test(groups = { "regression", "smoke" })
    public void getDateSpecific() {
        Assert.assertTrue(SoapServiceCommands.getDate("3").equals("fx:getdate;3"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("getDateTimeDefault")
    @Test(groups = { "regression", "smoke" })
    public void getDateTimeDefault() {
        Assert.assertTrue(SoapServiceCommands.getDateTime().equals("fx:getdatetime;0"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("getDateTimeSpecific")
    @Test(groups = { "regression", "smoke" })
    public void getDateTimeSpecific() {
        Assert.assertTrue(SoapServiceCommands.getDateTime("5").equals("fx:getdatetime;5"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("getRandomAlphaNumericDefault")
    @Test(groups = { "regression", "smoke" })
    public void getRandomAlphaNumericDefault() {
        Assert.assertTrue(SoapServiceCommands.getRandomAlphaNumeric().matches("fx:randomalphanumeric;[3-9]"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("getRandomAlphaNumericSpecific")
    @Test(groups = { "regression", "smoke" })
    public void getRandomAlphaNumericSpecific() {
        Assert.assertTrue(SoapServiceCommands.getRandomAlphaNumeric("8").equals("fx:randomalphanumeric;8"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("getRandomNumberDefault")
    @Test(groups = { "regression", "smoke" })
    public void getRandomNumberDefault() {
        Assert.assertTrue(SoapServiceCommands.getRandomNumber().matches("fx:randomnumber;[3-9]"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("getRandomNumberSpecific")
    @Test(groups = { "regression", "smoke" })
    public void getRandomNumberSpecific() {
        Assert.assertTrue(SoapServiceCommands.getRandomNumber("8").equals("fx:randomnumber;8"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("getRandomStringDefault")
    @Test(groups = { "regression", "smoke" })
    public void getRandomStringDefault() {
        Assert.assertTrue(SoapServiceCommands.getRandomString().matches("fx:randomstring;[3-9]"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("getRandomStringSpecific")
    @Test(groups = { "regression", "smoke" })
    public void getRandomStringSpecific() {
        Assert.assertTrue(SoapServiceCommands.getRandomString("8").equals("fx:randomstring;8"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("removeAttribute")
    @Test(groups = { "regression", "smoke" })
    public void removeAttribute() {
        Assert.assertTrue(SoapServiceCommands.removeAttribute().equals("fx:removeattribute"));
    }

    @Features("API")
    @Stories("SoapServiceCommands")
    @Title("removeNode")
    @Test(groups = { "regression", "smoke" })
    public void removeNode() {
        Assert.assertTrue(SoapServiceCommands.removeNode().equals("fx:removenode"));
    }

}


text:
package org.yaml.snakeyaml;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;

import junit.framework.TestCase;

import org.yaml.snakeyaml.constructor.AbstractConstruct;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.Tag;

/**
 * Test Chapter 2.4 from the YAML specification
 */
public class Chapter2_4Test extends TestCase {

    @SuppressWarnings("unchecked")
    public void testExample_2_19() {
        YamlDocument document = new YamlDocument("example2_19.yaml");
        Map<String, Object> map = (Map<String, Object>) document.getNativeData();
        assertEquals(5, map.size());
        assertEquals("Expect 12345 to be an Integer.", Integer.class,
                map.get("canonical").getClass());
        assertEquals(Integer.valueOf(12345), map.get("canonical"));
        assertEquals(Integer.valueOf(12345), map.get("decimal"));
        assertEquals(Integer.valueOf(3 * 3600 + 25 * 60 + 45), map.get("sexagesimal"));
        assertEquals(Integer.valueOf(014), map.get("octal"));
        assertEquals(Integer.valueOf(0xC), map.get("hexadecimal"));
    }

    @SuppressWarnings("unchecked")
    public void testExample_2_20() {
        YamlDocument document = new YamlDocument("example2_20.yaml");
        Map<String, Object> map = (Map<String, Object>) document.getNativeData();
        assertEquals(6, map.size());
        assertEquals("Expect '1.23015e+3' to be a Double.", Double.class,
                map.get("canonical").getClass());
        assertEquals(Double.valueOf(1230.15), map.get("canonical"));
        assertEquals(Double.valueOf(12.3015e+02), map.get("exponential"));
        assertEquals(Double.valueOf(20 * 60 + 30.15), map.get("sexagesimal"));
        assertEquals(Double.valueOf(1230.15), map.get("fixed"));
        assertEquals(Double.NEGATIVE_INFINITY, map.get("negative infinity"));
        assertEquals(Double.NaN, map.get("not a number"));
    }

    @SuppressWarnings("unchecked")
    public void testExample_2_21() {
        YamlDocument document = new YamlDocument("example2_21.yaml");
        Map<String, Object> map = (Map<String, Object>) document.getNativeData();
        assertEquals(4, map.size());
        assertNull("'~' must be parsed as 'null': " + map.get(null), map.get(null));
        assertTrue((Boolean) map.get(Boolean.TRUE));
        assertFalse((Boolean) map.get(Boolean.FALSE));
        assertEquals("12345", map.get("string"));
    }

    @SuppressWarnings("unchecked")
    public void testExample_2_22() {
        YamlDocument document = new YamlDocument("example2_22.yaml");
        Map<String, Object> map = (Map<String, Object>) document.getNativeData();
        assertEquals(4, map.size());
        assertEquals("Expect '2001-12-15T02:59:43.1Z' to be a Date.", Date.class,
                map.get("canonical").getClass());
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        cal.clear();
        cal.set(Calendar.YEAR, 2001);
        cal.set(Calendar.MONTH, 11); // Java's months are zero-based...
        cal.set(Calendar.DAY_OF_MONTH, 15);
        cal.set(Calendar.HOUR_OF_DAY, 2);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 43);
        cal.set(Calendar.MILLISECOND, 100);
        Date date = cal.getTime();
        assertEquals(date, map.get("canonical"));
        assertEquals("Expect '2001-12-14t21:59:43.10-05:00' to be a Date.", Date.class,
                map.get("iso8601").getClass());
        assertEquals("Expect '2001-12-14 21:59:43.10 -5' to be a Date.", Date.class,
                map.get("spaced").getClass());
        assertEquals("Expect '2002-12-14' to be a Date.", Date.class, map.get("date").getClass());
    }

    @SuppressWarnings("unchecked")
    public void testExample_2_23_non_date() {
        try {
            YamlDocument document = new YamlDocument("example2_23_non_date.yaml");
            Map<String, Object> map = (Map<String, Object>) document.getNativeData();
            assertEquals(1, map.size());
            assertEquals("2002-04-28", map.get("not-date"));
        } catch (RuntimeException e) {
            fail("Cannot parse '!!str': 'not-date: !!str 2002-04-28'");
        }
    }

    @SuppressWarnings("unchecked")
    public void testExample_2_23_picture() {
        YamlDocument document = new YamlDocument("example2_23_picture.yaml", false);
        Map<String, Object> map = (Map<String, Object>) document.getNativeData();
        assertEquals(1, map.size());
        byte[] picture = (byte[]) map.get("picture");
        assertEquals((byte) 'G', picture[0]);
        assertEquals((byte) 'I', picture[1]);
        assertEquals((byte) 'F', picture[2]);
    }

    class SomethingConstructor extends Constructor {
        public SomethingConstructor() {
            this.yamlConstructors.put(new Tag("!something"), new ConstructSomething());
        }

        private class ConstructSomething extends AbstractConstruct {
            public Object construct(Node node) {
                // convert to upper case
                String val = (String) constructScalar((ScalarNode) node);
                return val.toUpperCase().replace('\n', ' ').trim();
            }
        }
    }

    @SuppressWarnings("unchecked")
    public void testExample_2_23() {
        YamlDocument document = new YamlDocument("example2_23.yaml", false,
                new SomethingConstructor());
        Map<String, Object> map = (Map<String, Object>) document.getNativeData();
        assertEquals(3, map.size());
        String special = (String) map.get("application specific tag");
        assertEquals("THE SEMANTICS OF THE TAG ABOVE MAY BE DIFFERENT FOR DIFFERENT DOCUMENTS.",
                special);
    }

    @SuppressWarnings("unchecked")
    public void testExample_2_25() {
        YamlDocument document = new YamlDocument("example2_25.yaml");
        Set<String> set = (Set<String>) document.getNativeData();
        assertEquals(3, set.size());
        assertTrue(set.contains("Mark McGwire"));
        assertTrue(set.contains("Sammy Sosa"));
        assertTrue(set.contains("Ken Griff"));
    }

    @SuppressWarnings("unchecked")
    public void testExample_2_26() {
        YamlDocument document = new YamlDocument("example2_26.yaml");
        Map<String, String> map = (Map<String, String>) document.getNativeData();
        assertEquals(3, map.size());
        assertTrue(map instanceof LinkedHashMap);
        assertEquals(Integer.valueOf(65), map.get("Mark McGwire"));
        assertEquals(Integer.valueOf(63), map.get("Sammy Sosa"));
        assertEquals(Integer.valueOf(58), map.get("Ken Griffy"));
        List<String> list = new ArrayList<String>();
        for (String key : map.keySet()) {
            list.add(key);
        }
        assertEquals("Mark McGwire", list.get(0));
        assertEquals("Sammy Sosa", list.get(1));
        assertEquals("Ken Griffy", list.get(2));
    }
}


text:
#include "PS4Parser.h"

enum DPADEnum {
        DPAD_UP = 0x0,
        DPAD_UP_RIGHT = 0x1,
        DPAD_RIGHT = 0x2,
        DPAD_RIGHT_DOWN = 0x3,
        DPAD_DOWN = 0x4,
        DPAD_DOWN_LEFT = 0x5,
        DPAD_LEFT = 0x6,
        DPAD_LEFT_UP = 0x7,
        DPAD_OFF = 0x8,
};

// To enable serial debugging see "settings.h"
//#define PRINTREPORT // Uncomment to print the report send by the PS4 Controller

bool PS4Parser::checkDpad(ButtonEnum b) {
        switch (b) {
                case UP:
                        return ps4Data.btn.dpad == DPAD_LEFT_UP || ps4Data.btn.dpad == DPAD_UP || ps4Data.btn.dpad == DPAD_UP_RIGHT;
                case RIGHT:
                        return ps4Data.btn.dpad == DPAD_UP_RIGHT || ps4Data.btn.dpad == DPAD_RIGHT || ps4Data.btn.dpad == DPAD_RIGHT_DOWN;
                case DOWN:
                        return ps4Data.btn.dpad == DPAD_RIGHT_DOWN || ps4Data.btn.dpad == DPAD_DOWN || ps4Data.btn.dpad == DPAD_DOWN_LEFT;
                case LEFT:
                        return ps4Data.btn.dpad == DPAD_DOWN_LEFT || ps4Data.btn.dpad == DPAD_LEFT || ps4Data.btn.dpad == DPAD_LEFT_UP;
                default:
                        return false;
        }
}

bool PS4Parser::getButtonPress(ButtonEnum b) {
        if (b <= LEFT) // Dpad
                return checkDpad(b);
        else
                return ps4Data.btn.val & (1UL << pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]));
}

bool PS4Parser::getButtonClick(ButtonEnum b) {
        uint32_t mask = 1UL << pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]);
        bool click = buttonClickState.val & mask;
        buttonClickState.val &= ~mask; // Clear "click" event
        return click;
}

uint8_t PS4Parser::getAnalogButton(ButtonEnum b) {
        if (b == L2) // These are the only analog buttons on the controller
                return ps4Data.trigger[0];
        else if (b == R2)
                return ps4Data.trigger[1];
        return 0;
}

uint8_t PS4Parser::getAnalogHat(AnalogHatEnum a) {
        return ps4Data.hatValue[(uint8_t)a];
}

void PS4Parser::Parse(uint8_t len, uint8_t *buf) {
        if (len > 1 && buf)  {
#ifdef PRINTREPORT
                Notify(PSTR("\r\n"), 0x80);
                for (uint8_t i = 0; i < len; i++) {
                        D_PrintHex<uint8_t > (buf[i], 0x80);
                        Notify(PSTR(" "), 0x80);
                }
#endif

                if (buf[0] == 0x01) // Check report ID
                        memcpy(&ps4Data, buf + 1, min((uint8_t)(len - 1), sizeof(ps4Data)));
                else if (buf[0] == 0x11) { // This report is send via Bluetooth, it has an offset of 2 compared to the USB data
                        if (len < 4) {
#ifdef DEBUG_USB_HOST
                                Notify(PSTR("\r\nReport is too short: "), 0x80);
                                D_PrintHex<uint8_t > (len, 0x80);
#endif
                                return;
                        }
                        memcpy(&ps4Data, buf + 3, min((uint8_t)(len - 3), sizeof(ps4Data)));
                } else {
#ifdef DEBUG_USB_HOST
                        Notify(PSTR("\r\nUnknown report id: "), 0x80);
                        D_PrintHex<uint8_t > (buf[0], 0x80);
#endif
                        return;
                }

                if (ps4Data.btn.val != oldButtonState.val) { // Check if anything has changed
                        buttonClickState.val = ps4Data.btn.val & ~oldButtonState.val; // Update click state variable
                        oldButtonState.val = ps4Data.btn.val;

                        // The DPAD buttons does not set the different bits, but set a value corresponding to the buttons pressed, we will simply set the bits ourself
                        uint8_t newDpad = 0;
                        if (checkDpad(UP))
                                newDpad |= 1 << UP;
                        if (checkDpad(RIGHT))
                                newDpad |= 1 << RIGHT;
                        if (checkDpad(DOWN))
                                newDpad |= 1 << DOWN;
                        if (checkDpad(LEFT))
                                newDpad |= 1 << LEFT;
                        if (newDpad != oldDpad) {
                                buttonClickState.dpad = newDpad & ~oldDpad; // Override values
                                oldDpad = newDpad;
                        }
                }
        }

        if (ps4Output.reportChanged)
                sendOutputReport(&ps4Output); // Send output report
}

void PS4Parser::Reset() {
        uint8_t i;
        for (i = 0; i < sizeof(ps4Data.hatValue); i++)
                ps4Data.hatValue[i] = 127; // Center value
        ps4Data.btn.val = 0;
        oldButtonState.val = 0;
        for (i = 0; i < sizeof(ps4Data.trigger); i++)
                ps4Data.trigger[i] = 0;
        for (i = 0; i < sizeof(ps4Data.xy)/sizeof(ps4Data.xy[0]); i++) {
                for (uint8_t j = 0; j < sizeof(ps4Data.xy[0].finger)/sizeof(ps4Data.xy[0].finger[0]); j++)
                        ps4Data.xy[i].finger[j].touching = 1; // The bit is cleared if the finger is touching the touchpad
        }

        ps4Data.btn.dpad = DPAD_OFF;
        oldButtonState.dpad = DPAD_OFF;
        buttonClickState.dpad = 0;
        oldDpad = 0;

        ps4Output.bigRumble = ps4Output.smallRumble = 0;
        ps4Output.r = ps4Output.g = ps4Output.b = 0;
        ps4Output.flashOn = ps4Output.flashOff = 0;
        ps4Output.reportChanged = false;
};


text:
#ifndef CAF_TYPED_ACTOR_HPP
#define CAF_TYPED_ACTOR_HPP

#include "caf/intrusive_ptr.hpp"

#include "caf/actor_addr.hpp"
#include "caf/actor_cast.hpp"
#include "caf/replies_to.hpp"
#include "caf/abstract_actor.hpp"
#include "caf/stateful_actor.hpp"
#include "caf/typed_behavior.hpp"
#include "caf/typed_response_promise.hpp"

namespace caf {

class actor_addr;
class local_actor;

struct invalid_actor_addr_t;

template <class... Sigs>
class typed_event_based_actor;

namespace io {
namespace experimental {

template <class... Sigs>
class typed_broker;

} // namespace experimental
} // namespace io

/// Identifies a statically typed actor.
/// @tparam Sigs Signature of this actor as `replies_to<...>::with<...>`
///              parameter pack.
template <class... Sigs>
class typed_actor : detail::comparable<typed_actor<Sigs...>>,
                    detail::comparable<typed_actor<Sigs...>, actor_addr>,
                    detail::comparable<typed_actor<Sigs...>, invalid_actor_t>,
                    detail::comparable<typed_actor<Sigs...>,
                                       invalid_actor_addr_t> {
 public:
  static_assert(sizeof...(Sigs) > 0, "Empty typed actor handle");

  // grant access to private ctor
  friend class local_actor;

  // friend with all possible instantiations
  template <class...>
  friend class typed_actor;

  // allow conversion via actor_cast
  template <class T, typename U>
  friend T actor_cast(const U&);

  /// Creates a new `typed_actor` type by extending this one with `Es...`.
  template <class... Es>
  using extend = typed_actor<Sigs..., Es...>;

  /// Identifies the behavior type actors of this kind use
  /// for their behavior stack.
  using behavior_type = typed_behavior<Sigs...>;

  /// Identifies pointers to instances of this kind of actor.
  using pointer = typed_event_based_actor<Sigs...>*;

  /// Identifies the base class for this kind of actor.
  using base = typed_event_based_actor<Sigs...>;

  /// Identifies pointers to brokers implementing this interface.
  using broker_pointer = io::experimental::typed_broker<Sigs...>*;

  /// Identifies the base class of brokers implementing this interface.
  using broker_base = io::experimental::typed_broker<Sigs...>;

  /// Stores the template parameter pack.
  using signatures = detail::type_list<Sigs...>;

  /// Identifies the base class for this kind of actor with actor.
  template <class State>
  using stateful_base = stateful_actor<State, base>;

  /// Identifies the base class for this kind of actor with actor.
  template <class State>
  using stateful_pointer = stateful_actor<State, base>*;

  /// Identifies the broker_base class for this kind of actor with actor.
  template <class State>
  using stateful_broker_base =
    stateful_actor<State, broker_base>;

  /// Identifies the broker_base class for this kind of actor with actor.
  template <class State>
  using stateful_broker_pointer =
    stateful_actor<State, broker_base>*;

  typed_actor() = default;
  typed_actor(typed_actor&&) = default;
  typed_actor(const typed_actor&) = default;
  typed_actor& operator=(typed_actor&&) = default;
  typed_actor& operator=(const typed_actor&) = default;

  template <class TypedActor,
            class Enable =
              typename std::enable_if<
                detail::tlf_is_subset(signatures(),
                                      typename TypedActor::signatures())
              >::type>
  typed_actor(const TypedActor& other) : ptr_(other.ptr_) {
    // nop
  }

  // allow `handle_type{this}` for typed actors
  template <class TypedActor,
            class Enable =
              typename std::enable_if<
                detail::tlf_is_subset(signatures(),
                                      typename TypedActor::signatures())
              >::type>
  typed_actor(TypedActor* ptr) : ptr_(ptr) {
    // nop
  }

  template <class TypedActor,
            class Enable =
              typename std::enable_if<
                detail::tlf_is_subset(signatures(),
                                      typename TypedActor::signatures())
              >::type>
  typed_actor& operator=(const TypedActor& other) {
    ptr_ = other.ptr_;
    return *this;
  }

  template <class Impl,
            class Enable =
              typename std::enable_if<
                detail::tlf_is_subset(signatures(),
                                      typename Impl::signatures())
              >::type>
  typed_actor(intrusive_ptr<Impl> other) : ptr_(std::move(other)) {
    // nop
  }

  /// Queries the address of the stored actor.
  actor_addr address() const noexcept {
    return ptr_ ? ptr_->address() : actor_addr();
  }

  /// Returns `*this != invalid_actor`.
  explicit operator bool() const noexcept {
    return static_cast<bool>(ptr_);
  }

  /// Returns `*this == invalid_actor`.
  bool operator!() const noexcept {
    return !ptr_;
  }

  /// Returns whether this is an handle to a remote actor.
  bool is_remote() const noexcept {
    return ptr_ ? ptr_->is_remote() : false;
  }

  /// Returns the ID of this actor.
  actor_id id() const noexcept {
    return ptr_ ? ptr_->id() : invalid_actor_id;
  }

  /// Exchange content of `*this` and `other`.
  void swap(actor& other) noexcept {
    ptr_.swap(other.ptr_);
  }

  /// Returns the interface definition for this actor handle.
  static std::set<std::string> message_types() {
    return std::set<std::string>{Sigs::static_type_name()...};
  }

  /// @cond PRIVATE

  abstract_actor* operator->() const noexcept {
    return ptr_.get();
  }

  abstract_actor& operator*() const noexcept {
    return *ptr_.get();
  }

  intptr_t compare(const actor_addr& rhs) const noexcept {
    return address().compare(rhs);
  }

  intptr_t compare(const typed_actor& other) const noexcept {
    return compare(other.address());
  }

  intptr_t compare(const invalid_actor_addr_t&) const noexcept {
    return ptr_ ? 1 : 0;
  }

  /// @endcond

private:
  abstract_actor* get() const {
    return ptr_.get();
  }

  typed_actor(abstract_actor* ptr) : ptr_(ptr) {
    // nop
  }

  abstract_actor_ptr ptr_;
};

} // namespace caf

// allow typed_actor to be used in hash maps
namespace std {
template <class... Sigs>
struct hash<caf::typed_actor<Sigs...>> {
  size_t operator()(const caf::typed_actor<Sigs...>& ref) const {
    return ref ? static_cast<size_t>(ref->id()) : 0;
  }
};
} // namespace std

#endif // CAF_TYPED_ACTOR_HPP


text:
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]][link-license]
[![Build Status][ico-travis]][link-travis]
[![Coverage Status][ico-scrutinizer]][link-scrutinizer]
[![Quality Score][ico-code-quality]][link-code-quality]
[![Total Downloads][ico-downloads]][link-downloads]

Refinery is an extension and a command line interface of [Migrations Class](https://www.codeigniter.com/user_guide/libraries/migration.html) for the [Codeigniter](https://codeigniter.com/) framework. It uses the [Describe](https://roug.in/describe/) library for retrieving the database tables and as the basis for code generation.

## Installation

Install `Refinery` through [Composer](https://getcomposer.org/):

``` bash
$ composer require rougin/refinery
```

## Basic Usage

### Creating a table

``` bash
$ vendor/bin/refinery create create_users_table
"20180621090905_create_users_table.php" has been created.
```

``` php
// application/migrations/20180621090905_create_users_table.php

defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_create_users_table extends CI_Migration
{
    public function up()
    {
        $this->dbforge->add_field('id');

        $this->dbforge->create_table('users');
    }

    public function down()
    {
        $this->dbforge->drop_table('users');
    }
}
```

Use `--from-database` option to create a migration from an existing database table.

``` sql
CREATE TABLE IF NOT EXISTS `user` (
    `id` int(10) NOT NULL AUTO_INCREMENT,
    `name` varchar(200) NOT NULL,
    `age` int(2) NOT NULL,
    `gender` varchar(10) NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
```

``` bash
$ vendor/bin/refinery create create_users_table --from-database
"20180621090905_create_users_table.php" has been created.
```

``` php
// application/migrations/20180621090905_create_users_table.php

defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_create_users_table extends CI_Migration
{
    public function up()
    {
        $this->dbforge->add_column('users', array(
            'gender' => array(
                'type' => 'string',
                'constraint' => 10,
                'auto_increment' => FALSE,
                'default' => '',
                'null' => FALSE,
                'unsigned' => FALSE
            ),
        ));

        $this->dbforge->add_column('users', array(
            'age' => array(
                'type' => 'integer',
                'constraint' => 2,
                'auto_increment' => FALSE,
                'default' => '',
                'null' => FALSE,
                'unsigned' => FALSE
            ),
        ));

        $this->dbforge->add_column('users', array(
            'name' => array(
                'type' => 'string',
                'constraint' => 200,
                'auto_increment' => FALSE,
                'default' => '',
                'null' => FALSE,
                'unsigned' => FALSE
            ),
        ));

        $this->dbforge->add_column('users', array(
            'id' => array(
                'type' => 'integer',
                'constraint' => 10,
                'auto_increment' => TRUE,
                'default' => '',
                'null' => FALSE,
                'unsigned' => FALSE
            ),
        ));

        $this->dbforge->create_table('users');
    }

    public function down()
    {
        $this->dbforge->drop_table('users');
    }
}
```

### Creating a column inside a table

```bash
$ vendor/bin/refinery create add_name_in_users_table
"20180621090953_add_name_in_users_table.php" has been created.
```

``` php
// application/migrations/20180621090953_add_name_in_users_table.php

defined('BASEPATH') OR exit('No direct script access allowed');

class Migration_add_name_in_users_table extends CI_Migration
{
    public function up()
    {
        $this->dbforge->add_column('users', array(
            'name' => array(
                'type' => 'VARCHAR',
                'constraint' => 50,
                'auto_increment' => FALSE,
                'default' => '',
                'null' => FALSE,
                'unsigned' => FALSE
            ),
        ));
    }

    public function down()
    {
        $this->dbforge->drop_column('users', 'name');
    }
}
```

#### Available keywords

| Command | Description |
| ------- | ----------- |
| `create` | creates new table (`create_users_table`) |
| `add` | adds new column for a specific table (`add_username_in_users_table`) |
| `delete` | deletes specified column from table (`delete_created_at_in_users_table`) |
| `modify` | updates the specified column from table (`modify_name_in_users_table`) |

### Migrate, rollback and reset

```bash
$ vendor/bin/refinery migrate
Migrating: 20180621090905_create_users_table
Migrated:  20180621090905_create_users_table
Migrating: 20180621090953_add_name_in_users_table
Migrated:  20180621090953_add_name_in_users_table
```

```bash
$ vendor/bin/refinery rollback
Rolling back: 20180621090953_add_name_in_users_table
Rolled back:  20180621090953_add_name_in_users_table
```

**NOTE**: You can also specify the version you want to rollback on using the `--version` option. (e.g: `--version=20180621090905`)

```bash
$ vendor/bin/refinery rollback 20180621090905
Rolling back: 20180621090905_create_users_table
Rolled back:  20180621090905_create_users_table
```

```bash
$ vendor/bin/refinery reset
Rolling back: 20180621090953_add_name_in_users_table
Rolled back:  20180621090953_add_name_in_users_table
Rolling back: 20180621090905_create_users_table
Rolled back:  20180621090905_create_users_table
```

## Changelog

Please see [CHANGELOG][link-changelog] for more information what has changed recently.

## Testing

``` bash
$ composer test
```

## Credits

- [All contributors][link-contributors]

## License

The MIT License (MIT). Please see [LICENSE][link-license] for more information.

[ico-code-quality]: https://img.shields.io/scrutinizer/g/rougin/refinery.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/rougin/refinery.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/rougin/refinery.svg?style=flat-square
[ico-travis]: https://img.shields.io/travis/rougin/refinery/master.svg?style=flat-square
[ico-version]: https://img.shields.io/packagist/v/rougin/refinery.svg?style=flat-square

[link-changelog]: https://github.com/rougin/refinery/blob/master/CHANGELOG.md
[link-code-quality]: https://scrutinizer-ci.com/g/rougin/refinery
[link-contributors]: https://github.com/rougin/refinery/contributors
[link-downloads]: https://packagist.org/packages/rougin/refinery
[link-license]: https://github.com/rougin/refinery/blob/master/LICENSE.md
[link-packagist]: https://packagist.org/packages/rougin/refinery
[link-scrutinizer]: https://scrutinizer-ci.com/g/rougin/refinery/code-structure
[link-travis]: https://travis-ci.org/rougin/refinery