text:
cr.define('md_history.history_overflow_menu_test', function() {
  // Menu button event.
  var MENU_EVENT = {
    detail: {
      target: null
    }
  };

  var ADDITIONAL_MENU_EVENT = {
    detail: {
      target: null
    }
  };

  function registerTests() {
    suite('#overflow-menu', function() {
      var app;
      var listContainer;
      var sharedMenu;

      suiteSetup(function() {
        app = $('history-app');
        listContainer = app.$['history'];
        sharedMenu = listContainer.$.sharedMenu;

        var element1 = document.createElement('div');
        var element2 = document.createElement('div');
        document.body.appendChild(element1);
        document.body.appendChild(element2);

        MENU_EVENT.detail.target = element1;
        ADDITIONAL_MENU_EVENT.detail.target = element2;
      });

      test('opening and closing menu', function() {
        listContainer.toggleMenu_(MENU_EVENT);
        assertTrue(sharedMenu.menuOpen);
        assertEquals(MENU_EVENT.detail.target, sharedMenu.lastAnchor_);

        // Test having the same menu event (pressing the same button) closes the
        // overflow menu.
        listContainer.toggleMenu_(MENU_EVENT);
        assertFalse(sharedMenu.menuOpen);

        // Test having consecutive distinct menu events moves the menu to the
        // new button.
        listContainer.toggleMenu_(MENU_EVENT);
        listContainer.toggleMenu_(ADDITIONAL_MENU_EVENT);
        assertEquals(
            ADDITIONAL_MENU_EVENT.detail.target, sharedMenu.lastAnchor_);
        assertTrue(sharedMenu.menuOpen);
        listContainer.toggleMenu_(MENU_EVENT);
        assertTrue(sharedMenu.menuOpen);
        assertEquals(MENU_EVENT.detail.target, sharedMenu.lastAnchor_);

        sharedMenu.closeMenu();
        assertFalse(sharedMenu.menuOpen);
      });

      test('menu closes when search changes', function() {
        var entry =
            [createHistoryEntry('2016-07-19', 'https://www.nianticlabs.com')];

        app.historyResult(createHistoryInfo(), entry);
        listContainer.toggleMenu_(MENU_EVENT);

        // Menu closes when search changes
        app.historyResult(createHistoryInfo('niantic'), entry);
        assertFalse(sharedMenu.menuOpen);
      });

      teardown(function() {
        sharedMenu.lastAnchor_ = null;
      });
    });
  }
  return {
    registerTests: registerTests
  };
});


text:
FROM resin/rpi-raspbian

#
#	Basic Setup
#
MAINTAINER David Gatti "docker@gatti.pl"

#
#	Prepare the app by installing all the dependencies
#
RUN apt-get update && \
    apt-get upgrade && \
    apt-get install apt-utils && \
    apt-get install libnss-mdns && \
    apt-get install avahi-daemon && \
    apt-get -y autoclean && \
    apt-get -y autoremove && \
    apt-get -y clean && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

#
#
#
COPY avahi-daemon.conf /etc/avahi/avahi-daemon.conf

#
#	Services
#
COPY smb.service /etc/avahi/services/smb.service
COPY printer.service /etc/avahi/services/printer.service

#
#	Share the same dbus among all containers
#
RUN mkdir -p /var/run/dbus

#
#	Expose the default port
#
EXPOSE 5353/udp
EXPOSE 53791/udp

#
#	Run the app
#
CMD avahi-daemon --no-drop-root && tail -f /var/log/lastlog

redpajama_set_name: RedPajamaGithub


text:
"use strict";
var $ = require("jquery"),
    errors = require("./ui.errors"),
    Action = require("../../core/action"),
    commonUtils = require("../../core/utils/common"),
    domUtils = require("../../core/utils/dom"),
    devices = require("../../core/devices"),
    DOMComponent = require("../../core/dom_component"),
    Template = require("./jquery.template"),
    FunctionTemplate = require("./function_template"),
    EmptyTemplate = require("./empty_template"),
    ChildDefaultTemplate = require("./child_default_template"),
    KeyboardProcessor = require("./ui.keyboard_processor"),
    selectors = require("./jquery.selectors"),
    eventUtils = require("../../events/utils"),
    hoverEvents = require("../../events/hover"),
    feedbackEvents = require("../../events/core/emitter.feedback"),
    clickEvent = require("../../events/click"),
    inflector = require("../../core/utils/inflector");
var UI_FEEDBACK = "UIFeedback",
    WIDGET_CLASS = "dx-widget",
    ACTIVE_STATE_CLASS = "dx-state-active",
    DISABLED_STATE_CLASS = "dx-state-disabled",
    INVISIBLE_STATE_CLASS = "dx-state-invisible",
    HOVER_STATE_CLASS = "dx-state-hover",
    FOCUSED_STATE_CLASS = "dx-state-focused",
    FEEDBACK_SHOW_TIMEOUT = 30,
    FEEDBACK_HIDE_TIMEOUT = 400,
    FOCUS_NAMESPACE = "Focus",
    ANONYMOUS_TEMPLATE_NAME = "template",
    TEXT_NODE = 3,
    TEMPLATE_SELECTOR = "[data-options*='dxTemplate']",
    TEMPLATE_WRAPPER_CLASS = "dx-template-wrapper";
var DX_POLYMORPH_WIDGET_TEMPLATE = new FunctionTemplate(function(options) {
    var widgetName = options.model.widget;
    if (widgetName) {
        var widgetElement = $("<div>"),
            widgetOptions = options.model.options || {};
        if ("button" === widgetName || "tabs" === widgetName || "dropDownMenu" === widgetName) {
            var deprecatedName = widgetName;
            widgetName = inflector.camelize("dx-" + widgetName);
            errors.log("W0001", "dxToolbar - 'widget' item field", deprecatedName, "16.1", "Use: '" + widgetName + "' instead")
        }
        widgetElement[widgetName](widgetOptions);
        return widgetElement
    }
    return $()
});
var beforeActivateExists = void 0 !== document.onbeforeactivate;
var Widget = DOMComponent.inherit({
    _supportedKeys: function() {
        return {}
    },
    _getDefaultOptions: function() {
        return $.extend(this.callBase(), {
            disabled: false,
            visible: true,
            hint: void 0,
            activeStateEnabled: false,
            onContentReady: null,
            hoverStateEnabled: false,
            focusStateEnabled: false,
            tabIndex: 0,
            accessKey: null,
            onFocusIn: null,
            onFocusOut: null,
            integrationOptions: {
                watchMethod: function(fn, callback, options) {
                    options = options || {};
                    if (!options.skipImmediate) {
                        callback(fn())
                    }
                    return $.noop
                },
                templates: {
                    "dx-polymorph-widget": DX_POLYMORPH_WIDGET_TEMPLATE
                },
                createTemplate: function(element) {
                    return new Template(element)
                }
            },
            _keyboardProcessor: void 0
        })
    },
    _feedbackShowTimeout: FEEDBACK_SHOW_TIMEOUT,
    _feedbackHideTimeout: FEEDBACK_HIDE_TIMEOUT,
    _init: function() {
        this.callBase();
        this._tempTemplates = [];
        this._defaultTemplates = {};
        this._initTemplates();
        this._initContentReadyAction()
    },
    _initTemplates: function() {
        this._extractTemplates();
        this._extractAnonymousTemplate()
    },
    _extractTemplates: function() {
        var templates = this.option("integrationOptions.templates"),
            templateElements = this.element().contents().filter(TEMPLATE_SELECTOR);
        var templatesMap = {};
        templateElements.each(function(_, template) {
            var templateOptions = domUtils.getElementOptions(template).dxTemplate;
            if (!templateOptions) {
                return
            }
            if (!templateOptions.name) {
                throw errors.Error("E0023")
            }
            $(template).addClass(TEMPLATE_WRAPPER_CLASS).detach();
            templatesMap[templateOptions.name] = templatesMap[templateOptions.name] || [];
            templatesMap[templateOptions.name].push(template)
        });
        $.each(templatesMap, $.proxy(function(templateName, value) {
            var deviceTemplate = this._findTemplateByDevice(value);
            if (deviceTemplate) {
                templates[templateName] = this._createTemplate(deviceTemplate)
            }
        }, this))
    },
    _findTemplateByDevice: function(templates) {
        var suitableTemplate = commonUtils.findBestMatches(devices.current(), templates, function(template) {
            return domUtils.getElementOptions(template).dxTemplate
        })[0];
        $.each(templates, function(index, template) {
            if (template !== suitableTemplate) {
                $(template).remove()
            }
        });
        return suitableTemplate
    },
    _extractAnonymousTemplate: function() {
        var templates = this.option("integrationOptions.templates"),
            anonymousTemplateName = this._getAnonymousTemplateName(),
            $anonymousTemplate = this.element().contents().detach();
        var $notJunkTemplateContent = $anonymousTemplate.filter(function(_, element) {
                var isTextNode = element.nodeType === TEXT_NODE,
                    isEmptyText = $.trim($(element).text()).length < 1;
                return !(isTextNode && isEmptyText)
            }),
            onlyJunkTemplateContent = $notJunkTemplateContent.length < 1;
        if (!templates[anonymousTemplateName] && !onlyJunkTemplateContent) {
            templates[anonymousTemplateName] = this._createTemplate($anonymousTemplate)
        }
    },
    _getAriaTarget: function() {
        return this._focusTarget()
    },
    _getAnonymousTemplateName: function() {
        return ANONYMOUS_TEMPLATE_NAME
    },
    _getTemplateByOption: function(optionName) {
        return this._getTemplate(this.option(optionName))
    },
    _getTemplate: function(templateSource) {
        if ($.isFunction(templateSource)) {
            return new FunctionTemplate(function(options) {
                var templateSourceResult = templateSource.apply(this, this._getNormalizedTemplateArgs(options));
                if (!commonUtils.isDefined(templateSourceResult)) {
                    return new EmptyTemplate
                }
                var dispose = false;
                var template = this._acquireTemplate(templateSourceResult, function(templateSource) {
                    if (templateSource.nodeType || templateSource.jquery && !$(templateSource).is("script")) {
                        return new FunctionTemplate(function() {
                            return templateSource
                        })
                    }
                    dispose = true;
                    return this._createTemplate(templateSource)
                }.bind(this));
                var result = template.render(options);
                dispose && template.dispose && template.dispose();
                return result
            }.bind(this))
        }
        return this._acquireTemplate(templateSource, this._createTemplateIfNeeded.bind(this))
    },
    _acquireTemplate: function(templateSource, createTemplate) {
        if (null == templateSource) {
            return new EmptyTemplate
        }
        if (templateSource instanceof ChildDefaultTemplate) {
            return this._defaultTemplates[templateSource.name]
        }
        if (commonUtils.isFunction(templateSource.render) && !templateSource.jquery) {
            return templateSource
        }
        if (templateSource.nodeType || templateSource.jquery) {
            templateSource = $(templateSource);
            return createTemplate(templateSource)
        }
        if ("string" === typeof templateSource) {
            var userTemplate = this.option("integrationOptions.templates")[templateSource];
            if (userTemplate) {
                return userTemplate
            }
            var dynamicTemplate = this._defaultTemplates[templateSource];
            if (dynamicTemplate) {
                return dynamicTemplate
            }
            return createTemplate(templateSource)
        }
        return this._acquireTemplate(templateSource.toString(), createTemplate)
    },
    _createTemplateIfNeeded: function(templateSource) {
        var templateKey = function(templateSource) {
            return templateSource.jquery && templateSource[0] || templateSource
        };
        var cachedTemplate = this._tempTemplates.filter(function(t) {
            templateSource = templateKey(templateSource);
            return t.source === templateSource
        })[0];
        if (cachedTemplate) {
            return cachedTemplate.template
        }
        var template = this._createTemplate(templateSource);
        this._tempTemplates.push({
            template: template,
            source: templateKey(templateSource)
        });
        return template
    },
    _createTemplate: function(templateSource) {
        templateSource = "string" === typeof templateSource ? domUtils.normalizeTemplateElement(templateSource) : templateSource;
        return this.option("integrationOptions.createTemplate")(templateSource)
    },
    _getNormalizedTemplateArgs: function(options) {
        var args = [];
        if ("model" in options) {
            args.push(options.model)
        }
        if ("index" in options) {
            args.push(options.index)
        }
        args.push(options.container);
        return args
    },
    _cleanTemplates: function() {
        this._tempTemplates.forEach(function(t) {
            t.template.dispose && t.template.dispose()
        });
        this._tempTemplates = []
    },
    _initContentReadyAction: function() {
        this._contentReadyAction = this._createActionByOption("onContentReady", {
            excludeValidators: ["designMode", "disabled", "readOnly"]
        })
    },
    _render: function() {
        this.element().addClass(WIDGET_CLASS);
        this.callBase();
        this._toggleDisabledState(this.option("disabled"));
        this._toggleVisibility(this.option("visible"));
        this._renderHint();
        this._renderContent();
        this._renderFocusState();
        this._attachFeedbackEvents();
        this._attachHoverEvents()
    },
    _renderHint: function() {
        domUtils.toggleAttr(this.element(), "title", this.option("hint"))
    },
    _renderContent: function() {
        var that = this;
        commonUtils.deferRender(function() {
            that._renderContentImpl()
        });
        that._fireContentReadyAction()
    },
    _renderContentImpl: $.noop,
    _fireContentReadyAction: function() {
        this._contentReadyAction()
    },
    _dispose: function() {
        this._cleanTemplates();
        this._contentReadyAction = null;
        this.callBase()
    },
    _clean: function() {
        this._cleanFocusState();
        this.callBase();
        this.element().empty()
    },
    _toggleVisibility: function(visible) {
        this.element().toggleClass(INVISIBLE_STATE_CLASS, !visible);
        this.setAria("hidden", !visible || void 0)
    },
    _renderFocusState: function() {
        if (!this.option("focusStateEnabled") || this.option("disabled")) {
            return
        }
        this._renderFocusTarget();
        this._attachFocusEvents();
        this._attachKeyboardEvents();
        this._renderAccessKey()
    },
    _renderAccessKey: function() {
        var focusTarget = this._focusTarget();
        focusTarget.attr("accesskey", this.option("accessKey"));
        var clickNamespace = eventUtils.addNamespace(clickEvent.name, UI_FEEDBACK);
        focusTarget.off(clickNamespace);
        this.option("accessKey") && focusTarget.on(clickNamespace, $.proxy(function(e) {
            if (eventUtils.isFakeClickEvent(e)) {
                e.stopImmediatePropagation();
                this.focus()
            }
        }, this))
    },
    _eventBindingTarget: function() {
        return this.element()
    },
    _focusTarget: function() {
        return this._getActiveElement()
    },
    _getActiveElement: function() {
        var activeElement = this._eventBindingTarget();
        if (this._activeStateUnit) {
            activeElement = activeElement.find(this._activeStateUnit).not("." + DISABLED_STATE_CLASS)
        }
        return activeElement
    },
    _renderFocusTarget: function() {
        this._focusTarget().attr("tabindex", this.option("tabIndex"))
    },
    _keyboardEventBindingTarget: function() {
        return this._eventBindingTarget()
    },
    _detachFocusEvents: function() {
        var $element = this._focusTarget(),
            namespace = this.NAME + FOCUS_NAMESPACE,
            focusEvents = eventUtils.addNamespace("focusin", namespace);
        focusEvents = focusEvents + " " + eventUtils.addNamespace("focusout", namespace);
        if (beforeActivateExists) {
            focusEvents = focusEvents + " " + eventUtils.addNamespace("beforeactivate", namespace)
        }
        $element.off(focusEvents)
    },
    _attachFocusEvents: function() {
        var namespace = this.NAME + FOCUS_NAMESPACE,
            focusInEvent = eventUtils.addNamespace("focusin", namespace),
            focusOutEvent = eventUtils.addNamespace("focusout", namespace);
        this._focusTarget().on(focusInEvent, $.proxy(this._focusInHandler, this)).on(focusOutEvent, $.proxy(this._focusOutHandler, this));
        if (beforeActivateExists) {
            var beforeActivateEvent = eventUtils.addNamespace("beforeactivate", namespace);
            this._focusTarget().on(beforeActivateEvent, function(e) {
                if (!$(e.target).is(selectors.focusable)) {
                    e.preventDefault()
                }
            })
        }
    },
    _refreshFocusEvent: function() {
        this._detachFocusEvents();
        this._attachFocusEvents()
    },
    _focusInHandler: function(e) {
        var that = this;
        that._createActionByOption("onFocusIn", {
            beforeExecute: function() {
                that._updateFocusState(e, true)
            },
            excludeValidators: ["readOnly"]
        })({
            jQueryEvent: e
        })
    },
    _focusOutHandler: function(e) {
        var that = this;
        that._createActionByOption("onFocusOut", {
            beforeExecute: function() {
                that._updateFocusState(e, false)
            },
            excludeValidators: ["readOnly", "disabled"]
        })({
            jQueryEvent: e
        })
    },
    _updateFocusState: function(e, isFocused) {
        var target = e.target;
        if ($.inArray(target, this._focusTarget()) !== -1) {
            this._toggleFocusClass(isFocused, $(target))
        }
    },
    _toggleFocusClass: function(isFocused, $element) {
        var $focusTarget = $element && $element.length ? $element : this._focusTarget();
        $focusTarget.toggleClass(FOCUSED_STATE_CLASS, isFocused)
    },
    _hasFocusClass: function(element) {
        var $focusTarget = $(element || this._focusTarget());
        return $focusTarget.hasClass(FOCUSED_STATE_CLASS)
    },
    _attachKeyboardEvents: function() {
        var processor = this.option("_keyboardProcessor") || new KeyboardProcessor({
            element: this._keyboardEventBindingTarget(),
            focusTarget: this._focusTarget()
        });
        this._keyboardProcessor = processor.reinitialize(this._keyboardHandler, this)
    },
    _keyboardHandler: function(options) {
        var e = options.originalEvent,
            key = options.key;
        var keys = this._supportedKeys(),
            func = keys[key];
        if (void 0 !== func) {
            var handler = $.proxy(func, this);
            return handler(e) || false
        } else {
            return true
        }
    },
    _refreshFocusState: function() {
        this._cleanFocusState();
        this._renderFocusState()
    },
    _cleanFocusState: function() {
        var $element = this._focusTarget();
        this._detachFocusEvents();
        this._toggleFocusClass(false);
        $element.removeAttr("tabindex");
        if (this._keyboardProcessor) {
            this._keyboardProcessor.dispose()
        }
    },
    _attachHoverEvents: function() {
        var that = this,
            hoverableSelector = that._activeStateUnit,
            nameStart = eventUtils.addNamespace(hoverEvents.start, UI_FEEDBACK),
            nameEnd = eventUtils.addNamespace(hoverEvents.end, UI_FEEDBACK);
        that._eventBindingTarget().off(nameStart, hoverableSelector).off(nameEnd, hoverableSelector);
        if (that.option("hoverStateEnabled")) {
            var startAction = new Action(function(args) {
                that._hoverStartHandler(args.event);
                var $target = args.element;
                that._refreshHoveredElement($target)
            }, {
                excludeValidators: ["readOnly"]
            });
            that._eventBindingTarget().on(nameStart, hoverableSelector, function(e) {
                startAction.execute({
                    element: $(e.target),
                    event: e
                })
            }).on(nameEnd, hoverableSelector, function(e) {
                that._hoverEndHandler(e);
                that._forgetHoveredElement()
            })
        } else {
            that._toggleHoverClass(false)
        }
    },
    _hoverStartHandler: $.noop,
    _hoverEndHandler: $.noop,
    _attachFeedbackEvents: function() {
        var feedbackAction, feedbackActionDisabled, that = this,
            feedbackSelector = that._activeStateUnit,
            activeEventName = eventUtils.addNamespace(feedbackEvents.active, UI_FEEDBACK),
            inactiveEventName = eventUtils.addNamespace(feedbackEvents.inactive, UI_FEEDBACK);
        that._eventBindingTarget().off(activeEventName, feedbackSelector).off(inactiveEventName, feedbackSelector);
        if (that.option("activeStateEnabled")) {
            var feedbackActionHandler = function(args) {
                var $element = args.element,
                    value = args.value,
                    jQueryEvent = args.jQueryEvent;
                that._toggleActiveState($element, value, jQueryEvent)
            };
            that._eventBindingTarget().on(activeEventName, feedbackSelector, {
                timeout: that._feedbackShowTimeout
            }, function(e) {
                feedbackAction = feedbackAction || new Action(feedbackActionHandler);
                feedbackAction.execute({
                    element: $(e.currentTarget),
                    value: true,
                    jQueryEvent: e
                })
            }).on(inactiveEventName, feedbackSelector, {
                timeout: that._feedbackHideTimeout
            }, function(e) {
                feedbackActionDisabled = feedbackActionDisabled || new Action(feedbackActionHandler, {
                    excludeValidators: ["disabled", "readOnly"]
                });
                feedbackActionDisabled.execute({
                    element: $(e.currentTarget),
                    value: false,
                    jQueryEvent: e
                })
            })
        }
    },
    _toggleActiveState: function($element, value) {
        this._toggleHoverClass(!value);
        $element.toggleClass(ACTIVE_STATE_CLASS, value)
    },
    _refreshHoveredElement: function(hoveredElement) {
        var selector = this._activeStateUnit || this._eventBindingTarget();
        this._forgetHoveredElement();
        this._hoveredElement = hoveredElement.closest(selector);
        this._toggleHoverClass(true)
    },
    _forgetHoveredElement: function() {
        this._toggleHoverClass(false);
        delete this._hoveredElement
    },
    _toggleHoverClass: function(value) {
        if (this._hoveredElement) {
            this._hoveredElement.toggleClass(HOVER_STATE_CLASS, value && this.option("hoverStateEnabled"))
        }
    },
    _toggleDisabledState: function(value) {
        this.element().toggleClass(DISABLED_STATE_CLASS, Boolean(value));
        this._toggleHoverClass(!value);
        this.setAria("disabled", value || void 0)
    },
    _setWidgetOption: function(widgetName, args) {
        if (!this[widgetName]) {
            return
        }
        if ($.isPlainObject(args[0])) {
            $.each(args[0], $.proxy(function(option, value) {
                this._setWidgetOption(widgetName, [option, value])
            }, this));
            return
        }
        var optionName = args[0];
        var value = args[1];
        if (1 === args.length) {
            value = this.option(optionName)
        }
        var widgetOptionMap = this[widgetName + "OptionMap"];
        this[widgetName].option(widgetOptionMap ? widgetOptionMap(optionName) : optionName, value)
    },
    _optionChanged: function(args) {
        switch (args.name) {
            case "disabled":
                this._toggleDisabledState(args.value);
                this._refreshFocusState();
                break;
            case "hint":
                this._renderHint();
                break;
            case "activeStateEnabled":
                this._attachFeedbackEvents();
                break;
            case "hoverStateEnabled":
                this._attachHoverEvents();
                break;
            case "tabIndex":
            case "_keyboardProcessor":
            case "focusStateEnabled":
                this._refreshFocusState();
                break;
            case "onFocusIn":
            case "onFocusOut":
                break;
            case "accessKey":
                this._renderAccessKey();
                break;
            case "visible":
                var visible = args.value;
                this._toggleVisibility(visible);
                if (this._isVisibilityChangeSupported()) {
                    this._checkVisibilityChanged(args.value ? "shown" : "hiding")
                }
                break;
            case "onContentReady":
                this._initContentReadyAction();
                break;
            default:
                this.callBase(args)
        }
    },
    _isVisible: function() {
        return this.callBase() && this.option("visible")
    },
    beginUpdate: function() {
        this._ready(false);
        this.callBase()
    },
    endUpdate: function() {
        this.callBase();
        if (this._initialized) {
            this._ready(true)
        }
    },
    _ready: function(value) {
        if (0 === arguments.length) {
            return this._isReady
        }
        this._isReady = value
    },
    setAria: function() {
        var setAttribute = function(option) {
            var attrName = "role" === option.name || "id" === option.name ? option.name : "aria-" + option.name,
                attrValue = option.value;
            if (null === attrValue || void 0 === attrValue) {
                attrValue = void 0
            } else {
                attrValue = attrValue.toString()
            }
            domUtils.toggleAttr(option.target, attrName, attrValue)
        };
        if (!$.isPlainObject(arguments[0])) {
            setAttribute({
                name: arguments[0],
                value: arguments[1],
                target: arguments[2] || this._getAriaTarget()
            })
        } else {
            var $target = arguments[1] || this._getAriaTarget();
            $.each(arguments[0], function(key, value) {
                setAttribute({
                    name: key,
                    value: value,
                    target: $target
                })
            })
        }
    },
    isReady: function() {
        return this._ready()
    },
    repaint: function() {
        this._refresh()
    },
    focus: function() {
        this._focusTarget().focus()
    },
    registerKeyHandler: function(key, handler) {
        var currentKeys = this._supportedKeys(),
            addingKeys = {};
        addingKeys[key] = handler;
        this._supportedKeys = function() {
            return $.extend(currentKeys, addingKeys)
        }
    }
});
module.exports = Widget;


text:
"use strict";

// Sets up the about/ page

define([],function () {
	$(document).ready(function () {
		var queryInput = $('#styleNameQuery');
		queryInput.keypress(function (e) {
			if (e.which === 13 /* ENTER */) {
				window.location.href = "../searchByName/?style=" + queryInput.val();
				e.preventDefault();
			}
		});
	});
});


text:
namespace Takoyaki
{
    class DX12Context;
    class DX12ConstantBuffer;
    class DX12Device;

    class ConstantBufferImpl
    {
        ConstantBufferImpl(const ConstantBufferImpl&) = delete;
        ConstantBufferImpl& operator=(const ConstantBufferImpl&) = delete;
        ConstantBufferImpl(ConstantBufferImpl&&) = delete;
        ConstantBufferImpl& operator=(ConstantBufferImpl&&) = delete;

    public:
        ConstantBufferImpl(const std::shared_ptr<DX12Context>&, const std::shared_ptr<DX12Device>&, DX12ConstantBuffer&, std::shared_lock<std::shared_timed_mutex>) noexcept;
        ~ConstantBufferImpl() = default;

        void setMatrix4x4(const std::string&, const glm::mat4x4&);

    private:
        std::weak_ptr<DX12Context> context_;    // must own pointer to context for destruction
        std::weak_ptr<DX12Device> device_;      // to update correct frame CB
        DX12ConstantBuffer& cbuffer_;
        std::shared_lock<std::shared_timed_mutex> bufferLock_;    // to avoid removal while user is still using it
    };
}
// namespace Takoyaki


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.github.phiz71</groupId>
    <artifactId>vertx-swagger-parent</artifactId>
    <version>1.5.1-SNAPSHOT</version>
    <relativePath>../..</relativePath>
  </parent>

  <artifactId>vertx-swagger-router</artifactId>

  <name>VertX Swagger Router</name>
  <description>A Vert.X Web Router based on a swagger definition</description>

  <url>https://github.com/phiz71/vertx-swagger/tree/master/modules/vertx-swagger-router</url>

  <licenses>
    <license>
      <name>The Apache License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
    </license>
  </licenses>

  <developers>
    <developer>
      <name>Florent Chamfroy</name>
      <email>florent.chamfroy@gmail.com</email>
      <url>https://github.com/phiz71</url>
      <id>phiz71</id>
    </developer>
  </developers>

  <properties>
    <java.version>1.8</java.version>
    <vertx.version>3.4.2</vertx.version>
    <swagger-parser.version>1.0.26</swagger-parser.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-core</artifactId>
      <version>${vertx.version}</version>
    </dependency>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-rx-java</artifactId>
      <version>${vertx.version}</version>
    </dependency>
    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-web</artifactId>
      <version>${vertx.version}</version>
    </dependency>

    <dependency>
      <groupId>io.swagger</groupId>
      <artifactId>swagger-parser</artifactId>
      <version>${swagger-parser.version}</version>
    </dependency>

    <dependency>
      <groupId>io.vertx</groupId>
      <artifactId>vertx-unit</artifactId>
      <version>${vertx.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>


text:
.. :changes:

Changes
=======

0.1.2 (2015-08-28)

* Fixes bug with field names for the FOOD_DES.txt data file.

* Removes field in NUT_DATA.txt which is not included in the SR27
  release.

* Fixes bug with CSV delimiter used in Python 2.7.

0.1.1 (2015-08-28)

* Not publicly released.

0.1.0 (2015-08-23)

* Initial public release


text:
var mongoose = require('mongoose');
// var assert = require('assert');

var Dishes = require('./models/dishes-1');

// Connection URL
var url = 'mongodb://localhost:27017/conFusion';
mongoose.connect(url, {useMongoClient: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
  // we're connected!
  console.log('Connected correctly to server');

  // create a new user
  var newDish = Dishes({
    name: 'Uthapizza',
    description: 'Test'
  });

  // save the user
  newDish.save(function (err) {
    if (err) throw err;
    console.log('Dish created!');

    // get all the users
    Dishes.find({}, function (err, dishes) {
      if (err) throw err;

      // object of all the users
      console.log(dishes);
      db.collection('dishes').drop(function () {
        db.close();
      });
    });
  });
});


text:
#pragma once
#include <aws/workspaces/WorkSpaces_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/workspaces/model/Snapshot.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace WorkSpaces
{
namespace Model
{
  class AWS_WORKSPACES_API DescribeWorkspaceSnapshotsResult
  {
  public:
    DescribeWorkspaceSnapshotsResult();
    DescribeWorkspaceSnapshotsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DescribeWorkspaceSnapshotsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
Information about the snapshots that can be used to rebuild a WorkSpace.
     * These snapshots include the user volume.

     */
    inline const Aws::Vector<Snapshot>& GetRebuildSnapshots() const{ return m_rebuildSnapshots; }

    /**
     *
Information about the snapshots that can be used to rebuild a WorkSpace.
     * These snapshots include the user volume.

     */
    inline void SetRebuildSnapshots(const Aws::Vector<Snapshot>& value) { m_rebuildSnapshots = value; }

    /**
     *
Information about the snapshots that can be used to rebuild a WorkSpace.
     * These snapshots include the user volume.

     */
    inline void SetRebuildSnapshots(Aws::Vector<Snapshot>&& value) { m_rebuildSnapshots = std::move(value); }

    /**
     *
Information about the snapshots that can be used to rebuild a WorkSpace.
     * These snapshots include the user volume.

     */
    inline DescribeWorkspaceSnapshotsResult& WithRebuildSnapshots(const Aws::Vector<Snapshot>& value) { SetRebuildSnapshots(value); return *this;}

    /**
     *
Information about the snapshots that can be used to rebuild a WorkSpace.
     * These snapshots include the user volume.

     */
    inline DescribeWorkspaceSnapshotsResult& WithRebuildSnapshots(Aws::Vector<Snapshot>&& value) { SetRebuildSnapshots(std::move(value)); return *this;}

    /**
     *
Information about the snapshots that can be used to rebuild a WorkSpace.
     * These snapshots include the user volume.

     */
    inline DescribeWorkspaceSnapshotsResult& AddRebuildSnapshots(const Snapshot& value) { m_rebuildSnapshots.push_back(value); return *this; }

    /**
     *
Information about the snapshots that can be used to rebuild a WorkSpace.
     * These snapshots include the user volume.

     */
    inline DescribeWorkspaceSnapshotsResult& AddRebuildSnapshots(Snapshot&& value) { m_rebuildSnapshots.push_back(std::move(value)); return *this; }

    /**
     *
Information about the snapshots that can be used to restore a WorkSpace.
     * These snapshots include both the root volume and the user volume.

     */
    inline const Aws::Vector<Snapshot>& GetRestoreSnapshots() const{ return m_restoreSnapshots; }

    /**
     *
Information about the snapshots that can be used to restore a WorkSpace.
     * These snapshots include both the root volume and the user volume.

     */
    inline void SetRestoreSnapshots(const Aws::Vector<Snapshot>& value) { m_restoreSnapshots = value; }

    /**
     *
Information about the snapshots that can be used to restore a WorkSpace.
     * These snapshots include both the root volume and the user volume.

     */
    inline void SetRestoreSnapshots(Aws::Vector<Snapshot>&& value) { m_restoreSnapshots = std::move(value); }

    /**
     *
Information about the snapshots that can be used to restore a WorkSpace.
     * These snapshots include both the root volume and the user volume.

     */
    inline DescribeWorkspaceSnapshotsResult& WithRestoreSnapshots(const Aws::Vector<Snapshot>& value) { SetRestoreSnapshots(value); return *this;}

    /**
     *
Information about the snapshots that can be used to restore a WorkSpace.
     * These snapshots include both the root volume and the user volume.

     */
    inline DescribeWorkspaceSnapshotsResult& WithRestoreSnapshots(Aws::Vector<Snapshot>&& value) { SetRestoreSnapshots(std::move(value)); return *this;}

    /**
     *
Information about the snapshots that can be used to restore a WorkSpace.
     * These snapshots include both the root volume and the user volume.

     */
    inline DescribeWorkspaceSnapshotsResult& AddRestoreSnapshots(const Snapshot& value) { m_restoreSnapshots.push_back(value); return *this; }

    /**
     *
Information about the snapshots that can be used to restore a WorkSpace.
     * These snapshots include both the root volume and the user volume.

     */
    inline DescribeWorkspaceSnapshotsResult& AddRestoreSnapshots(Snapshot&& value) { m_restoreSnapshots.push_back(std::move(value)); return *this; }

  private:

    Aws::Vector<Snapshot> m_rebuildSnapshots;

    Aws::Vector<Snapshot> m_restoreSnapshots;
  };

} // namespace Model
} // namespace WorkSpaces
} // namespace Aws


text:
/* @test
 * @bug 4927640
 * @summary Tests the SCTP protocol implementation
 * @author chegar
 */

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.io.IOException;
import java.util.Set;
import java.util.Iterator;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.nio.ByteBuffer;
import com.sun.nio.sctp.AbstractNotificationHandler;
import com.sun.nio.sctp.Association;
import com.sun.nio.sctp.AssociationChangeNotification;
import com.sun.nio.sctp.AssociationChangeNotification.AssocChangeEvent;
import com.sun.nio.sctp.HandlerResult;
import com.sun.nio.sctp.InvalidStreamException;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;
import com.sun.nio.sctp.SctpMultiChannel;
import com.sun.nio.sctp.ShutdownNotification;
import static java.lang.System.out;
import static java.lang.System.err;

public class Branch {
    /* Latches used to synchronize between the client and server so that
     * connections without any IO may not be closed without being accepted */
    final CountDownLatch clientFinishedLatch = new CountDownLatch(1);
    final CountDownLatch serverFinishedLatch = new CountDownLatch(1);

    void test(String[] args) {
        SocketAddress address = null;
        Server server = null;

        if (!Util.isSCTPSupported()) {
            out.println("SCTP protocol is not supported");
            out.println("Test cannot be run");
            return;
        }

        if (args.length == 2) {
            /* requested to connecct to a specific address */
            try {
                int port = Integer.valueOf(args[1]);
                address = new InetSocketAddress(args[0], port);
            } catch (NumberFormatException nfe) {
                err.println(nfe);
            }
        } else {
            /* start server on local machine, default */
            try {
                server = new Server();
                server.start();
                address = server.address();
                debug("Server started and listening on " + address);
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return;
            }
        }

        doTest(address);
    }

    void doTest(SocketAddress peerAddress) {
        SctpMultiChannel channel = null;
        ByteBuffer buffer = ByteBuffer.allocate(Util.LARGE_BUFFER);
        MessageInfo info = MessageInfo.createOutgoing(null, 0);

        try {
            channel = SctpMultiChannel.open();

            /* setup an association implicitly by sending a small message */
            int streamNumber = 0;
            debug("sending to " + peerAddress + " on stream number: " + streamNumber);
            info = MessageInfo.createOutgoing(peerAddress, streamNumber);
            buffer.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
            buffer.flip();
            int position = buffer.position();
            int remaining = buffer.remaining();

            debug("sending small message: " + buffer);
            int sent = channel.send(buffer, info);

            check(sent == remaining, "sent should be equal to remaining");
            check(buffer.position() == (position + sent),
                    "buffers position should have been incremented by sent");

            /* Receive the COMM_UP */
            buffer.clear();
            BranchNotificationHandler handler = new BranchNotificationHandler();
            info = channel.receive(buffer, null, handler);
            check(handler.receivedCommUp(), "COMM_UP no received");
            Set<Association> associations = channel.associations();
            check(!associations.isEmpty(),"There should be some associations");
            Association bassoc = associations.iterator().next();

            /* TEST 1: branch */
            SctpChannel bchannel = channel.branch(bassoc);

            check(!bchannel.getAllLocalAddresses().isEmpty(),
                                   "branched channel should be bound");
            check(!bchannel.getRemoteAddresses().isEmpty(),
                                   "branched channel should be connected");
            check(channel.associations().isEmpty(),
                  "there should be no associations since the only one was branched off");

            buffer.clear();
            info = bchannel.receive(buffer, null, null);
            buffer.flip();
            check(info != null, "info is null");
            check(info.streamNumber() == streamNumber,
                    "message not sent on the correct stream");
            check(info.bytes() == Util.SMALL_MESSAGE.getBytes("ISO-8859-1").
                  length, "bytes received not equal to message length");
            check(info.bytes() == buffer.remaining(), "bytes != remaining");
            check(Util.compare(buffer, Util.SMALL_MESSAGE),
              "received message not the same as sent message");

        } catch (IOException ioe) {
            unexpected(ioe);
        } finally {
            clientFinishedLatch.countDown();
            try { serverFinishedLatch.await(10L, TimeUnit.SECONDS); }
            catch (InterruptedException ie) { unexpected(ie); }
            if (channel != null) {
                try { channel.close(); }
                catch (IOException e) { unexpected (e);}
            }
        }
    }

    class Server implements Runnable
    {
        final InetSocketAddress serverAddr;
        private SctpMultiChannel serverChannel;

        public Server() throws IOException {
            serverChannel = SctpMultiChannel.open().bind(null);
            java.util.Set<SocketAddress> addrs = serverChannel.getAllLocalAddresses();
            if (addrs.isEmpty())
                debug("addrs should not be empty");

            serverAddr = (InetSocketAddress) addrs.iterator().next();
        }

        public void start() {
            (new Thread(this, "Server-"  + serverAddr.getPort())).start();
        }

        public InetSocketAddress address() {
            return serverAddr;
        }

        @Override
        public void run() {
            ByteBuffer buffer = ByteBuffer.allocateDirect(Util.LARGE_BUFFER);
            try {
                MessageInfo info;

                /* receive a small message */
                do {
                    info = serverChannel.receive(buffer, null, null);
                    if (info == null) {
                        fail("Server: unexpected null from receive");
                            return;
                    }
                } while (!info.isComplete());

                buffer.flip();
                check(info != null, "info is null");
                check(info.streamNumber() == 0,
                        "message not sent on the correct stream");
                check(info.bytes() == Util.SMALL_MESSAGE.getBytes("ISO-8859-1").
                      length, "bytes received not equal to message length");
                check(info.bytes() == buffer.remaining(), "bytes != remaining");
                check(Util.compare(buffer, Util.SMALL_MESSAGE),
                  "received message not the same as sent message");

                check(info != null, "info is null");
                Set<Association> assocs = serverChannel.associations();
                check(assocs.size() == 1, "there should be only one association");

                /* echo the message */
                debug("Server: echoing first message");
                buffer.flip();
                int bytes = serverChannel.send(buffer, info);
                debug("Server: sent " + bytes + "bytes");

                clientFinishedLatch.await(10L, TimeUnit.SECONDS);
                serverFinishedLatch.countDown();
            } catch (IOException ioe) {
                unexpected(ioe);
            } catch (InterruptedException ie) {
                unexpected(ie);
            } finally {
                try { if (serverChannel != null) serverChannel.close(); }
                catch (IOException  unused) {}
            }
        }
    }

    class BranchNotificationHandler extends AbstractNotificationHandler<Object>
    {
        boolean receivedCommUp;  // false

        boolean receivedCommUp() {
            return receivedCommUp;
        }

        @Override
        public HandlerResult handleNotification(
                AssociationChangeNotification notification, Object attachment) {
            AssocChangeEvent event = notification.event();
            debug("AssociationChangeNotification");
            debug("  Association: " + notification.association());
            debug("  Event: " + event);

            if (event.equals(AssocChangeEvent.COMM_UP))
                receivedCommUp = true;

            return HandlerResult.RETURN;
        }

        /* A ShutdownNotification handler is provided to ensure that no
         * shutdown notification are being handled since we don't expect
         * to receive them. This is not part of branch testing, it just
         * fits here to test another bug. */
        @Override
        public HandlerResult handleNotification(
                ShutdownNotification notification, Object attachment) {
            debug("ShutdownNotification");
            debug("  Association: " + notification.association());

            fail("Shutdown should not be received");

            return HandlerResult.RETURN;
        }

    }

        //--------------------- Infrastructure ---------------------------
    boolean debug = true;
    volatile int passed = 0, failed = 0;
    void pass() {passed++;}
    void fail() {failed++; Thread.dumpStack();}
    void fail(String msg) {System.err.println(msg); fail();}
    void unexpected(Throwable t) {failed++; t.printStackTrace();}
    void check(boolean cond) {if (cond) pass(); else fail();}
    void check(boolean cond, String failMessage) {if (cond) pass(); else fail(failMessage);}
    void debug(String message) {if(debug) { System.out.println(message); }  }
    public static void main(String[] args) throws Throwable {
        Class<?> k = new Object(){}.getClass().getEnclosingClass();
        try {k.getMethod("instanceMain",String[].class)
                .invoke( k.newInstance(), (Object) args);}
        catch (Throwable e) {throw e.getCause();}}
    public void instanceMain(String[] args) throws Throwable {
        try {test(args);} catch (Throwable t) {unexpected(t);}
        System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
        if (failed > 0) throw new AssertionError("Some tests failed");}

}


text:
package org.jactiveresource;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * Assemble valid URL's from component parts, encoding as necessary. There are
 * methods to add path components and query strings.
 *
 *
Anatomy of a URL

 *

 * A picture is worth a thousand words, especially if it's ASCII Art. This
 * stunning image is reproduced from RFC 3986
 *
 *
 *

 *        foo://example.com:8042/over/there?name=ferret#nose
 *        \_/   \______________/\_________/ \_________/ \__/
 *         |           |            |            |        |
 *      scheme     authority       path        query   fragment
 *

 *
 *
 * The URL class in Java is too stringent to accept our use cases here, namely
 * you can not create a URL class that excludes the scheme and authority
 * portions of a URL. However, Java does include a URI class which is suitable
 * for our needs.
 *
 *
Usage Overview

 *

 * The URLBuilder class doesn't help you build the scheme or authority parts of
 * a URL. The URI class in java.net handles that part perfectly well. This class
 * helps you with the path, query, and fragment parts of a URL.
 *

 * Since this class relies on the URI class to handle the scheme and authority
 * parts of a URI, we frequently refer to them together. We've chosen the term
 * base. It's short and descriptive.
 *

 * Here's a few examples of using URLBuilder to construct URL's. Here's an easy
 * one:
 *
 *
 *

 * URI base = new URI("http://www.example.com");
 * URLBuilder urlb = new URLBuilder(base);
 * urlb.add("yellow").add("brick");
 * urlb.add("road.html");
 * assertEquals("http://www.example.com/yellow/brick/road.html",urlb.toString());
 *

 *
 *
 * Here's one with a query string:
 *
 *
 *

 * URI base = new URI("http://www.example.com");
 * URLBuilder urlb = new URLBuilder(base);
 * urlb.add("people.xml").addQuery("title","manager");
 * assertEquals("http://www.example.com/people.xml?title=manager",urlb.toString());
 *

 *
 *
 * All of the {@link #add(Object)} and {@link #addQuery(Object, Object)} methods
 * do their thing, but also return this. Which means you can chain
 * the methods together like we have done in both of our examples so far.
 *
 * We don't have to have a base, we can create just the path component and the
 * query string:.
 *
 *
 *

 * URLBuilder urlb = new URLBuilder();
 * urlb.add("people.xml")
 * urlb.addQuery("title","manager");
 * assertEquals("people.xml?title=manager",urlb.toString());
 *

 *
 *
 * @version $LastChangedRevision$

 *          $LastChangedDate$
 * @author $LastChangedBy$
 */
public class URLBuilder {

	// this separates the segments of the path
	private static final char PATH_SEGMENT_SEPARATOR = '/';
	// this separates the entire query string from the rest of the URL
	private static final char QUERY_DELIMITER = '?';
	// the separates the various query parameters from each other
	private static final char QUERY_PARAM_SEPARATOR = '&';
	// join the key and value into a single query parameter
	private static final char QUERY_PARAM_JOINER = '=';
	// this separates the fragment from the rest of the URL
	private static final char FRAGMENT_DELIMITER = '#';

	private static final String UTF8 = "UTF-8";

	private URI base;
	private ArrayList<String> path;
	private ArrayList<QueryParam> query;
	private String fragment;

	/**
	 * Create an empty URL builder, no base, no path.
	 */
	public URLBuilder() {
		init();
	}

	/**
	 * Create a new URL builder using an existing URL as a base.
	 *
	 * @param base
	 *            an existing URI fragment
	 * @throws MalformedURLException
	 */
	public URLBuilder(URI base) throws MalformedURLException {
		init();
		this.setBase(base);
	}

	/**
	 * Create a URL builder with a path. In the example below, the URL's for A
	 * and B are the same.
	 *
	 *
	 *

	 * URLBuilder a = new URLBuilder();
	 * a.add("people.xml");
	 * URLBuilder b = new URLBuilder("people.xml");
	 * assertEquals(a.toString(), b.toString())
	 * assertEquals("/people.xml", a.toString());
	 *

	 *
	 *
	 * @param path
	 *            the path to start the URL with
	 */
	public URLBuilder(String path) {
		init();
		this.add(path);
	}

	private void init() {
		clearPath();
		clearQuery();
	}

	/**
	 * Return the base URI object for the URLBuilder instance.
	 *
	 * @return the base URI
	 */
	public URI getBase() {
		return base;
	}

	/**
	 * Set the base URI to be used for this URLBuilder instance. The scheme,
	 * authority, and path components, if present, will be used as the base for
	 * this URLBuilder object. Query parameters and fragments in
	 * base will be silently ignored.
	 *
	 * If you pass an opaque URI, a MalformedURLException will be thrown.
	 *
	 * @param base
	 * @throws MalformedURLException
	 */
	public void setBase(URI base) throws MalformedURLException {
		StringBuffer newurl = new StringBuffer();
		if (base.isOpaque()) {
			throw new MalformedURLException();
		}
		if (base.getScheme() != null) {
			// we assume you have scheme and authority
			newurl.append(base.getScheme());
			newurl.append("://");
			newurl.append(base.getAuthority());
		}
		newurl.append(base.getPath());
		try {
			this.base = new URI(newurl.toString());
		} catch (URISyntaxException e) {
			// Uh-oh
		}
	}

	/**
	 * Append a path component to the URL. Adding slashes is taken care of for
	 * you. If you want "/people/1/contacts.xml" then you have two choices:
	 *
	 *
	 *

	 * URLBuilder u = new URLBuilder();
	 * u.add("people").add("1").add("contacts.xml");
	 *
	 * URLBuilder v = new URLBuilder();
	 * u.add("/people/1/contacts.xml");
	 *

	 *
	 *
	 *
	 * If you want "http://localhost:3000/people/1/contacts.xml" then do:
	 *
	 *
	 *

	 * URLBuilder u = new URLBuilder("http://localhost:3000");
	 * u.add("people").add("1").add("contacts.xml");
	 *

	 *
	 *
	 * This method can not be used to set the scheme or authority segments of
	 * the url.
	 *
	 * @param pathcomponent
	 *            any object that can render itself as a string
	 *
	 * @return self
	 */
	public URLBuilder add(Object pathcomponent) {
		StringTokenizer st = new StringTokenizer(pathcomponent.toString(),
				Character.toString(PATH_SEGMENT_SEPARATOR));
		while (st.hasMoreTokens()) {
			path.add(st.nextToken());
		}
		return this;
	}

	/**
	 * clear all path components
	 */
	public void clearPath() {
		this.path = new ArrayList<String>();
	}

	/**
	 * Add a query parameter to the URL. You can do lots of fun stuff with this.
	 * As long as the key and the value both return a useful .toString(), you
	 * are good to go.
	 *

	 * If you pass a value that implements Iterable, then you will get a query
	 * parameter added for each value returned by hasNext(). You can also pass a
	 * value that is an array[] of somethings and get the same behavior.
	 *
	 * @param key
	 * @param value
	 * @return self
	 */
	public URLBuilder addQuery(Object key, Object value) {
		query.add(new QueryParam(key, value));
		return this;
	}

	/**
	 * Add a bunch of query parameters from a Map. This method provides
	 * compatability with the query parameters provided by
	 * javax.servlet.ServletRequest
	 *
	 * @param params
	 * @return self
	 */
	public URLBuilder addQuery(Map<Object, Object> params) {
		for (Map.Entry<Object, Object> e : params.entrySet())
			query.add(new QueryParam(e.getKey(), e.getValue()));
		return this;
	}

	/**
	 * Add just the query part (ignore the path) from another URLBuilder and add
	 * it to this URLBuilder.
	 *
	 * @param params
	 * @return self
	 */
	public URLBuilder addQuery(URLBuilder params) {
		query.addAll(params.query);
		return this;
	}

	/**
	 * clear all query parameters
	 */
	public void clearQuery() {
		this.query = new ArrayList<QueryParam>();
	}

	/**
	 * Set the fragment for this URL. Don't put a question mark or a slash in
	 * your fragment or an IllegalArgumentException will be thrown.
	 *
	 * @param fragment
	 *            the fragment to be attached to the URL
	 */
	public void setFragment(String fragment) {
		if (fragment.contains(String.valueOf(PATH_SEGMENT_SEPARATOR))
				|| fragment.contains(String.valueOf(QUERY_DELIMITER))) {
			throw new IllegalArgumentException();
		}
		this.fragment = fragment;
	}

	/**
	 * get the fragment to be attached to the URL
	 *
	 * @return the fragment to be attached to the URL
	 */
	public String getFragment() {
		return this.fragment;
	}

	/**
	 * clear any fragment associated with this URL
	 */
	public void clearFragment() {
		this.fragment = null;
	}

	/**
	 * turn this URL builder object into a URLEncoded string
	 */
	public String toString() {
		Iterator<String> pi;
		Iterator<URLBuilder.QueryParam> qi;
		StringBuffer out = new StringBuffer();

		// first the base
		if (base != null)
			out.append(base.toString());

		// then the path
		if ((pi = path.iterator()).hasNext()) {
			if (out.length() == 0) {
				// nothing there yet but we have a path; tack on a slash
				out.append(PATH_SEGMENT_SEPARATOR);
			} else {
				// we have something already, see if it ends with a slash
				// if not, add one
				if (out.charAt(out.length() - 1) != PATH_SEGMENT_SEPARATOR)
					out.append(PATH_SEGMENT_SEPARATOR);
			}

			try {
				out.append(URLEncoder.encode(pi.next(), UTF8));
				while (pi.hasNext())
					out.append(PATH_SEGMENT_SEPARATOR).append(
							URLEncoder.encode(pi.next(), UTF8));
			} catch (UnsupportedEncodingException e) {
			}
		}

		// the query string
		if ((qi = query.iterator()).hasNext()) {
			out.append(QUERY_DELIMITER);
			out.append(qi.next().toString());
			while (qi.hasNext())
				out.append(QUERY_PARAM_SEPARATOR).append(qi.next().toString());
		}

		// and finally the fragment
		if (this.fragment != null) {
			try {
				out.append(FRAGMENT_DELIMITER);
				out.append(URLEncoder.encode(this.fragment, UTF8));
			} catch (UnsupportedEncodingException e) {
			}
		}
		return out.toString();
	}

	/**
	 * turn this URLBuilder object into a new URI
	 *
	 * @return a new URI object
	 */
	public URI toURI() {
		try {
			return new URI(toString());
		} catch (URISyntaxException e) {
			// if this happens the URLBuilder class is broken
			throw new RuntimeException(e);
		}
	}

	/**
	 * shamelessly took the LinkTool class
	 * in Velocity Tools 1.4 and improved it
	 *
	 * @version $LastChangedRevision$

	 *          $LastChangedDate$
	 * @author $LastChangedBy$
	 */
	public final class QueryParam {

		private final Object key;
		private final Object value;

		/**
		 * Create a new query parameter
		 *
		 * @param key
		 *            query pair
		 * @param value
		 *            query value
		 */
		public QueryParam(Object key, Object value) {
			this.key = key;
			this.value = value;
		}

		/**
		 * Return the URL-encoded query string.
		 */
		public String toString() {
			StringBuffer out = new StringBuffer();
			try {
				String encodedKey = URLEncoder.encode(key.toString(), UTF8);
				if (value == null) {
					out.append(encodedKey).append(QUERY_PARAM_JOINER);

				} else if (Iterable.class.isInstance(value)) {
					// if it's something iterable, then spin through it
					Iterator<?> i;
					if ((i = ((Iterable<?>) value).iterator()).hasNext()) {
						out.append(encodedKey);
						out.append(QUERY_PARAM_JOINER);
						out.append(i.next().toString());

						while (i.hasNext()) {
							out.append(QUERY_PARAM_SEPARATOR);
							out.append(encodedKey);
							out.append(QUERY_PARAM_JOINER);
							out.append(i.next().toString());
						}
					}

				} else if (value instanceof Object[]) {
					// we'll take array's too
					Object[] array = (Object[]) value;
					for (int i = 0; i < array.length; i++) {
						out.append(encodedKey);
						out.append(QUERY_PARAM_JOINER);
						if (array[i] != null) {
							out.append(URLEncoder.encode(
									String.valueOf(array[i]), UTF8));
						}
						if (i + 1 < array.length) {
							out.append(QUERY_PARAM_SEPARATOR);
						}
					}

				} else {
					out.append(encodedKey);
					out.append(QUERY_PARAM_JOINER);
					out.append(URLEncoder.encode(String.valueOf(value), UTF8));
				}
			} catch (UnsupportedEncodingException e) {
				// make sure we return an empty string
				out = new StringBuffer();
			}

			return out.toString();
		}
	}
}


text:
from .r_dependencies import *
from .r_base import r_base
class r_generalizedSimulatedAnnealing(r_base):

    def calculate_generalizedSimulatedAnnealing(self):
        '''generalized simulated annealing
        requires the GenSA package
        e.g.
        '''
        # TODO
        # Call to R
        try:
            # format the data into R objects
            # call tune
            r_statement = ('concentrations_m = matrix(concentrations, nrow = %s, ncol = %s, byrow = TRUE)' %(len(cn_sorted),len(sns_sorted)));
            ans = robjects.r(r_statement);
            return
        except Exception as e:
            print(e);
            exit(-1);


text:
Full bash autocompletion for wdltool

Simply source this file from bash to get autocompletion for wdltool, for example from your Downloads folder.
```
source ~/Downloads/wdltool
```

If your wdltool executable is called something else, you'll have to modify the last line.
For example, if you just downloaded the jar file and put it in your PATH, change the last line to:
```
complete -F _wdl wdltool-0.8.jar
```


text: module.exports = require("./scrape-linkedin");


text:
@interface UserInfoViewController ()

@end

@implementation UserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor purpleColor];
}
- (void)refreshUserInformation {
    NSLog(@"User Name : %@, User Age : %ld", self.name, [self.age integerValue]);
}

@end


text:
                    Supir

                         Supir

                <button class="btn btn-success" onclick="addData()"> Tambah
                </button>
                <button class="btn btn-default" onclick="reloadTable()">
                    Reload
                </button>

                            No
                            Nama Supir
                            No. HP
                            Status
                            Action

                            No
                            Nama Supir
                            No. HP
                            Status
                            Action

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Form Supir

                <form action="#" id="form" class="form-horizontal">
                    <input type="hidden" value="" name="driver_id"/>

                            Nama

                                <input id="driver_name" name="driver_name" class="form-control" type="text">

                            No. Handphone

                                <input id="driver_handphone" name="driver_handphone" class="form-control" type="text">

                            Alamat

                                <textarea id="driver_address" name="driver_address" class="form-control"></textarea>

                            Keterangan

                                <textarea id="driver_information" name="driver_information" class="form-control"></textarea>

                            Status

                                <select id="driver_status" name="driver_status" class="form-control">
                                    <option value="">--Pilih Salah Satu--</option>
                                    <option value="0">Tidak Aktif</option>
                                    <option value="1">Aktif</option>
                                </select>

                </form>

                <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Simpan</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Batal</button>


text:
package de.danoeh.antennapod.core.util.playback;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;

import java.util.List;
import java.util.concurrent.Callable;

import de.danoeh.antennapod.core.feed.Chapter;
import de.danoeh.antennapod.core.feed.MediaType;
import de.danoeh.antennapod.core.util.ChapterUtils;

/** Represents a media file that is stored on the local storage device. */
public class ExternalMedia implements Playable {

	public static final int PLAYABLE_TYPE_EXTERNAL_MEDIA = 2;
	public static final String PREF_SOURCE_URL = "ExternalMedia.PrefSourceUrl";
	public static final String PREF_POSITION = "ExternalMedia.PrefPosition";
	public static final String PREF_MEDIA_TYPE = "ExternalMedia.PrefMediaType";
	public static final String PREF_LAST_PLAYED_TIME = "ExternalMedia.PrefLastPlayedTime";

	private String source;

	private String episodeTitle;
	private String feedTitle;
	private MediaType mediaType = MediaType.AUDIO;
	private List<Chapter> chapters;
	private int duration;
	private int position;
	private long lastPlayedTime;

	public ExternalMedia(String source, MediaType mediaType) {
		super();
		this.source = source;
		this.mediaType = mediaType;
	}

	public ExternalMedia(String source, MediaType mediaType, int position, long lastPlayedTime) {
		this(source, mediaType);
		this.position = position;
		this.lastPlayedTime = lastPlayedTime;
	}

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(source);
		dest.writeString(mediaType.toString());
		dest.writeInt(position);
		dest.writeLong(lastPlayedTime);
	}

	@Override
	public void writeToPreferences(Editor prefEditor) {
		prefEditor.putString(PREF_SOURCE_URL, source);
		prefEditor.putString(PREF_MEDIA_TYPE, mediaType.toString());
		prefEditor.putInt(PREF_POSITION, position);
		prefEditor.putLong(PREF_LAST_PLAYED_TIME, lastPlayedTime);
	}

	@Override
	public void loadMetadata() throws PlayableException {
		MediaMetadataRetriever mmr = new MediaMetadataRetriever();
		try {
			mmr.setDataSource(source);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
			throw new PlayableException(
					"IllegalArgumentException when setting up MediaMetadataReceiver");
		} catch (RuntimeException e) {
			// http://code.google.com/p/android/issues/detail?id=39770
			e.printStackTrace();
			throw new PlayableException(
					"RuntimeException when setting up MediaMetadataRetriever");
		}
		episodeTitle = mmr
				.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
		feedTitle = mmr
				.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
        try {
		    duration = Integer.parseInt(mmr
				.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
        } catch (NumberFormatException e) {
            e.printStackTrace();
            throw new PlayableException("NumberFormatException when reading duration of media file");
        }
		ChapterUtils.loadChaptersFromFileUrl(this);
	}

	@Override
	public void loadChapterMarks() {

	}

	@Override
	public String getEpisodeTitle() {
		return episodeTitle;
	}

	@Override
	public Callable<String> loadShownotes() {
		return () -> "";
	}

	@Override
	public List<Chapter> getChapters() {
		return chapters;
	}

	@Override
	public String getWebsiteLink() {
		return null;
	}

	@Override
	public String getPaymentLink() {
		return null;
	}

	@Override
	public String getFeedTitle() {
		return feedTitle;
	}

	@Override
	public Object getIdentifier() {
		return source;
	}

	@Override
	public int getDuration() {
		return duration;
	}

	@Override
	public int getPosition() {
		return position;
	}

	@Override
	public long getLastPlayedTime() {
		return lastPlayedTime;
	}

	@Override
	public MediaType getMediaType() {
		return mediaType;
	}

	@Override
	public String getLocalMediaUrl() {
		return source;
	}

	@Override
	public String getStreamUrl() {
		return null;
	}

	@Override
	public boolean localFileAvailable() {
		return true;
	}

	@Override
	public boolean streamAvailable() {
		return false;
	}

	@Override
	public void saveCurrentPosition(SharedPreferences pref, int newPosition, long timestamp) {
		SharedPreferences.Editor editor = pref.edit();
		editor.putInt(PREF_POSITION, newPosition);
		editor.putLong(PREF_LAST_PLAYED_TIME, timestamp);
		position = newPosition;
		lastPlayedTime = timestamp;
		editor.commit();
	}

	@Override
	public void setPosition(int newPosition) {
		position = newPosition;
	}

	@Override
	public void setDuration(int newDuration) {
		duration = newDuration;
	}

	@Override
	public void setLastPlayedTime(long lastPlayedTime) {
		this.lastPlayedTime = lastPlayedTime;
	}

	@Override
	public void onPlaybackStart() {

	}

	@Override
	public void onPlaybackCompleted() {

	}

	@Override
	public int getPlayableType() {
		return PLAYABLE_TYPE_EXTERNAL_MEDIA;
	}

	@Override
	public void setChapters(List<Chapter> chapters) {
		this.chapters = chapters;
	}

	public static final Parcelable.Creator<ExternalMedia> CREATOR = new Parcelable.Creator<ExternalMedia>() {
		public ExternalMedia createFromParcel(Parcel in) {
			String source = in.readString();
			MediaType type = MediaType.valueOf(in.readString());
			int position = 0;
			if (in.dataAvail() > 0) {
				position = in.readInt();
			}
			long lastPlayedTime = 0;
			if (in.dataAvail() > 0) {
				lastPlayedTime = in.readLong();
			}

			return new ExternalMedia(source, type, position, lastPlayedTime);
		}

		public ExternalMedia[] newArray(int size) {
			return new ExternalMedia[size];
		}
	};

    @Override
    public Uri getImageUri() {
        if (localFileAvailable()) {
            return new Uri.Builder().scheme(SCHEME_MEDIA).encodedPath(getLocalMediaUrl()).build();
        } else {
            return null;
        }
    }
}


text:
namespace ceres {
namespace internal {

class ProblemImpl;

// The parameter block encodes the location of the user's original value, and
// also the "current state" of the parameter. The evaluator uses whatever is in
// the current state of the parameter when evaluating. This is inlined since the
// methods are performance sensitive.
//
// The class is not thread-safe, unless only const methods are called. The
// parameter block may also hold a pointer to a local parameterization; the
// parameter block does not take ownership of this pointer, so the user is
// responsible for the proper disposal of the local parameterization.
class ParameterBlock {
 public:
  ParameterBlock(double* user_state, int size) {
    Init(user_state, size, NULL);
  }
  ParameterBlock(double* user_state,
                 int size,
                 LocalParameterization* local_parameterization) {
    Init(user_state, size, local_parameterization);
  }

  // The size of the parameter block.
  int Size() const { return size_; }

  // Manipulate the parameter state.
  bool SetState(const double* x) {
    CHECK(x != NULL)
        << "Tried to set the state of constant parameter "
        << "with user location " << user_state_;
    CHECK(!is_constant_)
        << "Tried to set the state of constant parameter "
        << "with user location " << user_state_;

    state_ = x;
    return UpdateLocalParameterizationJacobian();
  }

  // Copy the current parameter state out to x. This is "GetState()" rather than
  // simply "state()" since it is actively copying the data into the passed
  // pointer.
  void GetState(double *x) const {
    if (x != state_) {
      memcpy(x, state_, sizeof(*state_) * size_);
    }
  }

  // Direct pointers to the current state.
  const double* state() const { return state_; }
  const double* user_state() const { return user_state_; }
  double* mutable_user_state() { return user_state_; }
  LocalParameterization* local_parameterization() const {
    return local_parameterization_;
  }
  LocalParameterization* mutable_local_parameterization() {
    return local_parameterization_;
  }

  // Set this parameter block to vary or not.
  void SetConstant() { is_constant_ = true; }
  void SetVarying() { is_constant_ = false; }
  bool IsConstant() const { return is_constant_; }

  // This parameter block's index in an array.
  int index() const { return index_; }
  void set_index(int index) { index_ = index; }

  // This parameter offset inside a larger state vector.
  int state_offset() const { return state_offset_; }
  void set_state_offset(int state_offset) { state_offset_ = state_offset; }

  // This parameter offset inside a larger delta vector.
  int delta_offset() const { return delta_offset_; }
  void set_delta_offset(int delta_offset) { delta_offset_ = delta_offset; }

  // Methods relating to the parameter block's parameterization.

  // The local to global jacobian. Returns NULL if there is no local
  // parameterization for this parameter block. The returned matrix is row-major
  // and has Size() rows and  LocalSize() columns.
  const double* LocalParameterizationJacobian() const {
    return local_parameterization_jacobian_.get();
  }

  int LocalSize() const {
    return (local_parameterization_ == NULL)
        ? size_
        : local_parameterization_->LocalSize();
  }

  // Set the parameterization. The parameterization can be set exactly once;
  // multiple calls to set the parameterization to different values will crash.
  // It is an error to pass NULL for the parameterization. The parameter block
  // does not take ownership of the parameterization.
  void SetParameterization(LocalParameterization* new_parameterization) {
    CHECK(new_parameterization != NULL) << "NULL parameterization invalid.";
    CHECK(new_parameterization->GlobalSize() == size_)
        << "Invalid parameterization for parameter block. The parameter block "
        << "has size " << size_ << " while the parameterization has a global "
        << "size of " << new_parameterization->GlobalSize() << ". Did you "
        << "accidentally use the wrong parameter block or parameterization?";
    if (new_parameterization != local_parameterization_) {
      CHECK(local_parameterization_ == NULL)
          << "Can't re-set the local parameterization; it leads to "
          << "ambiguous ownership.";
      local_parameterization_ = new_parameterization;
      local_parameterization_jacobian_.reset(
          new double[local_parameterization_->GlobalSize() *
                     local_parameterization_->LocalSize()]);
      CHECK(UpdateLocalParameterizationJacobian())
          "Local parameterization Jacobian computation failed"
          "for x: " << ConstVectorRef(state_, Size()).transpose();
    } else {
      // Ignore the case that the parameterizations match.
    }
  }

  // Generalization of the addition operation. This is the same as
  // LocalParameterization::Plus() but uses the parameter's current state
  // instead of operating on a passed in pointer.
  bool Plus(const double *x, const double* delta, double* x_plus_delta) {
    if (local_parameterization_ == NULL) {
      VectorRef(x_plus_delta, size_) = ConstVectorRef(x, size_) +
                                       ConstVectorRef(delta,  size_);
      return true;
    }
    return local_parameterization_->Plus(x, delta, x_plus_delta);
  }

 private:
  void Init(double* user_state,
            int size,
            LocalParameterization* local_parameterization) {
    user_state_ = user_state;
    size_ = size;
    is_constant_ = false;
    state_ = user_state_;

    local_parameterization_ = NULL;
    if (local_parameterization != NULL) {
      SetParameterization(local_parameterization);
    }

    index_ = -1;
    state_offset_ = -1;
    delta_offset_ = -1;
  }

  bool UpdateLocalParameterizationJacobian() {
    if (local_parameterization_ == NULL) {
      return true;
    }

    // Update the local to global Jacobian. In some cases this is
    // wasted effort; if this is a bottleneck, we will find a solution
    // at that time.

    const int jacobian_size = Size() * LocalSize();
    InvalidateArray(jacobian_size,
                    local_parameterization_jacobian_.get());
    if (!local_parameterization_->ComputeJacobian(
            state_,
            local_parameterization_jacobian_.get())) {
      LOG(WARNING) << "Local parameterization Jacobian computation failed"
          "for x: " << ConstVectorRef(state_, Size()).transpose();
      return false;
    }

    if (!IsArrayValid(jacobian_size, local_parameterization_jacobian_.get())) {
      LOG(WARNING) << "Local parameterization Jacobian computation returned"
                   << "an invalid matrix for x: "
                   << ConstVectorRef(state_, Size()).transpose()
                   << "\n Jacobian matrix : "
                   << ConstMatrixRef(local_parameterization_jacobian_.get(),
                                     Size(),
                                     LocalSize());
      return false;
    }
    return true;
  }

  double* user_state_;
  int size_;
  bool is_constant_;
  LocalParameterization* local_parameterization_;

  // The "state" of the parameter. These fields are only needed while the
  // solver is running. While at first glance using mutable is a bad idea, this
  // ends up simplifying the internals of Ceres enough to justify the potential
  // pitfalls of using "mutable."
  mutable const double* state_;
  mutable scoped_array<double> local_parameterization_jacobian_;

  // The index of the parameter. This is used by various other parts of Ceres to
  // permit switching from a ParameterBlock* to an index in another array.
  int32 index_;

  // The offset of this parameter block inside a larger state vector.
  int32 state_offset_;

  // The offset of this parameter block inside a larger delta vector.
  int32 delta_offset_;

  // Necessary so ProblemImpl can clean up the parameterizations.
  friend class ProblemImpl;
};

}  // namespace internal
}  // namespace ceres

#endif  // CERES_INTERNAL_PARAMETER_BLOCK_H_


text:
package com.example.franciscogutierrez.hackathon;

import android.app.Application;
import android.test.ApplicationTestCase;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }
}


text:
"""Utilities for batched rejection sampling."""

import numpy as np

import tensorflow.compat.v2 as tf

from tensorflow_probability.python.internal import broadcast_util as bu
from tensorflow_probability.python.internal import prefer_static as ps
from tensorflow_probability.python.internal import samplers

__all__ = [
    'batched_las_vegas_algorithm',
    'batched_rejection_sampler',
]

def batched_las_vegas_algorithm(
    batched_las_vegas_trial_fn, max_trials=None, seed=None, name=None):
  """Batched Las Vegas Algorithm.

  This utility encapsulates the notion of a 'batched las_vegas_algorithm'
  (BLVA): a batch of independent (but not necessarily identical) randomized
  computations, each of which will eventually terminate after an unknown number
  of trials [(Babai, 1979)][1]. The number of trials will in general vary
  across batch points.

  The computation is parameterized by a callable representing a single trial for
  the entire batch. The utility runs the callable repeatedly, keeping track of
  which batch points have succeeded, until all have succeeded.

  Because we keep running the callable repeatedly until we've generated at least
  one good value for every batch point, we may generate multiple good values for
  many batch points. In this case, the particular good batch point returned is
  deliberately left unspecified.

  Args:
    batched_las_vegas_trial_fn: A callable that takes a PRNG seed and returns
      two values. (1) A structure of Tensors containing the results of the
      computation, all with a shape broadcastable with (2) a boolean mask
      representing whether each batch point succeeded.
    max_trials: An optional integer Tensor giving an upper bound on
      the number of calls to `batched_las_vegas_trial_fn`.  If not
      supplied, no limit is enforced.
    seed: Python integer or `Tensor`, for seeding PRNG.
    name: A name to prepend to created ops.
      Default value: `'batched_las_vegas_algorithm'`.

  Returns:
    results: A structure of Tensors representing the results of a
      successful computation for each batch point.
    successes: A boolean Tensor indicating which batch points succeeded.
      This will be all `True` if no `max_trials` limit was supplied.
    num_iters: A scalar int32 tensor, the number of calls to
      `batched_las_vegas_algorithm`.

  #### References

  [1]: Laszlo Babai. Monte-Carlo algorithms in graph isomorphism
       testing. Universite de Montreal, D.M.S. No. 79-10.
  """
  with tf.name_scope(name or 'batched_las_vegas_algorithm'):
    init_seed, loop_seed = samplers.split_seed(seed)
    values, good_values_mask = batched_las_vegas_trial_fn(init_seed)
    num_iters = tf.constant(1)

    def cond(unused_values, good_values_mask, num_iters, unused_seed):
      all_done = tf.reduce_all(good_values_mask)
      if max_trials is not None:
        return ~all_done & (num_iters < max_trials)
      else:
        return ~all_done

    def body(values, good_values_mask, num_iters, seed):
      """Batched Las Vegas Algorithm body."""

      trial_seed, new_seed = samplers.split_seed(seed)
      new_values, new_good_values_mask = batched_las_vegas_trial_fn(trial_seed)

      def pick(new, old):
        return bu.where_left_justified_mask(new_good_values_mask, new, old)

      values = tf.nest.map_structure(pick, new_values, values)

      good_values_mask = good_values_mask | new_good_values_mask

      return values, good_values_mask, num_iters + 1, new_seed

    (values, final_successes, num_iters, _) = tf.while_loop(
        cond, body, (values, good_values_mask, num_iters, loop_seed),
        back_prop=False)
    return values, final_successes, num_iters

def batched_rejection_sampler(
    proposal_fn, target_fn, seed=None, dtype=tf.float32, name=None):
  """Generic batched rejection sampler.

  In each iteration, the sampler generates a batch of proposed samples and
  proposal heights by calling `proposal_fn`. For each such sample point S, a
  uniform random variate U is generated and the sample is accepted if U *
  height(S) <= target(S). The batched rejection sampler keeps track of which
  batch points have been accepted, and continues generating new batches until
  all batch points have been acceped.

  The values returned by `proposal_fn` should satisfy the desiderata of
  rejection sampling: proposed samples should be drawn independently from a
  valid distribution on some domain D that includes the domain of `target_fn`,
  and the proposal must upper bound the target: for all points S in D, height(S)
  >= target(S).

  Args:
    proposal_fn: A callable that takes a Python integer PRNG seed and returns a
      set of proposed samples and the value of the proposal at the samples.
    target_fn: A callable that takes a tensor of samples and returns the value
      of the target at the samples.
    seed: Python integer or `Tensor`, for seeding PRNG.
    dtype: The TensorFlow dtype used internally by `proposal_fn` and
      `target_fn`.  Default value: `tf.float32`.
    name: A name to prepend to created ops.
      Default value: `'batched_rejection_sampler'`.

  Returns:
    results, num_iters: A tensor of samples from the target and a scalar int32
    tensor, the number of calls to `proposal_fn`.
  """
  with tf.name_scope(name or 'batched_rejection_sampler'):
    def randomized_computation(seed):
      """Internal randomized computation."""
      proposal_seed, mask_seed = samplers.split_seed(seed)

      proposed_samples, proposed_values = proposal_fn(proposal_seed)

      # The comparison needs to be strictly less to avoid spurious acceptances
      # when the uniform samples exactly 0 (or when the product underflows to
      # 0).
      target_values = target_fn(proposed_samples)
      good_samples_mask = tf.less(
          proposed_values * samplers.uniform(
              ps.shape(proposed_samples),
              seed=mask_seed,
              dtype=dtype),
          target_values)

      # If either the `proposed_value` or the corresponding `target_value` is
      # `nan`, force that `proposed_sample` to `nan` and accept.  Why?
      #
      # - A `nan` would never be accepted, because tf.less must return False
      #   when either argument is `nan`.
      #
      # - If `nan` happens every time (e.g., due to `nan` in the parameters of
      #   the distribution we are trying to sample from), then we should clearly
      #   return `nan` after going around the rejection loop only once, rather
      #   than looping forever.
      #
      # - If `nan` happens only some of the time, it would silently skew the
      #   distribution on results to always reject, because some of those `nan`
      #   values may have stood for proposals that would have been accepted if
      #   we had computed more accurately.  Instead we forward the `nan`
      #   upstream, so the client can fix their proposal or evaluation
      #   functions.
      #
      # - We force the `proposed_sample` to `nan` because not doing so would
      #   hide a `nan` that occurred in only the `proposed_value` or
      #   `target_value`, silently skewing the distribution on results.
      #
      # - Corner case: if the `proposed_sample` is `nan` but both the
      #   corresponding `proposed_value` and `proposed_target` are for some
      #   reason not `nan`, we trust the user and proceed normally.
      nans = tf.math.is_nan(proposed_values) | tf.math.is_nan(target_values)
      proposed_samples = tf.where(
          nans, tf.cast(np.nan, proposed_samples.dtype), proposed_samples)
      good_samples_mask |= nans
      return proposed_samples, good_samples_mask

    samples, _, num_iters = batched_las_vegas_algorithm(
        randomized_computation, seed=seed)
    return samples, num_iters


text:
package com.google.api.ads.dfp.jaxws.v201403;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for LineItemOperationError.Reason.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="LineItemOperationError.Reason">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="NOT_ALLOWED"/>
 *     <enumeration value="NOT_APPLICABLE"/>
 *     <enumeration value="HAS_COMPLETED"/>
 *     <enumeration value="HAS_NO_ACTIVE_CREATIVES"/>
 *     <enumeration value="CANNOT_ACTIVATE_LEGACY_DFP_LINE_ITEM"/>
 *     <enumeration value="CANNOT_DELETE_DELIVERED_LINE_ITEM"/>
 *     <enumeration value="CANNOT_RESERVE_COMPANY_CREDIT_STATUS_NOT_ACTIVE"/>
 *     <enumeration value="CANNOT_ACTIVATE_INVALID_COMPANY_CREDIT_STATUS"/>
 *     <enumeration value="UNKNOWN"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "LineItemOperationError.Reason")
@XmlEnum
public enum LineItemOperationErrorReason {

    /**
     *
     *                 The operation is not allowed due to lack of permissions.
     *
     *
     */
    NOT_ALLOWED,

    /**
     *
     *                 The operation is not applicable for the current state of the
     *                 {@link LineItem}.
     *
     *
     */
    NOT_APPLICABLE,

    /**
     *
     *                 The {@link LineItem} is completed. A {@link LineItemAction} cannot
     *                 be applied to a line item that is completed.
     *
     *
     */
    HAS_COMPLETED,

    /**
     *
     *                 The {@link LineItem} has no active creatives. A line item cannot be
     *                 activated with no active creatives.
     *
     *
     */
    HAS_NO_ACTIVE_CREATIVES,

    /**
     *
     *                 A {@link LineItem} of type {@link LineItemType#LEGACY_DFP} cannot be
     *                 Activated.
     *
     *
     */
    CANNOT_ACTIVATE_LEGACY_DFP_LINE_ITEM,

    /**
     *
     *                 Deleting an {@link LineItem} that has delivered is not allowed
     *
     *
     */
    CANNOT_DELETE_DELIVERED_LINE_ITEM,

    /**
     *
     *                 Reservation cannot be made for line item because the
     *                 {@link LineItem#advertiserId} it is associated with has
     *                 {@link Company#creditStatus} that is not {@code ACTIVE}
     *                 or {@code ON_HOLD}.
     *
     *
     */
    CANNOT_RESERVE_COMPANY_CREDIT_STATUS_NOT_ACTIVE,

    /**
     *
     *                 Cannot activate line item  because the {@link LineItem#advertiserId}
     *                 it is associated with has {@link Company#creditStatus} that is not
     *                 {@code ACTIVE}, {@code INACTIVE}, or {@code ON_HOLD}.
     *
     *
     */
    CANNOT_ACTIVATE_INVALID_COMPANY_CREDIT_STATUS,

    /**
     *
     *                 The value returned if the actual value is not exposed by the requested API version.
     *
     *
     */
    UNKNOWN;

    public String value() {
        return name();
    }

    public static LineItemOperationErrorReason fromValue(String v) {
        return valueOf(v);
    }

}