text:
(function(root, factory) {
    "use strict";

    // CommonJS module is defined
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory(
            require('jquery'),
            require('routing'),
            require('twig'),
            require('ekyna-modal'),
            require('ekyna-form'),
            require('ekyna-media-player'),
            require('ekyna-string'),
            require('ekyna-media-thumb'),
            require('fancytree'),
            require('fancybox')
        );
    }
    // AMD module is defined
    else if (typeof define === 'function' && define.amd) {
        define('ekyna-media-browser',
            ['jquery', 'routing', 'twig', 'ekyna-modal', 'ekyna-form', 'ekyna-media-player',
                'ekyna-string', 'ekyna-media-thumb', 'fancytree', 'fancybox'],
            function($, Router, Twig, Modal, Form, Player) {
                return factory($, Router, Twig, Modal, Form, Player);
        });
    } else {
        // planted over the root!
        root.EkynaMediaBrowser = factory(
            root.jQuery,
            root.Routing,
            root.Twig,
            root.EkynaModal,
            root.EkynaForm, // TODO
            root.EkynaMediaPlayer
        );
    }

}(this, function($, Router, Twig, Modal, Form, Player) {
    "use strict";

    // http://james.padolsey.com/javascript/sorting-elements-with-jquery/
    $.fn.sortElements = (function(){
        var sort = [].sort;
        return function(comparator, getSortable) {
            getSortable = getSortable || function(){return this;};
            var placements = this.map(function(){
                var sortElement = getSortable.call(this),
                    parentNode = sortElement.parentNode,
                    nextSibling = parentNode.insertBefore(
                        document.createTextNode(''),
                        sortElement.nextSibling
                    );
                return function() {
                    if (parentNode === this) {
                        throw new Error(
                            "You can't sort elements if any one is a descendant of another."
                        );
                    }
                    parentNode.insertBefore(this, nextSibling);
                    parentNode.removeChild(nextSibling);
                };
            });
            return sort.call(this, comparator).each(function(i){
                placements[i].call(getSortable.call(this));
            });
        };
    })();

    var defaultConfig = {
        mode:    "browse",
        //path:    "",
        folderId: null,
        types:   [],
        sortBy:  "filename",
        sortDir: "asc",
        search:  "",
        debug:   true
    };

    var EkynaMediaBrowser = function(selector) {
        this.$browser = $(selector);
        this.config = $.extend({}, defaultConfig, this.$browser.data('config'));
        this.$tree = this.$browser.find('.media-browser-tree');
        this.$content = this.$browser.find('.media-browser-content');
        this.$controls = this.$browser.find('.media-browser-controls');
        this.modal = new Modal();
        this.busy = false;
        this.folderId = null;
        this.browseXhr = null;
    };

    EkynaMediaBrowser.prototype = {
        constructor: EkynaMediaBrowser,
        init: function(config) {
            this.config = $.extend({}, this.config, config || {});
            if (-1 == $.inArray(this.config.mode, ['browse', 'single_selection', 'multiple_selection', 'tinymce'])) {
                throw 'Unexpected browser mode "' + this.config.mode + '".';
            }

            this.initTree();

            // Disable controls until the user select a folder
            this.$controls.find('button, label').addClass('disabled').prop('disabled', true);
            this.$controls.find('input').prop('disabled', true);
        },
        setBusy: function(busy) {
            if (busy && this.browseXhr) {
                this.browseXhr.abort();
            }
            if (this.busy == busy) {
                return;
            }
            this.busy = busy;
            if (this.busy) {
                this.clearHandlers();
                this.$controls.find('button, label').addClass('disabled').prop('disabled', true);
                this.$controls.find('input').prop('disabled', true);
                this.$controls.find('[data-role="refresh"] span.glyphicon').addClass('glyphicon-refresh-animate');
            } else {
                this.initHandlers();
                this.$controls.find('button, label').removeClass('disabled').prop('disabled', false);
                this.$controls.find('input').prop('disabled', false);
                this.$controls.find('[data-role="refresh"] span.glyphicon').removeClass('glyphicon-refresh-animate');
            }
        },
        initHandlers: function () {
            var that = this;

            // Create/import buttons
            this.$controls.on('click', '[data-role="create"]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                that.newMedia();
            });
            this.$controls.on('click', '[data-role="import"]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                that.importMedia();
            });

            // Refresh button
            this.$controls.on('click', '[data-role="refresh"]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                that.browse();
            });

            // Filter button
            this.$controls.on('change', 'input[name="filters[]"]', function (e) {
                e.preventDefault();
                e.stopPropagation();
                that.filterList();
            });

            // Search input
            var searchTimeout = null;
            this.$controls.on('keyup', 'input[data-role="search"]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(function() { that.filterList(); }, 1500);
            });
            this.$controls.on('click', 'button[data-role="clear-search"]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                clearTimeout(searchTimeout);
                that.$controls.find('input[data-role="search"]').val('');
                that.filterList();
            });

            // Sort button
            this.$controls.on('click', '[data-role="sort"]', function(e) {
                e.preventDefault();
                var $input = $(e.currentTarget).find('input');
                var $icon = $(e.currentTarget).find('span.glyphicon');
                if ($input.is(':checked')) {
                    var icon = $input.val() == 'filename' ? 'glyphicon-sort-by-alphabet' : 'glyphicon-sort-by-attributes';
                    if ($input.data('dir') == 'asc') {
                        $icon.removeClass(icon).addClass(icon + '-alt');
                        $input.data('dir', 'desc');
                    } else {
                        $icon.removeClass(icon + '-alt').addClass(icon);
                        $input.data('dir', 'asc');
                    }
                    $input.trigger('change');
                }
            });
            this.$controls.on('change', 'input[name="sort"]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                that.sortList();
            });

            // Media selection
            this.$content.on('click', '.media-thumb [data-role="select"]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                var $element = $(e.currentTarget).parents('.media-thumb').eq(0);
                if (that.config.mode == 'tinymce' && parent.tinymce && parent.tinymce.activeEditor) {
                    parent.tinymce.activeEditor.windowManager.getParams().setUrl(
                        $element.data('media').front
                    );
                    parent.tinymce.activeEditor.windowManager.close();
                } else if (that.config.mode == 'single_selection') {
                    var event = jQuery.Event('ekyna.media-browser.selection');
                    event.media = $element.data('media');
                    $(that).trigger(event);
                } else if (that.config.mode == 'multiple_selection') {
                    var $checkbox = $element.find('input[type="checkbox"]');
                    $checkbox.prop('checked', !$checkbox.is(':checked'));
                }
            });

            // Media show
            this.$content.on('click', '.media-thumb [data-role="show"]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                var $media = $(e.currentTarget).parents('.media-thumb');
                that.showMedia($media);
            });

            // Media download
            this.$content.on('click', '.media-thumb [data-role="download"]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                var $media = $(e.currentTarget).parents('.media-thumb');
                that.downloadMedia($media);
            });

            // Media edit
            this.$content.on('click', '.media-thumb [data-role="edit"]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                var $media = $(e.currentTarget).parents('.media-thumb');
                that.editMedia($media);
            });

            // Media remove
            this.$content.on('click', '.media-thumb [data-role="delete"]', function(e) {
                e.preventDefault();
                e.stopPropagation();
                var $media = $(e.currentTarget).parents('.media-thumb');
                that.removeMedia($media);
            });
        },
        clearHandlers: function () {
            this.$controls.off();
            this.$content.off();
        },
        browse: function(id) {
            var that = this;

            that.$content.empty();
            this.folderId = id || this.folderId;

            if (this.folderId) {
                that.setBusy(true);
                that.browseXhr = $.ajax({
                    url: Router.generate('ekyna_media_browser_admin_list_media', {'id': this.folderId}),
                    method: 'GET',
                    dataType: 'json',
                    data: {types: that.config.types}
                })
                .done(function (d) {
                    if (d.error) {
                        alert(d.message);
                        return;
                    }
                    if (d.hasOwnProperty('medias')) {
                        var selector = false;
                        if (that.config.mode == 'multiple_selection') {
                            selector = true;
                        }
                        var controls = [
                            {role: 'show', icon: 'play'},
                            {role: 'edit', icon: 'pencil'},
                            {role: 'delete', icon: 'trash'},
                            {role: 'download', icon: 'download'}
                        ];
                        $(d['medias']).each(function (index, media) {
                            $(Twig.render(media_thumb_template, {media: media, controls: controls, selector: selector}))
                                .data('media', media)
                                .appendTo(that.$content)
                                .draggable({
                                    revert: "invalid",
                                    cursorAt: { top: -5, left: -5 },
                                    appendTo: that.$browser,
                                    delay: 200,
                                    containement: that.$browser,
                                    scroll: false,
                                    connectToFancytree: true,
                                    helper: function(e) {
                                        return $(e.currentTarget).clone();
                                    }
                                });
                        });
                        that.sortList();
                        that.filterList();
                    }
                    that.browseXhr = null;
                })
                .fail(function () {
                    // TODO ?
                })
                .always(function() {
                    that.setBusy(false);
                });
            }
        },
        openModal: function(options) {
            var settings = $.extend({}, {
                url: null,
                onData: function() {},
                onShow: function(data) {},
                onHide: function() { that.setBusy(false); }
            }, options);

            if (!settings.url) {
                throw "Modal url is not defined";
            }

            var that = this;
            that.setBusy(true);

            var form;
            that.modal = new Modal();
            $(that.modal).on('ekyna.modal.content', function (e) {
                settings.onShow(e);
                if (form) {
                    form.destroy();
                    form = null;
                }
                if (e.contentType == 'form') {
                    form = Form.create(e.content);
                    form.init();
                } else if (e.contentType == 'data') {
                    settings.onData(e.content);
                    that.modal.getDialog().close();
                    that.browse();
                }
            });

            $(that.modal).on('ekyna.modal.button_click', function (e) {
                if (e.buttonId == 'submit' && form) {
                    form.save();
                    setTimeout(function() {
                        form.getElement().ajaxSubmit({
                            dataType: 'xml',
                            success: function(response) {
                                form.destroy();
                                form = null;
                                that.modal.handleResponse(response);
                            }
                        });
                    }, 100);
                }
            });

            $(that.modal).on('ekyna.modal.load_fail', function () {
                that.setBusy(false);
            });

            that.modal.getDialog().onHide(function() {
                settings.onHide();
                if (form) {
                    form.destroy();
                    form = null;
                }
            });

            that.modal.load({url: settings.url});
        },
        newMedia: function() {
            this.openModal({
                url: Router.generate(
                    'ekyna_media_browser_admin_create_media',
                    {'id': this.folderId}
                )
            });
        },
        importMedia: function() {
            this.openModal({
                url: Router.generate(
                    'ekyna_media_browser_admin_import_media',
                    {'id': this.folderId}
                )
            });
        },
        showMedia: function($media) {
            if ($media.data('media').type == 'file' || $media.data('media').type == 'file') {
                this.downloadMedia($media);
                return;
            }
            var params = {
                href        : $media.data('media').front,
                maxWidth    : 1200,
                //maxHeight   : 600,
                fitToView   : false,
                width       : '90%',
                height      : '90%',
                autoSize    : false,
                closeClick  : false,
                openEffect  : 'none',
                closeEffect : 'none',
                padding     : 0
            };
            if ($media.data('media').type == 'image') {
                params.type  = 'image';
            } else {
                params.type = 'ajax';
                params.beforeShow = function() {
                    Player.init($('.fancybox-inner'));
                };
                params.beforeClose = function() {
                    Player.destroy($('.fancybox-inner'));
                };
            }
            $.fancybox(params);
        },
        editMedia: function($media) {
            var that = this;
            this.openModal({
                url: Router.generate(
                    'ekyna_media_media_admin_edit',
                    {'mediaId': $media.data('media').id}
                )/*,
                TODO onData: function(data) {
                    if (data.hasOwnProperty('success') && data.success) {
                        var event = jQuery.Event('ekyna.media-browser.media_update');
                        event.media = $media.data('media');
                        $(that).trigger(event);
                    }
                }*/
            });
        },
        removeMedia: function($media) {
            var that = this;
            this.openModal({
                // TODO modal size
                url: Router.generate(
                    'ekyna_media_media_admin_remove',
                    {'mediaId': $media.data('media').id}
                ),
                onData: function(data) {
                    if (data.hasOwnProperty('success') && data.success) {
                        var event = jQuery.Event('ekyna.media-browser.media_delete');
                        event.media = $media.data('media');
                        $(that).trigger(event);
                    }
                }
            });
        },
        downloadMedia: function($media) {
            var url = Router.generate('ekyna_media_download', {'key': $media.data('media').path});
            window.open(url,'_blank');
        },
        filterList: function() {
            var filters = this.$controls.find('input[name="filters[]"]:checked').map(function(_, el) {
                return $(el).val()
            }).get();
            var search = this.$controls.find('input[name="search"]').val();
            if (filters.length > 0 || search.length > 0) {
                var searchRegex = new RegExp(search.removeDiatrics().escapeRegExp(), 'i');
                this.$content.find('.media-thumb').each(function(i, media) {
                    var $element = $(media);
                    var type = $element.data('media').type;
                    if (filters.length > 0) {
                        if (0 > $.inArray(type, filters)) {
                            $element.hide();
                        } else {
                            $element.show();
                        }
                    }
                    if (search.length > 0) {
                        if (searchRegex.test($element.data('media').title.removeDiatrics())
                            || searchRegex.test($element.data('media').filename.removeDiatrics())) {
                            $element.show();
                        } else {
                            $element.hide();
                        }
                    }
                });
            } else {
                this.$content.find('.media-thumb').show();
            }
        },
        sortList: function() {
            var $input = $(this.$controls.find('input[name="sort"]:checked'));
            var prop = $input.val();
            var dir = $input.data('dir') == 'asc' ? 1 : -1;
            this.$content.find('.media-thumb').sortElements(function(a, b) {
                return $(a).data('media')[prop] > $(b).data('media')[prop] ? dir : -dir;
            });
        },
        getSelection: function() {
            if (this.config.mode != 'multiple_selection') {
                return [];
            }
            var result = [];
            this.$content.find('input[name="thumb_selection[]"]:checked').each(function(i, input) {
                result.push($(input).closest('.media-thumb').data('media'));
            });
            return result;
        },
        initTree: function() {
            var that = this;
            this.$tree.fancytree({
                source: {
                    url: Router.generate('ekyna_media_browser_admin_list', that.config.folderId ? {folderId: that.config.folderId} : {})
                },
                activeVisible: true,
                minExpandLevel: 2,
                selectMode: 1,
                extensions: ["edit", "dnd"],
                init: function(event, data) {
                    var node = data.tree.getActiveNode();
                    if (node)  {
                        that.browse(node.key);
                    }
                },
                activate: function(event, data) {
                    that.browse(data.node.key);
                },
                dnd: {
                    preventVoidMoves: true,
                    preventRecursiveMoves: true,
                    autoExpandMS: 400,
                    dragStart: function(node) { // , data
                        return node.data.level > 0;
                    },
                    dragEnter: function(node, data) {
                        // return ["before", "after"];
                        /*if( !data.otherNode ) {
                            return ["over"];
                        }
                        if (node.data.level === 0) {
                            return ["over"];
                        }
                        return true;*/
                        return ["over"];
                    },
                    dragDrop: function(refNode, data) {
                        that.setBusy(true);
                        if( !data.otherNode ) { // It's a non-tree draggable
                            var $draggable = $(data.draggable.element);
                            if ($draggable.hasClass('media-thumb')) {
                                $.ajax({
                                    url: Router.generate('ekyna_media_browser_admin_move_media', {
                                        'id': refNode.key,
                                        'mediaId': $draggable.data('media').id
                                    }),
                                    method: 'POST',
                                    dataType: 'json'
                                })
                                .done(function () {
                                    that.browse();
                                })
                                .fail(function () {
                                    that.setBusy(false);
                                });
                            }
                        } else {
                            var node = data.otherNode;
                            $.ajax({
                                url: Router.generate('ekyna_media_browser_admin_move', {'id': node.key}),
                                data: {
                                    'reference': refNode.key,
                                    'mode': data.hitMode
                                },
                                method: 'POST',
                                dataType: 'json'
                            })
                            .done(function (d) {
                                if (d.error) {
                                    alert(d.message);
                                    return;
                                }
                                node.moveTo(refNode, data.hitMode);
                            })
                            .fail(function () {
                                that.setBusy(false);
                            });
                        }
                    }
                },
                edit: {
                    triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"],
                    adjustWidthOfs: 4,
                    beforeEdit: function(event, data){
                        return data.node.data.level > 0;
                    },
                    /*edit: function(event, data){
                     // Editor was opened (available as data.input)
                     },*/
                    beforeClose: function(event, data){
                        return data.input.val().length > 0;
                    },
                    save: function(event, data){
                        that.setBusy(true);
                        var node = data.node;
                        $.ajax({
                            url: Router.generate('ekyna_media_browser_admin_rename', {'id': node.key}),
                            data : { 'name' : data.input.val() },
                            method: 'POST',
                            dataType: 'json'
                        })
                        .done(function (d) {
                            if (d.error) {
                                node.setTitle(data.orgTitle);
                                alert(d.message);
                                return;
                            }
                            node.setTitle(d.name);
                            node.setActive();
                        })
                        .fail(function () {
                            node.setTitle(data.orgTitle);
                        })
                        .always(function(){
                            $(data.node.span).removeClass("pending");
                            that.setBusy(false);
                        });
                        return true;
                    },
                    close: function(event, data){
                        if( data.save ) {
                            $(data.node.span).addClass("pending");
                        }
                    }
                }
            });

            var createNode = function(node, mode) {
                that.setBusy(true);
                mode = mode || "child";
                $.ajax({
                    url: Router.generate('ekyna_media_browser_admin_create', {'id': node.key}),
                    data : {
                        'mode' : mode
                    },
                    method: 'POST',
                    dataType: 'json'
                })
                .done(function (d) {
                    if (d.error) {
                        alert(d.message);
                        return;
                    }
                    node.editCreateNode(mode, d.node);
                })
                .always(function () {
                    that.setBusy(false);
                });
            };

            var removeNode = function(node) {
                that.setBusy(true);
                var message = 'Êtes-vous sûr de vouloir supprimer le dossier "' + node.title + '"';
                if (node.children && node.children.length) {
                    message = message + ' et tous ses sous-dossiers';
                }
                message = message + ' ?';
                if (confirm(message)) {
                    $.ajax({
                        url: Router.generate('ekyna_media_browser_admin_delete', {'id': node.key}),
                        method: 'POST',
                        dataType: 'json'
                    })
                    .done(function (d) {
                        if (d.error) {
                            alert(d.message);
                            return;
                        }
                        var refNode = node.getNextSibling() || node.getPrevSibling() || node.getParent();
                        node.remove();
                        if (refNode) {
                            refNode.setActive();
                        }
                    })
                    .always(function () {
                        that.setBusy(false);
                    });
                }
            };

            this.$tree.on("nodeCommand", function(event, data){
                var node = $(this).fancytree("getTree").getActiveNode();

                switch( data.cmd ) {
                    case "rename":
                        node.editStart();
                        break;
                    case "remove":
                        removeNode(node);
                        break;
                    case "addChild":
                        createNode(node, "child");
                        break;
                    case "addSibling":
                        createNode(node, "after");
                        break;
                    default:
                        alert("Unhandled command: " + data.cmd);
                        return;
                }
            });

            /*
             * Context menu (https://github.com/mar10/jquery-ui-contextmenu)
             */
            this.$tree.contextmenu({
                delegate: "span.fancytree-node",
                menu: [
                    {title: "Modifier", cmd: "rename", uiIcon: "ui-icon-pencil" },
                    {title: "Supprimer", cmd: "remove", uiIcon: "ui-icon-trash" },
                    /*{title: "----"},*/
                    {title: "Ajouter suivant", cmd: "addSibling", uiIcon: "ui-icon-plus" },
                    {title: "Ajouter enfant", cmd: "addChild", uiIcon: "ui-icon-arrowreturn-1-e" }
                ],
                beforeOpen: function(event, ui) {
                    var node = $.ui.fancytree.getNode(ui.target);
                    node.setActive();
                    $(that.$tree)
                        .contextmenu("showEntry", "addSibling", node.data.level > 0)
                        .contextmenu("showEntry", "rename", node.data.level > 0)
                        .contextmenu("showEntry", "remove", node.data.level > 0)
                    ;
                },
                select: function(event, ui) {
                    var that = this;
                    // delay the event, so the menu can close and the click event does
                    // not interfere with the edit control
                    setTimeout(function(){
                        $(that).trigger("nodeCommand", {cmd: ui.cmd});
                    }, 100);
                }
            });
        }
    };

    return EkynaMediaBrowser;
}));

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#include "Geo/vector.hh"

#include <array>
#include <memory>

namespace Gen {
template <class TypeT, size_t DimT> using Segment =
  Geo::Vector<Geo::Vector<TypeT, DimT>, 2>;

template <class TypeT, size_t DimT>
auto evaluate(const Segment<TypeT, DimT>& _seg, double _t)
{
  return (1 - _t) * _seg[0] + _t * _seg[1];
}

template <class TypeT, size_t DimT, bool infT = false>
bool closest_point(
  const Segment<TypeT, DimT>& _seg, const Geo::Vector<TypeT, DimT>& _pt,
  Geo::Vector<TypeT, DimT>* _clsst_pt = nullptr,
  TypeT* _t = nullptr,
  TypeT * _dist_sq = nullptr)
{
  auto a = _pt - _seg[0];
  auto b = _seg[1] - _seg[0];
  auto len_sq = Geo::length_square(b);
  auto len_ref_sq = 10 * std::numeric_limits<TypeT>::epsilon() *
    std::max(Geo::length_square(_seg[0]), Geo::length_square(_seg[1]));
  if (len_sq <= len_ref_sq)
    return false;
  auto t = (a * b) / len_sq;
  if constexpr (!infT)
  {
    if (t <= 0 || t >= 1)
      return false;
  }
  if (_t != nullptr) *_t = t;
  if (_clsst_pt != nullptr) *_clsst_pt = _seg[1] * t + (1 - t) * _seg[0];
  if (_dist_sq != nullptr)
    *_dist_sq = Geo::length_square(a - t * b);
  return true;
  }

template <class TypeT, size_t DimT, bool Inf1 = false, bool Inf2 = false>
bool closest_point(const Segment<TypeT, DimT>& _seg_a, const Segment<TypeT, DimT>& _seg_b,
                   Geo::Vector<TypeT, DimT>* _clsst_pt = nullptr,
                   double _t[2] = nullptr, double * _dist = nullptr);

} // namespace Gen

namespace Geo {

typedef VectorD3 Point;
typedef std::array<Point, 2> Segment;
typedef std::array<Point, 3> Triangle;

struct IPolygonalFace
{
  virtual ~IPolygonalFace() {}
  virtual bool triangle(size_t _idx, Triangle& _tri) const = 0;
  virtual size_t triangle_number() const = 0;
  virtual Point normal() const = 0;
  static std::shared_ptr<IPolygonalFace> make();
  template <class IteratorT> void add_loop(const IteratorT& _beg, const IteratorT& _end)
  {
    const auto loop_num = make_new_loop();
    for (auto it = _beg; it != _end; ++it)
      add_point(*it, loop_num);
  }
  virtual void compute() = 0;
protected:
  virtual size_t make_new_loop() = 0;
  virtual void add_point(const Point& _pt, size_t _loop_num) = 0;
};

Point evaluate(const Segment& _seg, double _t);

inline bool
closest_point(const Segment& _seg, const Point& _pt,
              Point* _clsst_pt = nullptr, double* _t = nullptr,
              double * _dist_sq = nullptr)
{
  return Gen::closest_point<double, 3>(_seg, _pt, _clsst_pt, _t, _dist_sq);
}

/*! Finds the internal points at minimum distance between two segments.
    Returns false
    if the two segments are parallel (according to the numeric precision) or
    if the minimum distance point between the two segment is on an end of
    at least one the two segments.
*/
inline bool closest_point(const Segment& _seg_a, const Segment& _seg_b,
                          Point* _clsst_pt = nullptr, double _t[2] = nullptr, double * _dist_sq = nullptr)
{
  return Gen::closest_point<double, 3>(_seg_a, _seg_b, _clsst_pt, _t, _dist_sq);
}

/*! Finds the internal point of a triangle closest to a point, ad its distance.
The closest point is returned only if it is strictly inside the triangle.
*/
bool closest_point(const Triangle& _tri, const Point& _pt,
  Point* _clsst_pt, double * _dist_sq);

/*! Finds the internal point of a PolygonalFace closest to a point, ad its distance.
The closest point is returned only if it is strictly inside the PolygonalFace.
It is possible to miss a collision if the point is at an internal boundary of
the triangles used to create the face.
*/
bool closest_point(const IPolygonalFace& _face, const Point& _pt,
  Point* _clsst_pt = nullptr, double * _dist_sq = nullptr);

bool closest_point(const Triangle& _tri, const Segment& _seg,
                   Point* _clsst_pt = nullptr, double * _t = nullptr, double * _dist_sq = nullptr);

bool closest_point(const IPolygonalFace& _face, const Segment& _seg,
  Point* _clsst_pt = nullptr, double * _t = nullptr, double * _dist_sq = nullptr);

}//namespace Geo


text:
namespace WinAuthAndAzureAuthTestForURCS.Models
{
    using System;
    using System.Collections.Generic;

    public partial class UserProjectRole
    {
        public int UserProjectRoleId { get; set; }
        public int UserAccountID { get; set; }
        public int RoleId { get; set; }
        public int ProjectID { get; set; }

        public virtual Role Role { get; set; }
        public virtual UserAccount UserAccount { get; set; }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>EverQuest II - Character Profile v0.6 (by DRL)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">


text:
.. Copyright (c) 2016-2019, Ruslan Baratov
.. All rights reserved.

.. spelling::

  Gitter
  refactor
  spam

Contacts
--------

Public
======

* Feel free to open a new `issue`_ if you want to ask a question
* Public chat room on Gitter: https://gitter.im/cpp-pm/community

Private
=======

* Private chat room on Gitter: https://gitter.im/rbsheth

.. _issue: https://github.com/cpp-pm/hunter/issues/new

Please don't
============

- Please use private channels only if you have sensible or private information
  to share, do use public channels otherwise.

- Please do not cross-post. Do not send the same messages to all channels.

- Please avoid adding messages to closed issues unless it's absolutely
  necessary. If the issue is closed then it means that problem was resolved
  for original author or author lost interest in it. Please report a new issue
  with your details and fresh setup instead.

- Please don't spam channels with uninformative messages such as
  "+1", "me too!", "any updates?!", "please please fix it!", etc.
  Please use `GitHub reactions <https://github.blog/2016-03-10-add-reactions-to-pull-requests-issues-and-comments/>`__ instead.


text:
Example app to demonstrate Google signin using Firebase. Register your app on Firebase and enable Google authentication.

![Initial Page](page1.jpg)
![Login Dialog](page2.jpg)
![User Page](page3.jpg)

## Getting Started

For help getting started with Flutter, view our online
[documentation](https://flutter.io/).


text:
package org.sparklinedata.hive.hook

import java.io.Writer

import org.apache.commons.io.output.StringBuilderWriter

trait Node {
  node =>

  def id : String

  def fastEquals(other: Node): Boolean = {
    this.eq(other) || this == other
  }

  def children : Seq[Node]

  def foreach(f: Node => Unit): Unit = {
    f(this)
    children.foreach(_.foreach(f))
  }

  def traverse(preVisit: Node => Unit, postVisit: Node => Unit)
              (implicit visited : scala.collection.mutable.Set[String]): Unit = {
    val alreadyVisited = visited.contains(id)
    if (!alreadyVisited)  visited.add(id)
    preVisit(this)
    if ( alreadyVisited) return
    children.foreach(_.traverse(preVisit, postVisit))
    postVisit(this)
  }

  def map[A](f: Node => A): Seq[A] = {
    val ret = new collection.mutable.ArrayBuffer[A]()
    foreach(ret += f(_))
    ret
  }

  def flatMap[A](f: Node => TraversableOnce[A]): Seq[A] = {
    val ret = new collection.mutable.ArrayBuffer[A]()
    foreach(ret ++= f(_))
    ret
  }

  def collect[B](pf: PartialFunction[Node, B]): Seq[B] = {
    val ret = new collection.mutable.ArrayBuffer[B]()
    val lifted = pf.lift
    foreach(node => lifted(node).foreach(ret.+=))
    ret
  }

  // for debugging in java
  def _throwNPE = {
    try {
      throw new NullPointerException
    } catch {
      case _ : NullPointerException => ()
    }
  }

}

trait PrintableNode extends Node {

  def printNode(prefix : String, out : Writer) : Unit

  def printGraph(filter : Node => Boolean, prefix : String, out : Writer)
                (implicit visited : scala.collection.mutable.Set[String]) : Unit = {
    val allReadyVisited = visited.contains(id)
    if ( !allReadyVisited)  visited.add(id)
    var p = prefix
    if (filter(this)) {
      printNode(prefix, out)
      p = p + "  "
      if ( allReadyVisited ) {
        out.write(s"$p ...\n")
      }
    }
    if ( allReadyVisited) return
    children.foreach {
      case c : PrintableNode => c.printGraph(filter, p, out)
      case n => out.write(s"$p $n\n")
    }
  }

  def printGraph(prefix : String, out : Writer)
                (implicit visited : scala.collection.mutable.Set[String]) : Unit =
    printGraph({n : Node => true}, prefix, out)

  def toStringTree() : String = {
    val out = new StringBuilderWriter()
    val visited : scala.collection.mutable.Set[String] = scala.collection.mutable.Set()
    printGraph("", out)(visited)
    return out.toString
  }

}


text:
package com.mateuszkoslacz.moviper.base.view.activity.mvp;

import android.view.View;

import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.hannesdorfmann.mosby.mvp.delegate.ActivityMvpDelegate;
import com.hannesdorfmann.mosby.mvp.delegate.ActivityMvpViewStateDelegateCallback;
import com.hannesdorfmann.mosby.mvp.delegate.ActivityMvpViewStateDelegateImpl;
import com.hannesdorfmann.mosby.mvp.lce.MvpLceActivity;
import com.hannesdorfmann.mosby.mvp.lce.MvpLceView;
import com.hannesdorfmann.mosby.mvp.viewstate.ViewState;
import com.hannesdorfmann.mosby.mvp.viewstate.lce.LceViewState;

/**
 * A {@link MvpLceActivity} with {@link ViewState} support.
 *
 * @author Hannes Dorfmann, modified by Mateusz Koślacz
 * @since 1.0.0
 */
public abstract class MvpLceViewStateAiActivity<CV extends View, M, V extends MvpLceView<M>, P extends MvpPresenter<V>>
        extends MvpLceAiActivity<CV, M, V, P>
        implements MvpLceView<M>, ActivityMvpViewStateDelegateCallback<V, P> {

    protected LceViewState<M, V> viewState;
    protected boolean restoringViewState = false;

    @Override protected ActivityMvpDelegate<V, P> getMvpDelegate() {
        if (mvpDelegate == null) {
            mvpDelegate = new ActivityMvpViewStateDelegateImpl<>(this);
        }

        return mvpDelegate;
    }

    @Override public ViewState<V> getViewState() {
        return viewState;
    }

    @Override public void setViewState(ViewState<V> viewState) {
        if (!(viewState instanceof LceViewState)) {
            throw new IllegalArgumentException(
                    "Only " + LceViewState.class.getSimpleName() + " are allowed as view state");
        }

        this.viewState = (LceViewState<M, V>) viewState;
    }

    @Override public void setRestoringViewState(boolean restoringViewState) {
        this.restoringViewState = restoringViewState;
    }

    @Override public boolean isRestoringViewState() {
        return restoringViewState;
    }

    @Override public void onNewViewStateInstance() {
        loadData(false);
    }

    @Override public void onViewStateInstanceRestored(boolean instanceStateRetained) {
        // not needed. You could override this is subclasses if needed
    }

    @Override public void showContent() {
        super.showContent();
        viewState.setStateShowContent(getData());
    }

    @Override public void showError(Throwable e, boolean pullToRefresh) {
        super.showError(e, pullToRefresh);
        viewState.setStateShowError(e, pullToRefresh);
    }

    @Override public void showLoading(boolean pullToRefresh) {
        super.showLoading(pullToRefresh);
        viewState.setStateShowLoading(pullToRefresh);
    }

    @Override protected void showLightError(String msg) {
        if (isRestoringViewState()) {
            return; // Do not display toast again while restoring viewstate
        }

        super.showLightError(msg);
    }

    /**
     * Creates the viewstate
     *
     * @return a new ViewState
     */
    public abstract LceViewState<M, V> createViewState();

    /**
     * Get the data that has been set before in {@link #setData(Object)}
     *

     * It's necessary to return the same data as set before to ensure that {@link ViewState} works
     * correctly
     *

     *
     * @return The data
     */
    public abstract M getData();
}


text:
package com.angkorteam.framework.wicket.extensions.markup.html.repeater.data.table.filter;

import com.angkorteam.framework.wicket.WicketBiFunction;
import com.angkorteam.framework.wicket.WicketTriConsumer;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;

import java.util.Map;

/**
 * Created by socheat on 12/7/16.
 */
public class ItemTextLink extends Panel {

    public ItemTextLink(String id, IModel<Map<String, Object>> rowModel, IModel<?> model, WicketBiFunction<String, Map<String, Object>, ItemCss> itemCss, WicketTriConsumer<String, Map<String, Object>, AjaxRequestTarget> itemClick, String identity) {
        super(id);

        AjaxLink<Map<String, Object>> link = new AjaxLink<Map<String, Object>>("link", rowModel) {
            @Override
            public void onClick(AjaxRequestTarget target) {
                if (itemClick != null) {
                    itemClick.accept(identity, rowModel.getObject(), target);
                }
            }
        };
        add(link);

        Label text = new Label("text", model);
        text.setRenderBodyOnly(true);
        link.add(text);

        ItemCss htmlLambdaCss = itemCss.apply(identity, rowModel.getObject());
        if (htmlLambdaCss == ItemCss.SUCCESS) {
            link.add(AttributeModifier.replace("class", "btn-xs btn-success"));
        } else if (htmlLambdaCss == ItemCss.PRIMARY) {
            link.add(AttributeModifier.replace("class", "btn-xs btn-primary"));
        } else if (htmlLambdaCss == ItemCss.WARNING) {
            link.add(AttributeModifier.replace("class", "btn-xs btn-warning"));
        } else if (htmlLambdaCss == ItemCss.DANGER) {
            link.add(AttributeModifier.replace("class", "btn-xs btn-danger"));
        } else if (htmlLambdaCss == ItemCss.INFO) {
            link.add(AttributeModifier.replace("class", "btn-xs btn-info"));
        }
    }

    public ItemTextLink(String id, IModel<Map<String, Object>> rowModel, IModel<?> model, ItemCss itemCss, WicketTriConsumer<String, Map<String, Object>, AjaxRequestTarget> itemClick, String identity) {
        super(id);

        AjaxLink<Map<String, Object>> link = new AjaxLink<Map<String, Object>>("link", rowModel) {
            @Override
            public void onClick(AjaxRequestTarget target) {
                if (itemClick != null) {
                    itemClick.accept(identity, rowModel.getObject(), target);
                }
            }
        };
        add(link);

        Label text = new Label("text", model);
        text.setRenderBodyOnly(true);
        link.add(text);

        ItemCss htmlLambdaCss = itemCss;
        if (htmlLambdaCss == ItemCss.SUCCESS) {
            link.add(AttributeModifier.replace("class", "btn-xs btn-success"));
        } else if (htmlLambdaCss == ItemCss.PRIMARY) {
            link.add(AttributeModifier.replace("class", "btn-xs btn-primary"));
        } else if (htmlLambdaCss == ItemCss.WARNING) {
            link.add(AttributeModifier.replace("class", "btn-xs btn-warning"));
        } else if (htmlLambdaCss == ItemCss.DANGER) {
            link.add(AttributeModifier.replace("class", "btn-xs btn-danger"));
        } else if (htmlLambdaCss == ItemCss.INFO) {
            link.add(AttributeModifier.replace("class", "btn-xs btn-info"));
        }
    }

}


text:
import { Routes, RouterModule } from '@angular/router';
import {HomeComponent} from "./home.component";
import {ProductDetailComponent} from "./product.component";
import {ProductDetailComponentParam} from "./product-param.component";

const routes: Routes = [
  {path: '',        component: HomeComponent},
  {path: 'product', component: ProductDetailComponent},
  {path: 'product/:id', component: ProductDetailComponentParam}
];

export const routing = RouterModule.forRoot(routes);


text:
#region Licence

#endregion

using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Paramore.Brighter
{
    internal class AsyncRequestHandlers<TRequest> : IEnumerable<RequestHandlerAsync<TRequest>>
        where TRequest : class, IRequest
    {
        private readonly IEnumerable<object> _handlers;

        internal AsyncRequestHandlers(IEnumerable<object> handlers)
        {
            _handlers = handlers;
        }

        public IEnumerator<RequestHandlerAsync<TRequest>> GetEnumerator()
        {
            return _handlers.Cast<RequestHandlerAsync<TRequest>>().GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}


text:
QuickSpecBegin(OCTAuthorizationSpec)

static NSString * const token = @"some-token";
NSDictionary *representation = @{
	@"id": @1,
	@"token": token,
};

__block OCTAuthorization *authorization;

beforeEach(^{
	authorization = [MTLJSONAdapter modelOfClass:OCTAuthorization.class fromJSONDictionary:representation error:NULL];
	expect(authorization).notTo(beNil());
});

it(@"should initialize from an external representation", ^{
	expect(authorization.objectID).to(equal(@"1"));
	expect(authorization.token).to(equal(token));
});

it(@"shouldn't include the token in the serialized representation", ^{
	NSDictionary *representation = [MTLJSONAdapter JSONDictionaryFromModel:authorization];
	expect(representation[@"token"]).to(equal(NSNull.null));
});

itBehavesLike(OCTObjectArchivingSharedExamplesName, ^{
	return @{ OCTObjectKey: authorization };
});

QuickSpecEnd


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../../" />

		<link type="text/css" rel="stylesheet" href="page.css" />

		[page:CurvePath] →

[name]

		This class is used to convert a series of shapes to an array of [page:Path]s, for example an SVG shape to a
		path (see the example below). It is used internally by [page:Font] to convert a font in JSON format to a
		series of paths.

Example

		[example:webgl_geometry_extrude_shapes2 geometry / extrude / shapes2]

Constructor

[name](  )

		Creates a new ShapePath. Unlike a [page:Path], no points are passed in as the ShapePath is designed to
		be generated after creation.

Properties

[property:array subPaths]

		Array of [page:Path]s.

[property:array currentPath]

		The current [page:Path] that is being generated.

Methods

[method:null moveTo]( [param:Float x], [param:Float y] )

		Starts a new [page:Path] and calls [page:Path.moveTo]( x, y ) on that [page:Path].
		Also points [page:ShapePath.currentPath currentPath] to that [page:Path].

[method:null lineTo]( [param:Float x], [param:Float y] )

This creates a line from the [page:ShapePath.currentPath currentPath]'s
			offset to X and Y and updates the offset to X and Y.

[method:null quadraticCurveTo]( [param:Float cpX], [param:Float cpY], [param:Float x], [param:Float y] )

This creates a quadratic curve from the [page:ShapePath.currentPath currentPath]'s
			offset to x and y with cpX and cpY as control point and updates the [page:ShapePath.currentPath currentPath]'s
			offset to x and y.

[method:null bezierCurveTo]( [param:Float cp1X], [param:Float cp1Y], [param:Float cp2X], [param:Float cp2Y], [param:Float x], [param:Float y] )

This creates a bezier curve from the [page:ShapePath.currentPath currentPath]'s
			 offset to x and y with cp1X, cp1Y and cp1X, cp1Y as control points and updates the
			 [page:ShapePath.currentPath currentPath]'s offset to x and y.

[method:null splineThru] ( [param:Array points] )

points - An array of [page:Vector2]s

Connects a new [page:SplineCurve] onto the [page:ShapePath.currentPath currentPath].

[method:Array toShapes]( [param:Boolean isCCW], [param:Boolean noHoles] )

		isCCW -- Changes how solids and holes are generated

		noHoles -- Whether or not to generate holes

		Converts the [page:ShapePath.subPaths subPaths] array into an array of Shapes. By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW). If isCCW is set to true,
		then those are flipped. If the parameter noHoles is set to true then all paths are set as solid shapes and isCCW is ignored.

Source

		[link:https://github.com/mrdoob/three.js/blob/master/src/extras/core/Path.js src/extras/core/Path.js]


text:
package core;

import core.AbstractSampler.InitialState;
import core.crossvalidation.Fold;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import regression.AbstractRegressor;
import util.CLIUtils;
import util.IOUtils;
import util.RankingItem;
import util.StatUtils;
import util.evaluation.Measurement;

/**
 * @param <D> dataset
 * @author vietan
 */
public abstract class AbstractExperiment<D extends AbstractDataset> extends AbstractRunner {

    public static final String PREDICTION_FILE = AbstractRegressor.PREDICTION_FILE;
    public static final String RESULT_FILE = AbstractRegressor.RESULT_FILE;
    public static final String SUMMARY_FILE = "summary.txt";
    public static final String SUPERVISED_FOLDER = "supervised/";
    public static final String UNSUPERVISED_FOLDER = "unsupervised/";
    public static final String SAMPLER_FOLDER = "data/sampler/";
    public static final String TRAIN_PREFIX = "tr_";
    public static final String DEV_PREFIX = "de_";
    public static final String TEST_PREFIX = "te_";
    public static final String TRAIN_POSFIX = "_tr";
    public static final String DEV_POSFIX = "_de";
    public static final String TEST_POSFIX = "_te";
    public static final String PARALLEL_POSFIX = "_p";
    public static final String RESULT_FOLDER = "result";
    public static final String RANKING_FOLDER = "ranking";
    public static final String SURVEY_FOLDER = "survey";
    public static final String MODEL_FILE = "model";
    public static final String PERPLEXITY_FILE = "perplexity.txt";
    public static final int UNOBSERVED = -1;

    public static int burn_in = 100;
    public static int max_iters = 1000;
    public static int sample_lag = 50;
    public static int report_interval = 5;
    protected InitialState initState;
    protected boolean paramOpt;
    public static String experimentPath;
    protected D data;

    public abstract void preprocess() throws Exception;

    public abstract void setup() throws Exception;

    public abstract void run() throws Exception;

    public abstract void evaluate() throws Exception;

    public String getDatasetFolder() {
        return data.getFolder();
    }

    public boolean isTraining() {
        return cmd.hasOption("train");
    }

    public boolean isDeveloping() {
        return cmd.hasOption("dev");
    }

    public boolean isTesting() {
        return cmd.hasOption("test");
    }

    public void setupSampling() {
        burn_in = CLIUtils.getIntegerArgument(cmd, "burnIn", 5);
        max_iters = CLIUtils.getIntegerArgument(cmd, "maxIter", 10);
        sample_lag = CLIUtils.getIntegerArgument(cmd, "sampleLag", 5);
        report_interval = CLIUtils.getIntegerArgument(cmd, "report", 1);
        paramOpt = cmd.hasOption("paramOpt");
        String init = CLIUtils.getStringArgument(cmd, "init", "random");
        switch (init) {
            case "random":
                initState = InitialState.RANDOM;
                break;
            case "preset":
                initState = InitialState.PRESET;
                break;
            default:
                throw new RuntimeException("Initialization " + init + " not supported");
        }
    }

    public static void addSamplingOptions() {
        addOption("burnIn", "Burn-in");
        addOption("maxIter", "Maximum number of iterations");
        addOption("sampleLag", "Sample lag");
        addOption("report", "Report interval");
        addOption("init", "Report interval");

        addOption("test-burnIn", "Burn-in");
        addOption("test-maxIter", "Maximum number of iterations");
        addOption("test-sampleLag", "Sample lag");
    }

    public static void addCrossValidationOptions() {
        addOption("num-folds", "Number of folds. Default 5.");
        addOption("tr2dev-ratio", "Training-to-development ratio. Default 0.8.");
        addOption("cv-folder", "Folder to store cross validation folds");
        addOption("fold", "The cross-validation fold to run");
        addOption("num-classes", "Number of classes when performing stratified sampling");
        options.addOption("train", false, "Train");
        options.addOption("dev", false, "Develop");
        options.addOption("test", false, "Test");
        options.addOption("parallel", false, "Parallel sampling");
    }

    public static void addCorpusProcessorOptions() {
        addOption("u", "The minimum count of raw unigrams");
        addOption("b", "The minimum count of raw bigrams");
        addOption("bs", "The minimum score of bigrams");
        addOption("V", "Maximum vocab size");
        addOption("min-tf", "Term frequency minimum cutoff");
        addOption("max-tf", "Term frequency maximum cutoff");
        addOption("min-df", "Document frequency minimum cutoff");
        addOption("max-df", "Document frequency maximum cutoff");
        addOption("min-doc-length", "Document minimum length");
        options.addOption("s", false, "Whether stopwords are filtered");
        options.addOption("l", false, "Whether lemmatization is performed");
        options.addOption("file", false, "Whether the text input data is stored in a file or a folder");
    }

    public static void addGreekParametersOptions() {
        addOption("alpha", "alpha");
        addOption("beta", "beta");
        addOption("gamma", "gamma");
        addOption("delta", "delta");
        addOption("lambda", "lambda");
        addOption("sigma", "sigma");
        addOption("mu", "mu");
        addOption("rho", "rho");
        addOption("epsilon", "epsilon");
        addOption("eta", "eta");
        addOption("pi", "pi");
    }

    /**
     * Summarize evaluation measurements over multiple folds.
     *
     * @param numFolds Number of folds
     * @param resultFolder The folder containing results
     * @param modelFolder The sub-folder in each foldFolder which stores the
     * outputs of different models
     * @param phase Whether it is training/development/test
     * @param resultFile Result file
     * @throws java.lang.Exception
     */
    protected void evaluate(
            String resultFolder,
            String modelFolder,
            int numFolds,
            String phase,
            String resultFile) throws Exception {
        ArrayList<String> modelNames = new ArrayList<String>();
        HashMap<String, ArrayList<Measurement>>[] results = new HashMap[numFolds];
        for (int f = 0; f < numFolds; f++) {
            Fold fold = new Fold(f, null);
            String foldName = fold.getFoldName();
            File foldFolder = new File(resultFolder, foldName);
            if (!foldFolder.exists()) {
                continue;
            }
            File foldModelFolder = foldFolder;
            if (modelFolder != null) {
                foldModelFolder = new File(foldFolder, modelFolder);
            }
            if (!foldModelFolder.exists()) {
                continue;
            }
            if (verbose) {
                logln("--- Reading results from " + foldModelFolder);
            }

            String[] modelFolders = foldModelFolder.list();
            ArrayList<String> modelFolderList = new ArrayList<String>();
            modelFolderList.addAll(Arrays.asList(modelFolders));
            Collections.sort(modelFolderList);

            results[f] = new HashMap<String, ArrayList<Measurement>>();

            File foldSummary = new File(foldModelFolder, phase + SUMMARY_FILE);
            BufferedWriter writer = IOUtils.getBufferedWriter(foldSummary);
            if (verbose) {
                logln("--- Summarizing fold " + f + ". Writing to " + foldSummary);
            }

            int count = 0;
            for (String mFolder : modelFolderList) {
                File teResultFolder = new File(new File(foldModelFolder, mFolder),
                        phase + RESULT_FOLDER);
                if (!teResultFolder.exists()) {
                    continue;
                }
                File teResultFile = new File(teResultFolder, resultFile);
                if (!teResultFile.exists()) {
                    continue;
                }

                // read measurements
                BufferedReader reader = IOUtils.getBufferedReader(teResultFile);
                String line;
                ArrayList<Measurement> measurements = new ArrayList<Measurement>();
                while ((line = reader.readLine()) != null) {
                    Measurement m = new Measurement(line.split("\t")[0],
                            Double.parseDouble(line.split("\t")[1]));
                    measurements.add(m);
                }
                reader.close();

                if (!modelNames.contains(mFolder)) {
                    modelNames.add(mFolder);
                }
                results[f].put(mFolder, measurements);

                if (count == 0) {
                    writer.write("Model");
                    for (Measurement m : measurements) {
                        writer.write("\t" + m.getName());
                    }
                    writer.write("\n");
                }

                writer.write(mFolder);
                for (Measurement m : measurements) {
                    writer.write("\t" + m.getValue());
                }
                writer.write("\n");

                count++;
            }
            writer.close();
        }
        Collections.sort(modelNames);

        // summarize across folds
        File mergeFile = new File(resultFolder, phase + "merged-" + SUMMARY_FILE);
        File metaSumFile = new File(resultFolder, phase + "meta-" + SUMMARY_FILE);
        if (verbose) {
            System.out.println("--- Meta summarizing " + metaSumFile);
            System.out.println("--- Merge summarizing " + mergeFile);
        }
        ArrayList<String> measureNames = null;

        BufferedWriter writer = IOUtils.getBufferedWriter(metaSumFile);
        BufferedWriter mergeWriter = IOUtils.getBufferedWriter(mergeFile);
        mergeWriter.write("Model\tMetric\tValue\tFold\n");
        for (int f = 0; f < results.length; f++) {
            if (results[f] == null) {
                continue;
            }
            writer.write("Fold " + f + "\n");
            for (String modelName : modelNames) {
                ArrayList<Measurement> modelFoldMeasurements = results[f].get(modelName);
                if (modelFoldMeasurements != null) {
                    writer.write(modelName);
                    for (Measurement m : modelFoldMeasurements) {
                        writer.write("\t" + m.getValue());
                        mergeWriter.write(modelName
                                + "\t" + m.getName()
                                + "\t" + m.getValue()
                                + "\t" + f
                                + "\n");
                    }

                    if (measureNames == null) {
                        measureNames = new ArrayList<String>();
                        for (Measurement m : modelFoldMeasurements) {
                            measureNames.add(m.getName());
                        }
                    }
                    writer.write("\n");
                }
            }
            writer.write("\n\n");
        }

        // average
        if (measureNames != null) {
            for (String measure : measureNames) {
                ArrayList<RankingItem<String>> rankModels = new ArrayList<>();
                HashMap<String, ArrayList<Double>> modelVals = new HashMap<>();
                for (String model : modelNames) {
                    ArrayList<Double> vals = new ArrayList<Double>();
                    for (HashMap<String, ArrayList<Measurement>> result : results) {
                        if (result == null) {
                            continue;
                        }
                        ArrayList<Measurement> modelFoldMeasurements = result.get(model);
                        if (modelFoldMeasurements != null) {
                            for (Measurement m : modelFoldMeasurements) {
                                if (m.getName().equals(measure)) {
                                    vals.add(m.getValue());
                                }
                            }
                        }
                    }

                    double avg = StatUtils.mean(vals);
                    rankModels.add(new RankingItem<String>(model, avg));
                    modelVals.put(model, vals);

                }
                Collections.sort(rankModels);

                writer.write(measure + "\n");
                writer.write("Model\tNum-folds\tAverage\tStdv\n");
                for (RankingItem<String> rankModel : rankModels) {
                    String model = rankModel.getObject();
                    ArrayList<Double> vals = modelVals.get(model);
                    double std = StatUtils.standardDeviation(vals);
                    writer.write(model
                            + "\t" + vals.size()
                            + "\t" + rankModel.getPrimaryValue()
                            + "\t" + std
                            + "\n");
                }
                writer.write("\n\n");
            }
        }
        writer.close();
        mergeWriter.close();
    }
}


text:
package com.valkryst.VNameGenerator.generator;

import com.valkryst.VParser_CFG.ContextFreeGrammar;
import lombok.NonNull;

import java.util.List;

public final class GrammarGenerator extends NameGenerator{
    private ContextFreeGrammar contextFreeGrammar;

    /**
     * Constructs a GrammarGenerator.
     *
     * @param rules A set of Context Free Grammar rules.
     */
    public GrammarGenerator(final @NonNull List<String> rules) {
        setRules(rules);
    }

    @Override
    public String generate(final int maxLength) {
    	super.validateMaxLength(maxLength);

		final var sb = new StringBuilder();
		sb.append(contextFreeGrammar.run());
		sb.setLength(Math.min(sb.length(), maxLength));
		return super.capitalize(super.clean(sb));
    }

	/**
	 * Set a new set of rules.
	 *
	 * @param rules A set of Context Free Grammar rules.
	 */
	public void setRules(final @NonNull List<String> rules) {
		if (rules.size() == 0) {
			throw new IllegalArgumentException("The list of rules must have at least one rule. It is currently empty.");
		}

		contextFreeGrammar = new ContextFreeGrammar(rules.toArray(new String[0]));
	}
}


text:
from m5.params import *
from m5.objects import *

from topologies.BaseTopology import SimpleTopology

class Crossbar(SimpleTopology):
    description='Crossbar'

    def makeTopology(self, options, network, IntLink, ExtLink, Router):

        # default values for link latency and router latency.
        # Can be over-ridden on a per link/router basis
        link_latency = options.link_latency # used by simple and garnet
        router_latency = options.router_latency # only used by garnet

        # Create an individual router for each controller plus one more for
        # the centralized crossbar.  The large numbers of routers are needed
        # because external links do not model outgoing bandwidth in the
        # simple network, but internal links do.
        # For garnet, one router suffices, use CrossbarGarnet.py

        routers = [Router(router_id=i) for i in range(len(self.nodes)+1)]
        xbar = routers[len(self.nodes)] # the crossbar router is the last router created
        network.routers = routers

        ext_links = [ExtLink(link_id=i, ext_node=n, int_node=routers[i],
                             latency = link_latency)
                        for (i, n) in enumerate(self.nodes)]
        network.ext_links = ext_links

        link_count = len(self.nodes)

        int_links = []
        for i in range(len(self.nodes)):
            int_links.append(IntLink(link_id=(link_count+i),
                                     src_node=routers[i],
                                     dst_node=xbar,
                                     latency = link_latency))

        link_count += len(self.nodes)

        for i in range(len(self.nodes)):
            int_links.append(IntLink(link_id=(link_count+i),
                                     src_node=xbar,
                                     dst_node=routers[i],
                                     latency = link_latency))

        network.int_links = int_links


text:
package [PACKAGE];

public class [LEXER_NAME]Exception extends Exception {

    public [LEXER_NAME]Exception(String message) {
        super(message);
    }

    private static final long serialVersionUID = 1L;

}


text:
package com.example.android.movies.adapters;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.android.movies.R;
import com.example.android.movies.models.MovieVideo;

import java.util.List;

public class MovieVideoAdapter  extends BaseAdapter {
    private static final String TAG = MovieVideoAdapter.class.getSimpleName();

    private final Context mContext;
    private final LayoutInflater mInflater;
    private final MovieVideo mLock = new MovieVideo();

    private List<MovieVideo> mObjects;

    public MovieVideoAdapter(Context context, List<MovieVideo> objects) {
        mContext = context;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mObjects = objects;
    }

    public Context getContext() {
        return mContext;
    }

    public void add(MovieVideo object) {
        synchronized (mLock) {
            mObjects.add(object);
        }
        // The adapter needs to know that the data has changed.
        // If we don't call this, app will crash!
        notifyDataSetChanged();
    }

    public void clear() {
        synchronized (mLock) {
            mObjects.clear();
        }
        // The adapter needs to know that the data has changed.
        // If we don't call this, app will crash!
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mObjects.size();
    }

    @Override
    public MovieVideo getItem(int position) {
        return mObjects.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        ViewHolder viewHolder;

        if (view == null) {
            view = mInflater.inflate(R.layout.item_movie_video, parent, false);
            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
        }

        final MovieVideo movieVideo = getItem(position);

        viewHolder = (ViewHolder) view.getTag();

        String youtubeThumbnailUrl = "http://img.youtube.com/vi/" + movieVideo.getKey() + "/0.jpg";

        if (getContext() != null) {
            Glide.with(getContext())
                    .load(youtubeThumbnailUrl)
                    .placeholder(R.drawable.ic_image_black_24dp)
                    .error(R.drawable.ic_broken_image_black_24dp)
                    .into(viewHolder.imageView);
        }

        viewHolder.nameView.setText(movieVideo.getName());

        return view;
    }

    public static class ViewHolder {
        public final ImageView imageView;
        public final TextView nameView;

        public ViewHolder(View view) {
            imageView = (ImageView) view.findViewById(R.id.iv_movie_video_image);
            nameView = (TextView) view.findViewById(R.id.tv_movie_video_name);
        }
    }

}


text:
var context = require("./context");

var afinnMock = {
    "hello": 1,
    "node": 2,
    "bye": -2
};

var sentiment;

describe("Test sentiment", function() {
    before(function () {
        // before() is the first thing we run before all your tests.
        // Do one-time setup here.
        context.mockery.enable();
    });
    beforeEach(function () {
        // beforeEach() is run before each test.
        // Replace './AFINN.json' with our mock
        context.mockery.registerMock("./AFINN.json", afinnMock);

        context.mockery.registerAllowable("require.async");

        // Explicitly telling mockery using the actual sentiment is OK
        // without registerAllowable, you will see WARNING in test output
        context.mockery.registerAllowable("../index");

        sentiment = require("../index");
    });
    describe("Test main method", function () {
        it("should return 3 for input of \"Hello Node\"", function (done) {
            // Now... Test!
            sentiment("Hello Node", function(err, data) {
                context.expect(err).to.equal(null);
                context.expect(data).to.equal(3);
                done();
            });
        });
        it("should return 0 for input of \"Bye Node\"", function (done) {
            // Now... Test!
            sentiment("Bye Node", function(err, data) {
                context.expect(err).to.equal(null);
                context.expect(data).to.equal(0);
                done();
            });
        });
        it("should return 2 for input of \"Lets Node\"", function (done) {
            // Now... Test!
            sentiment("Lets Node", function(err, data) {
                context.expect(err).to.equal(null);
                context.expect(data).to.equal(2);
                done();
            });
        });
    });
    afterEach(function () {
        // afterEach() is run after each test.
        context.mockery.deregisterAll();
    });
    after(function () {
        // after() is run after all your tests have completed.
        // Do teardown here.
        context.mockery.disable();
    });
});


text:
/***************************
** START: Global Settings **
***************************/
.charsheet {    /** Overall page viewed on the website: setting font, padding, and background color **/
    font-family: 'Candal', Helvetica, Arial, sans-serif;
    padding: 0px;
    margin: 0px;
    -webkit-box-sizing: border-box;
    -mox-box-sizing: border-box;
    box-sizing: border-box;
    color: #111111; /** set text to black **/
    color: #ffffff; /** set background to white **/
}
.charsheet textarea, div, input, button {   /** making padding, border, and margin appear INSIDE div area **/
    -webkit-box-sizing: border-box;
    -mox-box-sizing: border-box;
    box-sizing: border-box;
}
.sheet-container {  /** Container for the entire sheet: Background and border and set width **/
    vertical-align: top;
    margin-left: auto;
    margin-right: auto;
    width: 800px;
    text-align: center;
    padding: 10px;
    border: 3px solid #121212;
    background-image: url('https://raw.githubusercontent.com/Roll20/roll20-character-sheets/master/Worlds%20in%20Peril/Worlds%20in%20Peril%20background%20sheet.jpg');
    background-size: cover;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
}
.sheet-section {    /** Borders around individual sections of the sheet to give white background **/
    border: 3px solid #121212;
    background: #ededed;
    padding: 5px;
    width: 100%;
    margin-bottom: 5px;
    vertical-align: top;
}
.sheet-header-1b {	/** Section labels for Editor in Chief (red) **/
    height: 39px;
    background: #b11116;
    position: relative;
    padding-left: 5px;
    padding-top: 3px;
    text-align: left;
}
.sheet-header-1b:before {	/** Section labels for Editor in Chief (red): Beveling the top left **/
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    border-top: 15px solid #ededed;
    border-right: 15px solid rgba(177,17,22,0.0);
}
.sheet-header-1b:after {	/** Section labels for Editor in Chief (red): Beveling the bottom right **/
    content: '';
    position: absolute;
    bottom: 0;
    right: 0;
    border-bottom: 15px solid #ededed;
    border-left: 15px solid rgba(177,17,22,0.0);
}
.sheet-header-1a {	/** Section labels for Player Characters (blue) **/
    height: 39px;
    background: #0061a5;
    position: relative;
    padding-left: 5px;
    padding-top: 3px;
    text-align: left;
}
.sheet-header-1a:before {	/** Section labels for Player Characters (blue): Beveling the top left **/
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    border-top: 15px solid #ededed;
    border-right: 15px solid rgba(0,97,165,0.0);
}
.sheet-header-1a:after {	/** Section labels for Player Characters (blue): Beveling the bottom right **/
    content: '';
    position: absolute;
    bottom: 0;
    right: 0;
    border-bottom: 15px solid #ededed;
    border-left: 15px solid rgba(0,97,165,0.0);
}
.sheet-header-2 {	/** Gray header with 45 degree cut on the right **/
    height: 30px;
    background: #cecece;
    position: relative;
    padding-left: 5px;
    padding-top: 3px;
    text-align: left;
    margin-right: 15px;
}
.sheet-header-2:after {	/** Gray header with 45 degree cut on the right **/
    content: '';
    position: absolute;
    bottom: 0;
    right: -30px;
    border-bottom: 30px solid transparent;
    border-left: 30px solid #cecece;
}
.sheet-heading {
    font-family: 'Candal', Helvetica, Arial, sans-serif;
    text-transform: uppercase;
    display: inline-block;
    color: #ffffff;
    font-size: 1.5em;
    font-weight: bolder;
    line-height: 35px;
}
.sheet-heading-spacer {
    content: '';
    width: 15px;
    display: inline-block;
}
.sheet-heading-text,
.sheet-heading-text input[type=text] {
    display: inline-block;
    height: 29px;
}
.sheet-heading-2 {
    display: inline-block;
    text-transform: uppercase;
    font-family: 'Candal', Helvetica, Arial, sans-serif;
    font-weight: bold;
    font-size: 1.25em;
}
.sheet-half {
    width: 49%;
    padding-right: 1%;
    padding-left: 1%;
    display: inline-block;
    vertical-align: top;
}
.sheet-third {
    width: 32.5%;
    display: inline-block;
    vertical-align: top;
}
.sheet-width200 {
    width: 60px;
}
.sheet-width300 {
    width: 300px;
}
.sheet-bevel-input,
.sheet-bevel-input:focus {	/** Cut off top left and bottom right corners **/
    height: 30px;
    border-radius: 0;
    box-shadow: none;
    padding-left: 15px;
    padding-right: 10px;
    -webkit-clip-path: polygon(15px 0, 100% 0, 100% calc(100% - 15px), calc(100% - 15px) 100%, 0 100%, 0 15px);
    clip-path: polygon(15px 0, 100% 0, 100% calc(100% - 15px), calc(100% - 15px) 100%, 0 100%, 0 15px);
}
    /** START Main Sheet Tab select **/
input[type=radio].sheet-tab-sheet {
    margin-top: 2px;
    opacity: 0;
    width: 100px;
    height: 50px;
    z-index: 2;
}
input[type=radio].sheet-tab-sheet + div {
    margin-top: 2px;
    margin-left: -100px;
    display: inline-block;
    width: 100px;
    height: 50px;
    padding: 5px;
    border: 1px solid white;
    border-radius: 5px;
    background-color: #111111;
    color: #AAAAAA;
    font-family: Verdana, Geneva, sans-serif;
    font-variant: small-caps;
    text-align: center;
    vertical-align: top;
    font-weight: bold;
}
input[type=radio].sheet-tab-sheet:checked + div {
    background-color: #0061a5;
    color:#FFFFFF;
}
    /** END Main Sheet Tab select **/
    /** START show/hide EiC vs Player sheets **/
.sheet-tab {
    display: none;
}
input[type=radio].sheet-tab-sheet.sheet-main:checked ~ .sheet-tab.sheet-main,
input[type=radio].sheet-tab-sheet.sheet-background:checked ~ .sheet-tab.sheet-background {
    display: block;
}
.sheet-toggle {
    display: none;
}
input[type=checkbox].sheet-toggle-sheet:not(:checked) ~ .sheet-toggle.sheet-pc,
input[type=checkbox].sheet-toggle-sheet:checked ~ .sheet-toggle.sheet-eic {
    display: block;
}
input[type=checkbox].sheet-toggle-sheet:checked ~ .sheet-toggle.sheet-pc,
input[type=checkbox].sheet-toggle-sheet:not(:checked) ~ .sheet-toggle.sheet-eic {
    display: none;
}
	/** formatting for the EiC checkbox **/
input[type=checkbox].sheet-toggle-sheet {
    display: inline-block;
    width: 100px;
    opacity: 0;
    z-index: 2;
    height: 20px;
}
input[type=checkbox].sheet-toggle-sheet + div {
    display: inline-block;
    border: 1px solid #121212;
    border-radius: 5px;
    margin-left: -100px;
    width: 100px;
    font-size: 1.0em;
    font-weight: bolder;
    color: #A0A0A0;
    background: #FFFFFF;
    cursor: pointer;
    line-height: 18px;
    text-align: center;
}
input[type=checkbox].sheet-toggle-sheet:checked + div {
    display: inline-block;
    color: #FFFFFF;
    background: #b11116;
}
input[type=checkbox].sheet-toggle-sheet:hover + div,
input[type=checkbox].sheet-toggle-sheet:hover * {
    display: inline-block;
    color: #121212;
    background: #b11116;
}
    /** END show/hide **/

.sheet-clear {
  clear: both;
}

.sheet-mr1 {
  margin-right: 1em;
}

.sheet-mb25 {
  margin-bottom: .25em;
}

label {
  display: inline;
  font-size: inherit;
  line-height: inherit;
  font-weight: bold;
  padding-right: .15em;
}

label.sheet-label-bold {
  display: inline-block;
  text-transform: uppercase;
  font-family: 'Candal', Helvetica, Arial, sans-serif;
  font-weight: bold;
  font-size: 1.25em;
  width: 100%;
  margin-bottom: 0;
}

label.sheet-label-bold-inline {
  display: inline;
  text-transform: uppercase;
  font-family: 'Candal', Helvetica, Arial, sans-serif;
  font-weight: bold;
  font-size: 1.25em;
  line-height: 2;
  margin-right: .25em;
}

label.sheet-label-full {
  display: inline-block;
  margin: .5em 0 .25em 0;
  padding: .25em .25em .25em 1em;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  border: 0;
  background: #0061a5;
  color: #fff;
  text-transform: uppercase;
  width: 100%;
  font-size: 1.6em;
  line-height: 1.625;
  font-family: 'Candal', Helvetica, Arial, sans-serif;
  font-weight: bold;
}

.sheet-input-full {
  width: 100%;
  margin-bottom: .5em;
}

textarea.sheet-textarea-small {
  height: 4em;
}

textarea.sheet-textarea-medium {
  height: 7em;
}

textarea.sheet-textarea-large {
  height: 10em;
}

.sheet-repeated-item-wrapper {
  padding-bottom: .5em;
  border-bottom: 1px solid #ccc;
  margin-bottom: .75em;
}

.sheet-note {
  padding: 0;
  margin: 0 0 .5em 0;
}

/*-----------------*
 * Character Sheet *
 *-----------------*/
.sheet-bonds-wrapper {
  margin-top: .5em;
  border-top: 1px solid #ccc;
  padding-top: .5em;
}

.sheet-bonds-wrapper .repcontainer .repitem:nth-child(2n+1) {
    background: #93a1a1;
    padding: 5px;
}

.sheet-moves-wrapper input[type="text"],
.sheet-moves-wrapper textarea {
  margin-bottom: .5em;
}

.sheet-drives-wrapper .repcontainer .repitem,
.sheet-drives-wrapper .repcontrol,
.sheet-moves-wrapper .repcontainer .repitem,
.sheet-moves-wrapper .repcontrol,
.sheet-mob-wrapper .repcontainer .repitem,
.sheet-mob-wrapper .repcontrol,
.sheet-punch-wrapper .repcontainer .repitem,
.sheet-punch-wrapper .repcontrol {
  width: 49%;
  float: left;
  padding: 5px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  margin-top: .5em;
  margin-left: 2px;
  margin-right: 1px;
}

.sheet-drives-wrapper .repcontainer .repitem:nth-child(4n+3),
.sheet-drives-wrapper .repcontainer .repitem:nth-child(4n+2) {
  border: 2px solid #121212;
  background: #93a1a1;
}

.sheet-drives-wrapper .repcontainer .repitem:nth-child(4n+4),
.sheet-drives-wrapper .repcontainer .repitem:nth-child(4n+1) {
  border: 2px solid #121212;
  background: #586e75;
}

.sheet-moves-wrapper .repcontainer .repitem {
  border: 2px solid #121212;
  background: #fceabb;
  background: -moz-linear-gradient(-45deg, #fceabb 0%, #fccd4d 50%, #f8b500 51%, #fbdf93 100%);
  background: -webkit-linear-gradient(-45deg, #fceabb 0%,#fccd4d 50%,#f8b500 51%,#fbdf93 100%);
  background: linear-gradient(135deg, #fceabb 0%,#fccd4d 50%,#f8b500 51%,#fbdf93 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#fceabb', endColorstr='#fbdf93',GradientType=1 );
}

.sheet-punch-wrapper .repcontainer .repitem:nth-child(3n+1),
.sheet-mob-wrapper .repcontainer .repitem:nth-child(3n+1) {
  border: 2px solid #121212;
  background: #859900;
}
.sheet-punch-wrapper .repcontainer .repitem:nth-child(3n+2),
.sheet-mob-wrapper .repcontainer .repitem:nth-child(3n+2) {
  border: 2px solid #121212;
  background: #dc322f;
}
.sheet-punch-wrapper .repcontainer .repitem:nth-child(3n+3),
.sheet-mob-wrapper .repcontainer .repitem:nth-child(3n+3) {
  border: 2px solid #121212;
  background: #268bd2;
}

.sheet-drives-wrapper .repcontainer .repitem:nth-child(2n+1),
.sheet-moves-wrapper .repcontainer .repitem:nth-child(2n+1),
.sheet-mob-wrapper .repcontainer .repitem:nth-child(2n+1),
.sheet-punch-wrapper .repcontainer .repitem:nth-child(2n+1) {
  margin-left: 6px;
}

.sheet-drives-wrapper .repcontainer .repitem .sheet-repeated-item-wrapper,
.sheet-moves-wrapper .repcontainer .repitem .sheet-repeated-item-wrapper,
.sheet-mob-wrapper .repcontainer .repitem .sheet-repeated-item-wrapper,
.sheet-punch-wrapper .repcontainer .repitem .sheet-repeated-item-wrapper {
  margin: 0;
  padding: 0;
  border: 0;
}

/* ROLL TEMPLATE */

.sheet-rolltemplate-wip {
  width: 100%;
  padding: 1em;
  background-image: url('https://raw.githubusercontent.com/Roll20/roll20-character-sheets/master/Worlds%20in%20Peril/Worlds%20in%20Peril%20background%20rolls.jpg');
  background-size: cover;
  border: 4px solid #000;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
}

.sheet-rolltemplate-wip table {
  width: 100%;
  font-family: 'Candal', Helvetica, Arial, sans-serif;
  border-spacing: 0;
  margin-bottom: .5em;
}

.sheet-rolltemplate-wip table div,
.sheet-rolltemplate-wip table span {
  font-weight: bold;
  text-transform: uppercase;
}

.sheet-rolltemplate-wip th {
  color: #666;
  padding-bottom: 1em;
  line-height: 1.2;
  font-size: 1.5em;
  font-weight: normal;
  text-align: left;
}

.sheet-rolltemplate-wip th div.sheet-rt-character-name {
  color: #121212;
}

.sheet-rolltemplate-wip th div.sheet-rt-roll-name {
  color: #ff6c00;
}

.sheet-rolltemplate-wip th div.sheet-rt-roll-name span.sheet-rt-roll-mod {
  color: #121212;
}

.sheet-rolltemplate-wip .sheet-result {
  font-size: 2.5em;
  padding: 0;
  width: 20%;
  text-align: center;
}

.sheet-rolltemplate-wip .inlinerollresult,
.sheet-rolltemplate-wip .inlinerollresult.fullcrit,
.sheet-rolltemplate-wip .inlinerollresult.fullfail,
.sheet-rolltemplate-wip .inlinerollresult.importantroll {
  background-color: transparent;
  color: #000;
  border: none;
}

.sheet-rolltemplate-wip th span.sheet-rt-roll-effect-adv,
.sheet-rolltemplate-wip .sheet-success .inlinerollresult,
.sheet-rolltemplate-wip .sheet-success .inlinerollresult.fullcrit,
.sheet-rolltemplate-wip .sheet-success .inlinerollresult.fullfail,
.sheet-rolltemplate-wip .sheet-success .inlinerollresult.importantroll {
  background-color: transparent;
  color: #3fb315;
  border: none;
}

.sheet-rolltemplate-wip th span.sheet-rt-roll-effect-dis,
.sheet-rolltemplate-wip .sheet-failure .inlinerollresult,
.sheet-rolltemplate-wip .sheet-failure .inlinerollresult.fullcrit,
.sheet-rolltemplate-wip .sheet-failure .inlinerollresult.fullfail,
.sheet-rolltemplate-wip .sheet-failure .inlinerollresult.importantroll {
  background-color: transparent;
  color: #b31515;
  border: none;
}


text:
var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Navigator
} = React;

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  navigator: {
    flex: 1
  }
});

var NavigationBar = require('react-native-navbar');

class Example extends React.Component {
  render() {
    return (
      <View>
        <Text>Some content</Text>
      </View>
    );
  }
}

class Basic extends React.Component {
  renderScene(route, navigator) {
    var Component = route.component;
    var navBar = route.navigationBar;

    if (navBar) {
      navBar = React.addons.cloneWithProps(navBar, {
        navigator: navigator,
        route: route
      });
    }

    return (
      <View style={styles.navigator}>
        {navBar}
        <Component navigator={navigator} route={route} />
      </View>
    );
  }

  handleNext() {
    alert('Next button click handler');
  }

  render() {
    return (
      <Navigator
        renderScene={this.renderScene}
        initialRoute={{
          component: Example,
          navigationBar: <NavigationBar
            title="Initial View"
            onNext={this.handleNext}
            style={styles.navigator}
          />
        }}
      />
    );
  }
}

AppRegistry.registerComponent('Basic', () => Basic);


text:
"""{{ cookiecutter.project }} analysis."""

import os
import logging
import argparse
import errno

from dtoolcore import DataSet

from jicbioimage.core.image import Image
from jicbioimage.core.transform import transformation
from jicbioimage.core.io import AutoName, AutoWrite

__version__ = "{{ cookiecutter.version }}"

AutoName.prefix_format = "{:03d}_"

def safe_mkdir(directory):
    """Create directories if they do not exist."""
    try:
        os.makedirs(directory)
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(directory):
            pass
        else:
            raise

def item_output_path(output_directory, rel_path):
    """Return item output path; and create it if it does not already exist."""
    abs_path = os.path.join(output_directory, rel_path)
    safe_mkdir(abs_path)
    return abs_path

@transformation
def identity(image):
    """Return the image as is."""
    return image

def analyse_file(fpath, output_directory):
    """Analyse a single file."""
    logging.info("Analysing file: {}".format(fpath))

    AutoName.directory = output_directory

    image = Image.from_file(fpath)
    image = identity(image)

def analyse_dataset(dataset_dir, output_dir):
    """Analyse all the files in the dataset."""
    dataset = DataSet.from_path(dataset_dir)
    logging.info("Analysing items in dataset: {}".format(dataset.name))

    for i in dataset.identifiers:
        data_item_abspath = dataset.abspath_from_identifier(i)
        item_info = dataset.item_from_identifier(i)

        specific_output_dir = item_output_path(output_dir, item_info["path"])
        analyse_file(data_item_abspath, specific_output_dir)

def main():
    # Parse the command line arguments.
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input_dataset", help="Input dataset")
    parser.add_argument("output_dir", help="Output directory")
    parser.add_argument("--debug", default=False, action="store_true",
                        help="Write out intermediate images")
    args = parser.parse_args()

    # Create the output directory if it does not exist.
    if not os.path.isdir(args.output_dir):
        os.mkdir(args.output_dir)
    AutoName.directory = args.output_dir

    # Only write out intermediate images in debug mode.
    if not args.debug:
        AutoWrite.on = False

    # Setup a logger for the script.
    log_fname = "audit.log"
    log_fpath = os.path.join(args.output_dir, log_fname)
    logging_level = logging.INFO
    if args.debug:
        logging_level = logging.DEBUG
    logging.basicConfig(filename=log_fpath, level=logging_level)

    # Log some basic information about the script that is running.
    logging.info("Script name: {}".format(__file__))
    logging.info("Script version: {}".format(__version__))

    # Run the analysis.
    if os.path.isdir(args.input_dataset):
        analyse_dataset(args.input_dataset, args.output_dir)
    else:
        parser.error("{} not a directory".format(args.input_dataset))

if __name__ == "__main__":
    main()


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

namespace System.Collections.Generic {

    /// <summary>
    /// ABOUT:
    /// Helps with operations that rely on bit marking to indicate whether an item in the
    /// collection should be added, removed, visited already, etc.
    ///
    /// BitHelper doesn't allocate the array; you must pass in an array or ints allocated on the
    /// stack or heap. ToIntArrayLength() tells you the int array size you must allocate.
    ///
    /// USAGE:
    /// Suppose you need to represent a bit array of length (i.e. logical bit array length)
    /// BIT_ARRAY_LENGTH. Then this is the suggested way to instantiate BitHelper:
    /// ***************************************************************************
    /// int intArrayLength = BitHelper.ToIntArrayLength(BIT_ARRAY_LENGTH);
    /// BitHelper bitHelper;
    /// if (intArrayLength less than stack alloc threshold)
    ///     int* m_arrayPtr = stackalloc int[intArrayLength];
    ///     bitHelper = new BitHelper(m_arrayPtr, intArrayLength);
    /// else
    ///     int[] m_arrayPtr = new int[intArrayLength];
    ///     bitHelper = new BitHelper(m_arrayPtr, intArrayLength);
    /// ***************************************************************************
    ///
    /// IMPORTANT:
    /// The second ctor args, length, should be specified as the length of the int array, not
    /// the logical bit array. Because length is used for bounds checking into the int array,
    /// it's especially important to get this correct for the stackalloc version. See the code
    /// samples above; this is the value gotten from ToIntArrayLength().
    ///
    /// The length ctor argument is the only exception; for other methods -- MarkBit and
    /// IsMarked -- pass in values as indices into the logical bit array, and it will be mapped
    /// to the position within the array of ints.
    ///
    ///

    unsafe internal class BitHelper {   // should not be serialized

        private const byte MarkedBitFlag = 1;
        private const byte IntSize = 32;

        // m_length of underlying int array (not logical bit array)
        private int m_length;

        // ptr to stack alloc'd array of ints
        [System.Security.SecurityCritical]
        private int* m_arrayPtr;

        // array of ints
        private int[] m_array;

        // whether to operate on stack alloc'd or heap alloc'd array
        private bool useStackAlloc;

        /// <summary>
        /// Instantiates a BitHelper with a heap alloc'd array of ints
        /// </summary>
        /// <param name="bitArray">int array to hold bits</param>
        /// <param name="length">length of int array</param>
        // <SecurityKernel Critical="True" Ring="0">
        // <UsesUnsafeCode Name="Field: m_arrayPtr" />
        // <UsesUnsafeCode Name="Parameter bitArrayPtr of type: Int32*" />
        // </SecurityKernel>
        [System.Security.SecurityCritical]
        internal BitHelper(int* bitArrayPtr, int length) {
            this.m_arrayPtr = bitArrayPtr;
            this.m_length = length;
            useStackAlloc = true;
        }

        /// <summary>
        /// Instantiates a BitHelper with a heap alloc'd array of ints
        /// </summary>
        /// <param name="bitArray">int array to hold bits</param>
        /// <param name="length">length of int array</param>
        internal BitHelper(int[] bitArray, int length) {
            this.m_array = bitArray;
            this.m_length = length;
        }

        /// <summary>
        /// Mark bit at specified position
        /// </summary>
        /// <param name="bitPosition"></param>
        // <SecurityKernel Critical="True" Ring="0">
        // <UsesUnsafeCode Name="Field: m_arrayPtr" />
        // </SecurityKernel>
        [System.Security.SecurityCritical]
        internal unsafe void MarkBit(int bitPosition) {
            if (useStackAlloc) {
                int bitArrayIndex = bitPosition / IntSize;
                if (bitArrayIndex < m_length && bitArrayIndex >= 0) {
                    m_arrayPtr[bitArrayIndex] |= (MarkedBitFlag << (bitPosition % IntSize));
                }
            }
            else {
                int bitArrayIndex = bitPosition / IntSize;
                if (bitArrayIndex < m_length && bitArrayIndex >= 0) {
                    m_array[bitArrayIndex] |= (MarkedBitFlag << (bitPosition % IntSize));
                }
            }
        }

        /// <summary>
        /// Is bit at specified position marked?
        /// </summary>
        /// <param name="bitPosition"></param>
        /// <returns></returns>
        // <SecurityKernel Critical="True" Ring="0">
        // <UsesUnsafeCode Name="Field: m_arrayPtr" />
        // </SecurityKernel>
        [System.Security.SecurityCritical]
        internal unsafe bool IsMarked(int bitPosition) {
            if (useStackAlloc) {
                int bitArrayIndex = bitPosition / IntSize;
                if (bitArrayIndex < m_length && bitArrayIndex >= 0) {
                    return ((m_arrayPtr[bitArrayIndex] & (MarkedBitFlag << (bitPosition % IntSize))) != 0);
                }
                return false;
            }
            else {
                int bitArrayIndex = bitPosition / IntSize;
                if (bitArrayIndex < m_length && bitArrayIndex >= 0) {
                    return ((m_array[bitArrayIndex] & (MarkedBitFlag << (bitPosition % IntSize))) != 0);
                }
                return false;
            }
        }

        /// <summary>
        /// How many ints must be allocated to represent n bits. Returns (n+31)/32, but
        /// avoids overflow
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        internal static int ToIntArrayLength(int n) {
            return n > 0 ? ((n - 1) / IntSize + 1) : 0;
        }

    }
}


text:
<?php
/**
 * Nuwani-v2 Bot Framework
 *
 * This file is part of the Nuwani v2 Bot Framework, a simple set of PHP classes which allow
 * you to set-up and run your own bot. It features advanced, PHP-5.3 based syntax for
 * optimal performance and security.
 *
 * Author: Peter Beverloo
 *         peter@lvp-media.com
 */

use Nuwani \ Bot;

class CTCP extends Nuwani \ ModuleBase
{
	/**
	 * Function: onCTCP
	 * Argument: pBot (Bot) - The bot who received this CTCP-message.
	 * Argument: sSource (string) - Source channel or nickname of the message.
	 * Argument: sType (string) - Type of message that has been received.
	 * Argument: sMessage (string) - The actual received message.
	 *
	 * To make the bot more interactive with the IRC server, as well as with
	 * other clients, we want a default set of replies to CTCP requests.
	 */

	public function onCTCP (Bot $pBot, $sSource, $sNickname, $sType, $sMessage)
	{
		switch (trim ($sType))
		{
			case 'VERSION':
			{
				$this -> sendCTCP ($pBot, $sNickname, 'VERSION', '"' . $pBot ['Nickname'] . '" running ' . VERSION_STR);
				break;
			}

			case 'PING':
			{
				$this -> sendCTCP ($pBot, $sNickname, 'PING', trim ($sMessage));
				break;
			}

			case 'TIME':
			{
				if (strlen ($sMessage))
					break ; /* reply from another client */

				$this -> sendCTCP ($pBot, $sNickname, 'TIME', date('D M d H:i:s Y'));
				break;
			}

			case 'URL':
			case 'FINGER':
			{
				$this -> sendCTCP ($pBot, $sNickname, $sType, 'Check out http://nuwani.googlecode.com!');
				break;
			}
		}
	}

	/**
	 * Function: sendCTCP
	 * Argument: pBot (Bot) - The bot that will be sending this message.
	 * Argument: sNickname (string) - Nickname to reply to, e.g. the destination.
	 * Argument: sType (string) - Type of CTCP message that will be send.
	 * Argument: sMessage (string) - The message associated with the CTCP.
	 *
	 * A small helper function to distribute the CTCP reply to the IRC
	 * Network, mainly because it needs all kinds of characters.
	 */

	private function sendCTCP (Bot $pBot, $sNickname, $sType, $sMessage)
	{
		$sCommand = 'NOTICE ' . $sNickname . ' :' . self :: CTCP . $sType;
		if (strlen ($sMessage) > 0)
			$sCommand .= ' ' . $sMessage;

		$pBot -> send ($sCommand . self :: CTCP);
	}
};

?>