text:
/*
 * This var has to be outside the angular factory, otherwise when
 * there are multiple material apps on the same page, each app
 * will create its own instance of this array and the app's IDs
 * will not be unique.
 */
var nextUniqueId = 0, isIos, isAndroid;

// Support material-tools builds.
if (window.navigator) {
  var userAgent = window.navigator.userAgent || window.navigator.vendor || window.opera;
  isIos = userAgent.match(/ipad|iphone|ipod/i);
  isAndroid = userAgent.match(/android/i);
}

/**
 * @ngdoc module
 * @name material.core.util
 * @description
 * Util
 */
angular
.module('material.core')
.factory('$mdUtil', UtilFactory);

/**
 * @ngInject
 */
function UtilFactory($document, $timeout, $compile, $rootScope, $$mdAnimate, $interpolate, $log,
                     $rootElement, $window, $$rAF) {
  // Setup some core variables for the processTemplate method
  var startSymbol = $interpolate.startSymbol(),
    endSymbol = $interpolate.endSymbol(),
    usesStandardSymbols = ((startSymbol === '{{') && (endSymbol === '}}'));

  // Polyfill document.contains for IE11.
  document.contains || (document.contains = function (node) {
    return document.body.contains(node);
  });

  /**
   * Checks if the target element has the requested style by key
   * @param {DOMElement|JQLite} target Target element
   * @param {string} key Style key
   * @param {string=} expectedVal Optional expected value
   * @returns {boolean} Whether the target element has the style or not
   */
  var hasComputedStyle = function (target, key, expectedVal) {
    var hasValue = false;

    if (target && target.length) {
      var computedStyles = $window.getComputedStyle(target[0]);
      hasValue = angular.isDefined(computedStyles[key]) &&
        (expectedVal ? computedStyles[key] == expectedVal : true);
    }

    return hasValue;
  };

  function validateCssValue(value) {
    return !value ? '0' :
      hasPx(value) || hasPercent(value) ? value : value + 'px';
  }

  function hasPx(value) {
    return String(value).indexOf('px') > -1;
  }

  function hasPercent(value) {
    return String(value).indexOf('%') > -1;
  }

  var $mdUtil = {
    dom: {},
    isIos: isIos,
    isAndroid: isAndroid,
    now: window.performance && window.performance.now ?
      angular.bind(window.performance, window.performance.now) : Date.now || function() {
      return new Date().getTime();
    },

    /**
     * Cross-version compatibility method to retrieve an option of a ngModel controller,
     * which supports the breaking changes in the AngularJS snapshot (SHA 87a2ff76af5d0a9268d8eb84db5755077d27c84c).
     * @param {!ngModel.NgModelController} ngModelCtrl
     * @param {!string} optionName
     * @returns {string|number|boolean|Object|undefined}
     */
    getModelOption: function (ngModelCtrl, optionName) {
      if (!ngModelCtrl.$options) {
        return;
      }

      var $options = ngModelCtrl.$options;

      // The newer versions of AngularJS introduced a getOption function and made the option values
      // no longer visible on the $options object.
      return $options.getOption ? $options.getOption(optionName) : $options[optionName];
    },

    /**
     * Determines the current 'dir'ectional value based on the value of 'dir'
     * attribute of the element. If that is not defined, it will try to use
     * a 'dir' attribute of the body or html tag.
     *
     * @param {Object=} attrs a hash object with key-value pairs of normalized
     *     attribute names and their corresponding attribute values.
     * @returns {boolean} true if the element's passed in attributes,
     *     the document, or the body indicates RTL mode, false otherwise.
     */
    isRtl: function(attrs) {
      var dir = angular.isDefined(attrs) && attrs.hasOwnProperty('dir') && attrs.dir;

      switch (dir) {
        case 'ltr':
          return false;

        case 'rtl':
          return true;
      }

      return ($document[0].dir === 'rtl' || $document[0].body.dir === 'rtl');
    },

    /**
     * Bi-directional accessor/mutator used to easily update an element's
     * property based on the current 'dir'ectional value.
     */
    bidi: function(element, property, lValue, rValue) {
      var ltr = !this.isRtl();

      // If accessor
      if (arguments.length == 0) return ltr ? 'ltr' : 'rtl';

      // If mutator
      var elem = angular.element(element);

      if (ltr && angular.isDefined(lValue)) {
        elem.css(property, validateCssValue(lValue));
      }
      else if (!ltr && angular.isDefined(rValue)) {
        elem.css(property, validateCssValue(rValue));
      }
    },

    bidiProperty: function (element, lProperty, rProperty, value) {
      var ltr = !this.isRtl();

      var elem = angular.element(element);

      if (ltr && angular.isDefined(lProperty)) {
        elem.css(lProperty, validateCssValue(value));
        elem.css(rProperty, '');
      }
      else if (!ltr && angular.isDefined(rProperty)) {
        elem.css(rProperty, validateCssValue(value));
        elem.css(lProperty, '');
      }
    },

    clientRect: function(element, offsetParent, isOffsetRect) {
      var node = getNode(element);
      offsetParent = getNode(offsetParent || node.offsetParent || document.body);
      var nodeRect = node.getBoundingClientRect();

      // The user can ask for an offsetRect: a rect relative to the offsetParent,
      // or a clientRect: a rect relative to the page
      var offsetRect = isOffsetRect ?
        offsetParent.getBoundingClientRect() :
        {left: 0, top: 0, width: 0, height: 0};
      return {
        left: nodeRect.left - offsetRect.left,
        top: nodeRect.top - offsetRect.top,
        width: nodeRect.width,
        height: nodeRect.height
      };
    },
    offsetRect: function(element, offsetParent) {
      return $mdUtil.clientRect(element, offsetParent, true);
    },

    /**
     * Annoying method to copy nodes to an array, thanks to IE.
     * @param nodes
     * @return {Array}
     */
    nodesToArray: function(nodes) {
      var results = [], i;
      nodes = nodes || [];

      for (i = 0; i < nodes.length; ++i) {
        results.push(nodes.item(i));
      }
      return results;
    },

    /**
     * Determines the absolute position of the viewport.
     * Useful when making client rectangles absolute.
     * @returns {number}
     */
    getViewportTop: function() {
      // If body scrolling is disabled, then use the cached viewport top value, otherwise get it
      // fresh from the $window.
      if ($mdUtil.disableScrollAround._count && $mdUtil.disableScrollAround._viewPortTop) {
        return $mdUtil.disableScrollAround._viewPortTop;
      } else {
        return $window.scrollY || $window.pageYOffset || 0;
      }
    },

    /**
     * Finds the proper focus target by searching the DOM.
     *
     * @param containerEl
     * @param attributeVal
     * @returns {*}
     */
    findFocusTarget: function(containerEl, attributeVal) {
      var AUTO_FOCUS = this.prefixer('md-autofocus', true);
      var elToFocus;

      elToFocus = scanForFocusable(containerEl, attributeVal || AUTO_FOCUS);

      if (!elToFocus && attributeVal != AUTO_FOCUS) {
        // Scan for deprecated attribute
        elToFocus = scanForFocusable(containerEl, this.prefixer('md-auto-focus', true));

        if (!elToFocus) {
          // Scan for fallback to 'universal' API
          elToFocus = scanForFocusable(containerEl, AUTO_FOCUS);
        }
      }

      return elToFocus;

      /**
       * Can target and nested children for specified Selector (attribute)
       * whose value may be an expression that evaluates to True/False.
       */
      function scanForFocusable(target, selector) {
        var elFound, items = target[0].querySelectorAll(selector);

        // Find the last child element with the focus attribute
        if (items && items.length){
          items.length && angular.forEach(items, function(it) {
            it = angular.element(it);

            // Check the element for the md-autofocus class to ensure any associated expression
            // evaluated to true.
            var isFocusable = it.hasClass('md-autofocus');
            if (isFocusable) elFound = it;
          });
        }
        return elFound;
      }
    },

    /**
     * Disables scroll around the passed parent element.
     * @param {Element|angular.JQLite=} element Origin Element (not used)
     * @param {Element|angular.JQLite=} parent Element to disable scrolling within.
     *   Defaults to body if none supplied.
     * @param {Object=} options Object of options to modify functionality
     *   - disableScrollMask Boolean of whether or not to create a scroll mask element or
     *     use the passed parent element.
     */
    disableScrollAround: function(element, parent, options) {
      options = options || {};

      $mdUtil.disableScrollAround._count = Math.max(0, $mdUtil.disableScrollAround._count || 0);
      $mdUtil.disableScrollAround._count++;

      if ($mdUtil.disableScrollAround._restoreScroll) {
        return $mdUtil.disableScrollAround._restoreScroll;
      }

      var body = $document[0].body;
      var restoreBody = disableBodyScroll();
      var restoreElement = disableElementScroll(parent, options);

      return $mdUtil.disableScrollAround._restoreScroll = function() {
        if (--$mdUtil.disableScrollAround._count <= 0) {
          delete $mdUtil.disableScrollAround._viewPortTop;
          restoreBody();
          restoreElement();
          delete $mdUtil.disableScrollAround._restoreScroll;
        }
      };

      /**
       * Creates a virtual scrolling mask to prevent touchmove, keyboard, scrollbar clicking,
       * and wheel events.
       * @param {!Element|!angular.JQLite} elementToDisable
       * @param {Object=} scrollMaskOptions Object of options to modify functionality
       *   - disableScrollMask Boolean of whether or not to create a scroll mask element or
       *     use the passed parent element.
       * @returns {Function}
       */
      function disableElementScroll(elementToDisable, scrollMaskOptions) {
        var scrollMask;
        var wrappedElementToDisable = angular.element(elementToDisable || body);

        if (scrollMaskOptions.disableScrollMask) {
          scrollMask = wrappedElementToDisable;
        } else {
          scrollMask = angular.element(
            '
' +
            '

' +
            '
');
          wrappedElementToDisable.append(scrollMask);
        }

        /**
         * @param {Event} $event
         */
        function preventDefault($event) {
          $event.preventDefault();
        }

        scrollMask.on('wheel touchmove', preventDefault);

        return function restoreElementScroll() {
          scrollMask.off('wheel touchmove', preventDefault);

          if (!scrollMaskOptions.disableScrollMask && scrollMask[0].parentNode) {
            scrollMask[0].parentNode.removeChild(scrollMask[0]);
          }
        };
      }

      // Converts the body to a position fixed block and translate it to the proper scroll position
      function disableBodyScroll() {
        var documentElement = $document[0].documentElement;

        var prevDocumentStyle = documentElement.style.cssText || '';
        var prevBodyStyle = body.style.cssText || '';

        var viewportTop = $mdUtil.getViewportTop();
        $mdUtil.disableScrollAround._viewPortTop = viewportTop;
        var clientWidth = body.clientWidth;
        var hasVerticalScrollbar = body.scrollHeight > body.clientHeight + 1;

        // Scroll may be set on  element (for example by overflow-y: scroll)
        // but Chrome is reporting the scrollTop position always on .
        // scrollElement will allow to restore the scrollTop position to proper target.
        var scrollElement = documentElement.scrollTop > 0 ? documentElement : body;

        if (hasVerticalScrollbar) {
          angular.element(body).css({
            position: 'fixed',
            width: '100%',
            top: -viewportTop + 'px'
          });
        }

        if (body.clientWidth < clientWidth) {
          body.style.overflow = 'hidden';
        }

        return function restoreScroll() {
          // Reset the inline style CSS to the previous.
          body.style.cssText = prevBodyStyle;
          documentElement.style.cssText = prevDocumentStyle;

          // The scroll position while being fixed
          scrollElement.scrollTop = viewportTop;
        };
      }

    },

    enableScrolling: function() {
      var restoreFn = this.disableScrollAround._restoreScroll;
      restoreFn && restoreFn();
    },

    floatingScrollbars: function() {
      if (this.floatingScrollbars.cached === undefined) {
        var tempNode = angular.element('

').css({
          width: '100%',
          'z-index': -1,
          position: 'absolute',
          height: '35px',
          'overflow-y': 'scroll'
        });
        tempNode.children().css('height', '60px');

        $document[0].body.appendChild(tempNode[0]);
        this.floatingScrollbars.cached = (tempNode[0].offsetWidth == tempNode[0].childNodes[0].offsetWidth);
        tempNode.remove();
      }
      return this.floatingScrollbars.cached;
    },

    /**
     * Mobile safari only allows you to set focus in click event listeners.
     * @param {Element|angular.JQLite} element to focus
     */
    forceFocus: function(element) {
      var node = element[0] || element;

      document.addEventListener('click', function focusOnClick(ev) {
        if (ev.target === node && ev.$focus) {
          node.focus();
          ev.stopImmediatePropagation();
          ev.preventDefault();
          node.removeEventListener('click', focusOnClick);
        }
      }, true);

      var newEvent = document.createEvent('MouseEvents');
      newEvent.initMouseEvent('click', false, true, window, {}, 0, 0, 0, 0,
        false, false, false, false, 0, null);
      newEvent.$material = true;
      newEvent.$focus = true;
      node.dispatchEvent(newEvent);
    },

    /**
     * facade to build md-backdrop element with desired styles
     * NOTE: Use $compile to trigger backdrop postLink function
     */
    createBackdrop: function(scope, addClass) {
      return $compile($mdUtil.supplant('<md-backdrop class="{0}">', [addClass]))(scope);
    },

    /**
     * supplant() method from Crockford's `Remedial Javascript`
     * Equivalent to use of $interpolate; without dependency on
     * interpolation symbols and scope. Note: the '{<token>}' can
     * be property names, property chains, or array indices.
     */
    supplant: function(template, values, pattern) {
      pattern = pattern || /\{([^{}]*)\}/g;
      return template.replace(pattern, function(a, b) {
        var p = b.split('.'),
          r = values;
        try {
          for (var s in p) {
            if (p.hasOwnProperty(s)) {
              r = r[p[s]];
            }
          }
        } catch (e) {
          r = a;
        }
        return (typeof r === 'string' || typeof r === 'number') ? r : a;
      });
    },

    fakeNgModel: function() {
      return {
        $fake: true,
        $setTouched: angular.noop,
        $setViewValue: function(value) {
          this.$viewValue = value;
          this.$render(value);
          this.$viewChangeListeners.forEach(function(cb) {
            cb();
          });
        },
        $isEmpty: function(value) {
          return ('' + value).length === 0;
        },
        $parsers: [],
        $formatters: [],
        $viewChangeListeners: [],
        $render: angular.noop
      };
    },

    /**
     * @param {Function} func original function to be debounced
     * @param {number} wait number of milliseconds to delay (since last debounce reset).
     *  Default value 10 msecs.
     * @param {Object} scope in which to apply the function after debouncing ends
     * @param {boolean} invokeApply should the $timeout trigger $digest() dirty checking
     * @return {Function} A function, that, as long as it continues to be invoked, will not be
     *  triggered. The function will be called after it stops being called for N milliseconds.
     */
    debounce: function(func, wait, scope, invokeApply) {
      var timer;

      return function debounced() {
        var context = scope,
            args = Array.prototype.slice.call(arguments);

        $timeout.cancel(timer);
        timer = $timeout(function() {

          timer = undefined;
          func.apply(context, args);

        }, wait || 10, invokeApply);
      };
    },

    /**
     * The function will not be called unless it has been more than `delay` milliseconds since the
     * last call.
     * @param {Function} func original function to throttle
     * @param {number} delay number of milliseconds to delay
     * @return {Function} a function that can only be triggered every `delay` milliseconds.
     */
    throttle: function throttle(func, delay) {
      var recent;
      return function throttled() {
        var context = this;
        var args = arguments;
        var now = $mdUtil.now();

        if (!recent || (now - recent > delay)) {
          func.apply(context, args);
          recent = now;
        }
      };
    },

    /**
     * Measures the number of milliseconds taken to run the provided callback
     * function. Uses a high-precision timer if available.
     */
    time: function time(cb) {
      var start = $mdUtil.now();
      cb();
      return $mdUtil.now() - start;
    },

    /**
     * Create an implicit getter that caches its `getter()`
     * lookup value
     */
    valueOnUse : function (scope, key, getter) {
      var value = null, args = Array.prototype.slice.call(arguments);
      var params = (args.length > 3) ? args.slice(3) : [];

      Object.defineProperty(scope, key, {
        get: function () {
          if (value === null) value = getter.apply(scope, params);
          return value;
        }
      });
    },

    /**
     * Get a unique ID.
     *
     * @returns {string} an unique numeric string
     */
    nextUid: function() {
      return '' + nextUniqueId++;
    },

    /**
     * Stop watchers and events from firing on a scope without destroying it,
     * by disconnecting it from its parent and its siblings' linked lists.
     * @param {Object} scope to disconnect
     */
    disconnectScope: function disconnectScope(scope) {
      if (!scope) return;

      // we can't destroy the root scope or a scope that has been already destroyed
      if (scope.$root === scope) return;
      if (scope.$$destroyed) return;

      var parent = scope.$parent;
      scope.$$disconnected = true;

      // See Scope.$destroy
      if (parent.$$childHead === scope) parent.$$childHead = scope.$$nextSibling;
      if (parent.$$childTail === scope) parent.$$childTail = scope.$$prevSibling;
      if (scope.$$prevSibling) scope.$$prevSibling.$$nextSibling = scope.$$nextSibling;
      if (scope.$$nextSibling) scope.$$nextSibling.$$prevSibling = scope.$$prevSibling;

      scope.$$nextSibling = scope.$$prevSibling = null;

    },

    /**
     * Undo the effects of disconnectScope().
     * @param {Object} scope to reconnect
     */
    reconnectScope: function reconnectScope(scope) {
      if (!scope) return;

      // we can't disconnect the root node or scope already disconnected
      if (scope.$root === scope) return;
      if (!scope.$$disconnected) return;

      var child = scope;

      var parent = child.$parent;
      child.$$disconnected = false;
      // See Scope.$new for this logic...
      child.$$prevSibling = parent.$$childTail;
      if (parent.$$childHead) {
        parent.$$childTail.$$nextSibling = child;
        parent.$$childTail = child;
      } else {
        parent.$$childHead = parent.$$childTail = child;
      }
    },

    /**
     * Get an element's siblings matching a given tag name.
     *
     * @param {JQLite|angular.element|HTMLElement} element Element to start walking the DOM from
     * @param {string} tagName HTML tag name to match against
     * @returns {Object[]} JQLite
     */
    getSiblings: function getSiblings(element, tagName) {
      var upperCasedTagName = tagName.toUpperCase();
      if (element instanceof angular.element) {
        element = element[0];
      }
      var siblings = Array.prototype.filter.call(element.parentNode.children, function(node) {
        return element !== node && node.tagName.toUpperCase() === upperCasedTagName;
      });
      return siblings.map(function (sibling) {
        return angular.element(sibling);
      });
    },

    /*
     * getClosest replicates jQuery.closest() to walk up the DOM tree until it finds a matching nodeName
     *
     * @param {Node} el Element to start walking the DOM from
     * @param {string|function} validateWith If a string is passed, it will be evaluated against
     * each of the parent nodes' tag name. If a function is passed, the loop will call it with each
     * of the parents and will use the return value to determine whether the node is a match.
     * @param {boolean=} onlyParent Only start checking from the parent element, not `el`.
     * @returns {Node|null} closest matching parent Node or null if not found
     */
    getClosest: function getClosest(el, validateWith, onlyParent) {
      if (angular.isString(validateWith)) {
        var tagName = validateWith.toUpperCase();
        validateWith = function(el) {
          return el.nodeName.toUpperCase() === tagName;
        };
      }

      if (el instanceof angular.element) el = el[0];
      if (onlyParent) el = el.parentNode;
      if (!el) return null;

      do {
        if (validateWith(el)) {
          return el;
        }
      } while (el = el.parentNode);

      return null;
    },

    /**
     * Build polyfill for the Node.contains feature (if needed)
     * @param {Node} node
     * @param {Node} child
     * @returns {Node}
     */
    elementContains: function(node, child) {
      var hasContains = (window.Node && window.Node.prototype && Node.prototype.contains);
      var findFn = hasContains ? angular.bind(node, node.contains) : angular.bind(node, function(arg) {
        // compares the positions of two nodes and returns a bitmask
        return (node === child) || !!(this.compareDocumentPosition(arg) & 16);
      });

      return findFn(child);
    },

    /**
     * Functional equivalent for $element.filter('md-bottom-sheet')
     * useful with interimElements where the element and its container are important...
     *
     * @param {JQLite} element to scan
     * @param {string} nodeName of node to find (e.g. 'md-dialog')
     * @param {boolean=} scanDeep optional flag to allow deep scans; defaults to 'false'.
     * @param {boolean=} warnNotFound optional flag to enable log warnings; defaults to false
     */
    extractElementByName: function(element, nodeName, scanDeep, warnNotFound) {
      var found = scanTree(element);
      if (!found && !!warnNotFound) {
        $log.warn($mdUtil.supplant("Unable to find node '{0}' in element '{1}'.",[nodeName, element[0].outerHTML]));
      }

      return angular.element(found || element);

      /**
       * Breadth-First tree scan for element with matching `nodeName`
       */
      function scanTree(element) {
        return scanLevel(element) || (scanDeep ? scanChildren(element) : null);
      }

      /**
       * Case-insensitive scan of current elements only (do not descend).
       */
      function scanLevel(element) {
        if (element) {
          for (var i = 0, len = element.length; i < len; i++) {
            if (element[i].nodeName.toLowerCase() === nodeName) {
              return element[i];
            }
          }
        }
        return null;
      }

      /**
       * Scan children of specified node
       */
      function scanChildren(element) {
        var found;
        if (element) {
          for (var i = 0, len = element.length; i < len; i++) {
            var target = element[i];
            if (!found) {
              for (var j = 0, numChild = target.childNodes.length; j < numChild; j++) {
                found = found || scanTree([target.childNodes[j]]);
              }
            }
          }
        }
        return found;
      }

    },

    /**
     * Give optional properties with no value a boolean true if attr provided or false otherwise
     */
    initOptionalProperties: function(scope, attr, defaults) {
      defaults = defaults || {};
      angular.forEach(scope.$$isolateBindings, function(binding, key) {
        if (binding.optional && angular.isUndefined(scope[key])) {
          var attrIsDefined = angular.isDefined(attr[binding.attrName]);
          scope[key] = angular.isDefined(defaults[key]) ? defaults[key] : attrIsDefined;
        }
      });
    },

    /**
     * Alternative to $timeout calls with 0 delay.
     * nextTick() coalesces all calls within a single frame
     * to minimize $digest thrashing
     *
     * @param {Function} callback function to be called after the tick
     * @param {boolean=} digest true to call $rootScope.$digest() after callback
     * @param {Object=} scope associated with callback. If the scope is destroyed, the callback will
     *  be skipped.
     * @returns {*}
     */
    nextTick: function(callback, digest, scope) {
      // grab function reference for storing state details
      var nextTick = $mdUtil.nextTick;
      var timeout = nextTick.timeout;
      var queue = nextTick.queue || [];

      // add callback to the queue
      queue.push({scope: scope, callback: callback});

      // set default value for digest
      if (digest == null) digest = true;

      // store updated digest/queue values
      nextTick.digest = nextTick.digest || digest;
      nextTick.queue = queue;

      // either return existing timeout or create a new one
      return timeout || (nextTick.timeout = $timeout(processQueue, 0, false));

      /**
       * Grab a copy of the current queue
       * Clear the queue for future use
       * Process the existing queue
       * Trigger digest if necessary
       */
      function processQueue() {
        var queue = nextTick.queue;
        var digest = nextTick.digest;

        nextTick.queue = [];
        nextTick.timeout = null;
        nextTick.digest = false;

        queue.forEach(function(queueItem) {
          var skip = queueItem.scope && queueItem.scope.$$destroyed;
          if (!skip) {
            queueItem.callback();
          }
        });

        if (digest) $rootScope.$digest();
      }
    },

    /**
     * Processes a template and replaces the start/end symbols if the application has
     * overridden them.
     *
     * @param template The template to process whose start/end tags may be replaced.
     * @returns {*}
     */
    processTemplate: function(template) {
      if (usesStandardSymbols) {
        return template;
      } else {
        if (!template || !angular.isString(template)) return template;
        return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
      }
    },

    /**
     * Scan up dom hierarchy for enabled parent;
     */
    getParentWithPointerEvents: function (element) {
      var parent = element.parent();

      // jqLite might return a non-null, but still empty, parent; so check for parent and length
      while (hasComputedStyle(parent, 'pointer-events', 'none')) {
        parent = parent.parent();
      }

      return parent;
    },

    getNearestContentElement: function (element) {
      var current = element.parent()[0];
      // Look for the nearest parent md-content, stopping at the rootElement.
      while (current && current !== $rootElement[0] && current !== document.body && current.nodeName.toUpperCase() !== 'MD-CONTENT') {
        current = current.parentNode;
      }
      return current;
    },

    /**
     * Checks if the current browser is natively supporting the `sticky` position.
     * @returns {string} supported sticky property name
     */
    checkStickySupport: function() {
      var stickyProp;
      var testEl = angular.element('
');
      $document[0].body.appendChild(testEl[0]);

      var stickyProps = ['sticky', '-webkit-sticky'];
      for (var i = 0; i < stickyProps.length; ++i) {
        testEl.css({
          position: stickyProps[i],
          top: 0,
          'z-index': 2
        });

        if (testEl.css('position') == stickyProps[i]) {
          stickyProp = stickyProps[i];
          break;
        }
      }

      testEl.remove();

      return stickyProp;
    },

    /**
     * Parses an attribute value, mostly a string.
     * By default checks for negated values and returns `false´ if present.
     * Negated values are: (native falsy) and negative strings like:
     * `false` or `0`.
     * @param value Attribute value which should be parsed.
     * @param negatedCheck When set to false, won't check for negated values.
     * @returns {boolean}
     */
    parseAttributeBoolean: function(value, negatedCheck) {
      return value === '' || !!value && (negatedCheck === false || value !== 'false' && value !== '0');
    },

    hasComputedStyle: hasComputedStyle,

    /**
     * Returns true if the parent form of the element has been submitted.
     * @param element An AngularJS or HTML5 element.
     * @returns {boolean}
     */
    isParentFormSubmitted: function(element) {
      var parent = $mdUtil.getClosest(element, 'form');
      var form = parent ? angular.element(parent).controller('form') : null;

      return form ? form.$submitted : false;
    },

    /**
     * Animate the requested element's scrollTop to the requested scrollPosition with basic easing.
     * @param {!Element} element The element to scroll.
     * @param {number} scrollEnd The new/final scroll position.
     * @param {number=} duration Duration of the scroll. Default is 1000ms.
     */
    animateScrollTo: function(element, scrollEnd, duration) {
      var scrollStart = element.scrollTop;
      var scrollChange = scrollEnd - scrollStart;
      var scrollingDown = scrollStart < scrollEnd;
      var startTime = $mdUtil.now();

      $$rAF(scrollChunk);

      function scrollChunk() {
        var newPosition = calculateNewPosition();

        element.scrollTop = newPosition;

        if (scrollingDown ? newPosition < scrollEnd : newPosition > scrollEnd) {
          $$rAF(scrollChunk);
        }
      }

      function calculateNewPosition() {
        var easeDuration = duration || 1000;
        var currentTime = $mdUtil.now() - startTime;

        return ease(currentTime, scrollStart, scrollChange, easeDuration);
      }

      function ease(currentTime, start, change, duration) {
        // If the duration has passed (which can occur if our app loses focus due to $$rAF), jump
        // straight to the proper position
        if (currentTime > duration) {
          return start + change;
        }

        var ts = (currentTime /= duration) * currentTime;
        var tc = ts * currentTime;

        return start + change * (-2 * tc + 3 * ts);
      }
    },

    /**
     * Provides an easy mechanism for removing duplicates from an array.
     *
     *    var myArray = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
     *
     *    $mdUtil.uniq(myArray) => [1, 2, 3, 4]
     *
     * @param {Array} array The array whose unique values should be returned.
     * @returns {Array|void} A copy of the array containing only unique values.
     */
    uniq: function(array) {
      if (!array) { return; }

      return array.filter(function(value, index, self) {
        return self.indexOf(value) === index;
      });
    },

    /**
     * Gets the inner HTML content of the given HTMLElement.
     * Only intended for use with SVG or Symbol elements in IE11.
     * @param {Element} element
     * @returns {string} the inner HTML of the element passed in
     */
    getInnerHTML: function(element) {
      // For SVG or Symbol elements, innerHTML returns `undefined` in IE.
      // Reference: https://stackoverflow.com/q/28129956/633107
      // The XMLSerializer API is supported on IE11 and is the recommended workaround.
      var serializer = new XMLSerializer();

      return Array.prototype.map.call(element.childNodes, function (child) {
        return serializer.serializeToString(child);
      }).join('');
    },

    /**
     * Gets the outer HTML content of the given HTMLElement.
     * Only intended for use with SVG or Symbol elements in IE11.
     * @param {Element} element
     * @returns {string} the outer HTML of the element passed in
     */
    getOuterHTML: function(element) {
      // For SVG or Symbol elements, outerHTML returns `undefined` in IE.
      // Reference: https://stackoverflow.com/q/29888050/633107
      // The XMLSerializer API is supported on IE11 and is the recommended workaround.
      var serializer = new XMLSerializer();
      return serializer.serializeToString(element);
    },

    /**
     * Support: IE 9-11 only
     * documentMode is an IE-only property
     * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
     */
    msie: window.document.documentMode,

    getTouchAction: function() {
      var testEl = document.createElement('div');
      var vendorPrefixes = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];

      for (var i = 0; i < vendorPrefixes.length; i++) {
        var prefix = vendorPrefixes[i];
        var property = prefix ? prefix + 'TouchAction' : 'touchAction';
        if (angular.isDefined(testEl.style[property])) {
          return property;
        }
      }
    },

    /**
     * @param {Event} event the event to calculate the bubble path for
     * @return {EventTarget[]} the set of nodes that this event could bubble up to
     */
    getEventPath: function(event) {
      var path = [];
      var currentTarget = event.target;
      while (currentTarget) {
        path.push(currentTarget);
        currentTarget = currentTarget.parentElement;
      }
      if (path.indexOf(window) === -1 && path.indexOf(document) === -1)
        path.push(document);
      if (path.indexOf(window) === -1)
        path.push(window);
      return path;
    },

    /**
     * Gets the string the user has entered and removes Regex identifiers
     * @param {string} term
     * @returns {string} sanitized string
     */
    sanitize: function(term) {
      if (!term) return term;
      return term.replace(/[\\^$*+?.()|{}[]/g, '\\$&');
    }
  };

  // Instantiate other namespace utility methods

  $mdUtil.dom.animator = $$mdAnimate($mdUtil);

  return $mdUtil;

  function getNode(el) {
    return el[0] || el;
  }
}

/**
 * Since removing jQuery from the demos, some code that uses `element.focus()` is broken.
 * We need to add `element.focus()`, because it's testable unlike `element[0].focus`.
 */
angular.element.prototype.focus = angular.element.prototype.focus || function() {
  if (this.length) {
    this[0].focus();
  }
  return this;
};

angular.element.prototype.blur = angular.element.prototype.blur || function() {
  if (this.length) {
    this[0].blur();
  }
  return this;
};


text:
using PoshCode.Pansies.ColorSpaces;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Host;

namespace PoshCode.Pansies.Commands
{
    [Cmdlet("Get","ColorWheel")]
    public class GetColorWheel : Cmdlet
    {
        [Parameter(ValueFromPipeline = true, Position = 0)]
        [Alias("StartColor")]
        public RgbColor Color { get; set; } = new RgbColor(255, 0, 0);

        // Force the luminance to have "enough" contrast
        [Parameter()]
        public int Count { get; set; } = 7;

        // Assume there are only 16 colors
        [Parameter()]
        public int HueStep { get; set; } = 50;

        [Parameter()]
        [Alias("LightStep")]
        public int BrightStep { get; set; } = 4;

        // # If set, output the input $Color before the complement
        [Parameter()]
        public SwitchParameter Passthru { get; set; }

        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            if (Passthru) {
                Color.Mode = ColorMode.Rgb24Bit;
                WriteObject(Color);
            }
        }
        protected override void EndProcessing()
        {
            base.EndProcessing();

            WriteObject(Gradient.GetRainbow(Color, Count, HueStep, BrightStep).Select( c => { c.Mode = ColorMode.Rgb24Bit; return c; }), true);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Application Debug Mode
    |--------------------------------------------------------------------------
    |
    | When your application is in debug mode, detailed error messages with
    | stack traces will be shown on every error that occurs within your
    | application. If disabled, a simple generic error page is shown.
    |
    */

    'debug' => false,

    /*
    |--------------------------------------------------------------------------
    | Application URL
    |--------------------------------------------------------------------------
    |
    | This URL is used by the console to properly generate URLs when using
    | the Artisan command line tool. You should set this to the root of
    | your application so that it is used when running Artisan tasks.
    |
    */

    'url' => 'http://yourappdomain.com',

];


text:
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
  <env:Header/>
  <env:Body>
    <ns3:EnviarLoteRpsEnvioResponse xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" xmlns:ns3="http://www.betha.com.br/e-nota-contribuinte-ws">
      <EnviarLoteRpsResposta>
        <ListaMensagemRetorno>
          <MensagemRetorno>
            <Codigo>E44</Codigo>
            <Mensagem>CNPJ do prestador inválido</Mensagem>
            <Correcao>Informe o número do CNPJ correto do prestador.</Correcao>
          </MensagemRetorno>
        </ListaMensagemRetorno>
      </EnviarLoteRpsResposta>
    </ns3:EnviarLoteRpsEnvioResponse>
  </env:Body>
</env:Envelope>


text:
from . import BasicDataset
from padding import pad_dataset

class SequentialDataset(BasicDataset):
    """
    Dataset class for sequences.
    """

    def __init__(self, train, valid=None, test=None):
        super(SequentialDataset, self).__init__(train, valid, test)

    def _pad(self, side, length):
        """
        Pad sequences to given length in the left or right side.
        """
        if self._train_set:
            self._train_set = pad_dataset(self._train_set, side, length)
        if self._valid_set:
            self._valid_set = pad_dataset(self._valid_set, side, length)
        if self._test_set:
            self._test_set = pad_dataset(self._test_set, side, length)

    def pad_left(self, length):
        """
        Pad sequences to given length in the left side.
        """
        self._pad('left', length)

    def pad_right(self, length):
        """
        Pad sequences to given length in the left side.
        """
        self._pad('right', length)


text:
/**
 * Support and FAQ: visit Atmel Support
 */
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <asf.h>
#include <conf_test.h>

/**
 * \mainpage
 *
 * \section intro Introduction
 * This is the unit test application for \ref gfx_mono.
 * It tests that drawing different primitives will result in the correct output
 * to a display using a framebuffer in RAM.
 *
 * \section files Main Files
 * - \ref unit_tests.c
 * - \ref conf_test.h
 * - \ref conf_board.h
 * - \ref conf_clock.h
 * - \ref conf_usart_serial.h
 *
 * \section device_info Device Info
 * All AVR devices can be used.
 * This example has been tested with the following setup:
 * - Xplain
 *
 * \section description Description of the unit tests
 * See the documentation for the individual test functions
 * \ref unit_tests.c "here" for detailed descriptions of the
 * tests.
 *
 * \section dependencies Dependencies
 * Relevant module dependencies for this application are:
 * - \ref test_suite_group
 *
 * \section compinfo Compilation info
 * This software was written for the GNU GCC and IAR for AVR. Other compilers
 * may or may not work.
 *
 * \section contactinfo Contact Information
 * For further information, visit Atmel.\n
 * Support and FAQ: http://www.atmel.com/design-support/
 */

//! \name Debug output configuration
//@{
/**
 * \def CONF_TEST_USART
 * \brief USART to redirect STDIO to
 */
/**
 * \def CONF_TEST_BAUDRATE
 * \brief Baudrate of USART
 */
/**
 * \def CONF_TEST_CHARLENGTH
 * \brief Character length (bits) of USART
 */
/**
 * \def CONF_TEST_PARITY
 * \brief Parity mode of USART
 */
/**
 * \def CONF_TEST_STOPBITS
 * \brief Stopbit configuration of USART
 */
//@}

//! \name Helper functions, macros and bitmaps
//@{
//! Bitmap of two 8x8 pixel smileyfaces on top of each other stored in RAM
uint8_t smiley_data[16] = {
	0x3C, 0x42, 0x95, 0xA1, 0xA1, 0x95, 0x42, 0x3C,
	0x3C, 0x42, 0x95, 0xA1, 0xA1, 0x95, 0x42, 0x3C
};

//! Bitmap of two 8x8 pixel smileyfaces on top of each other stored in FLASH
PROGMEM_DECLARE(gfx_mono_color_t, flash_bitmap[16]) = {
	0x3C, 0x42, 0x95, 0xA1, 0xA1, 0x95, 0x42, 0x3C,
	0x3C, 0x42, 0x95, 0xA1, 0xA1, 0x95, 0x42, 0x3C
};

//! \brief Set all bytes in \a buffer to \a value.
#define set_buffer(buffer, value) memset(buffer, value, sizeof(buffer))
//! \brief The height of one lcd page
#define LCD_PAGE_HEIGHT 8

/**
 * \internal
 * \brief Check if a page buffer is equal to another
 *
 * \param test Current test case.
 *
 * \retval true  If the page buffers are the same
 * \retval false If the page buffers are not the same
 */
static bool is_page_correct(uint8_t *test_page, uint8_t *correct_page)
{
	uint16_t column;

	for (column = 0; column < GFX_MONO_LCD_WIDTH; column++) {
		if (test_page[column] != correct_page[column]) {
			return false;
		}
	}

	return true;
}
// @}

/**
 * \internal
 * \brief Test clearing the display
 *
 * This test clears the display, and then checks that each page is empty.
 *
 * \param test Current test case.
 */
static void run_clear_display_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;

	set_buffer(expected_empty, 0x00);

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Get all pages from display and check that each matches the empty page
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		test_assert_true(test, is_page_correct(actual, expected_empty),
			"Page %d not matching expected page", page);
	}
}

/**
 * \internal
 * \brief Test filling the display
 *
 * This test fills the entire display and checks that this is done.
 *
 * \param test Current test case.
 */
static void run_set_display_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_set[GFX_MONO_LCD_WIDTH];
	uint8_t page;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Filled expected page buffer
	set_buffer(expected_set, 0xFF);

	// Fill entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_SET);

	// Get all pages from display and check that each matches the empty page
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		test_assert_true(test, is_page_correct(actual, expected_set),
				"Page %d not matching expected page", page);
	}
}

/**
 * \internal
 * \brief Test drawing a filled rectangle to the every other page of the
 * display
 *
 * This test draws a filled rectangle to every other page of a display and
 * checks that every other page is filled and the rest are empty.
 *
 * \param test Current test case.
 */
static void run_draw_rectangles_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_set[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Fill expected page buffers
	set_buffer(expected_set, 0xFF);
	set_buffer(expected_empty, 0x00);

	// Fill every other page
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		if (page % 2 == 0) {
			gfx_mono_draw_filled_rect(0, LCD_PAGE_HEIGHT * page,
					GFX_MONO_LCD_WIDTH, LCD_PAGE_HEIGHT, GFX_PIXEL_SET);
		}
	}

	// Get all pages from display and check that every other is filled
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		if (page % 2 == 0) {
			test_assert_true(test, is_page_correct(actual, expected_set),
					"Set page %d not matching expected page", page);
		} else {
			test_assert_true(test, is_page_correct(actual, expected_empty),
					"Empty page %d not matching expected page", page);
		}
	}
}

/**
 * \internal
 * \brief Test drawing a filled rectangle inside a page
 *
 * This test draws a filled rectangle inside a page and checks that this
 * is done.
 *
 * \param test Current test case.
 */
static void run_draw_filled_rectangle_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;
	uint8_t i;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Fill page buffer holding rectangle
	set_buffer(expected_page, 0x00);
	for (i = 0; i < 10; i++) {
		expected_page[i + 50] = 0x7C;
	}

	// Fill empty page buffer
	set_buffer(expected_empty, 0x00);

	// Draw a 10x5 filled rectangle at position 50, 10
	gfx_mono_draw_filled_rect(50, 10, 10, 5, GFX_PIXEL_SET);

	// Get all pages from display and check that the rectangle is drawn
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		if (page == 1) {
			test_assert_true(test, is_page_correct(actual, expected_page),
					"Page with rectangle %d not matching expected page",
					page);
		} else {
			test_assert_true(test, is_page_correct(actual, expected_empty),
					"Empty page %d not matching expected page", page);
		}
	}
}

/**
 * \internal
 * \brief Test drawing a filled rectangle spanning two pages
 *
 * This test draws a filled rectangle spanning two pages and checks that this
 * is done.
 *
 * \param test Current test case.
 */
static void run_draw_rectangle_two_pages_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page1[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page2[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;
	uint8_t i;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Fill page buffer holding first part of rectangle
	set_buffer(expected_page1, 0x00);
	for (i = 0; i < 10; i++) {
		expected_page1[i + 48] = 0x80;
	}

	// Fill page buffer holding second part of rectangle
	set_buffer(expected_page2, 0x00);
	for (i = 0; i < 10; i++) {
		expected_page2[i + 48] = 0x7F;
	}

	// Fill empty page buffer
	set_buffer(expected_empty, 0x00);

	// Draw a 10x8 filled rectangle at position 48, 15
	gfx_mono_draw_filled_rect(48, 15, 10, 8, GFX_PIXEL_SET);

	// Get all pages from display and check that the rectangle is drawn
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		if (page == 1) {
			test_assert_true(test, is_page_correct(actual, expected_page1),
					"First page %d with rectangle not matching expected page",
					page);
		} else if (page == 2) {
			test_assert_true(test, is_page_correct(actual, expected_page2),
					"Second page %d with rectangle not matching expected page",
					page);
		} else {
			test_assert_true(test, is_page_correct(actual, expected_empty),
					"Empty page %d not matching expected page", page);
		}
	}
}

/**
 * \internal
 * \brief Test drawing the outline of a rectangle spanning two pages
 *
 * This test draws the outline of a rectangle spanning two pages and checks
 * that this is done.
 *
 * \param test Current test case.
 */
static void run_draw_rectangle_outline_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page1[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page2[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;
	uint8_t i;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Fill page buffer holding first part of rectangle
	set_buffer(expected_page1, 0x00);
	expected_page1[5] = 0xE0;
	for (i = 1; i < 99; i++) {
		expected_page1[i + 5] = 0x20;
	}
	expected_page1[99 + 5] = 0xE0;

	// Fill page buffer holding second part of rectangle
	set_buffer(expected_page2, 0x00);
	expected_page2[5] = 0x7F;
	for (i = 1; i < 99; i++) {
		expected_page2[i + 5] = 0x40;
	}
	expected_page2[99 + 5] = 0x7F;

	// Fill empty page buffer
	set_buffer(expected_empty, 0x00);

	// Draw the outline of a 100x10 rectangle at position 5, 5
	gfx_mono_draw_rect(5, 5, 100, 10, GFX_PIXEL_SET);

	// Get all pages from display and check that the rectangle is drawn
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		if (page == 0) {
			test_assert_true(test, is_page_correct(actual, expected_page1),
					"Page %d with rectangle not matching expected page",
					page);
		} else if (page == 1) {
			test_assert_true(test, is_page_correct(actual, expected_page2),
					"Page %d with rectangle not matching expected page",
					page);
		} else {
			test_assert_true(test, is_page_correct(actual, expected_empty),
					"Empty page %d not matching expected page", page);
		}
	}
}

/**
 * \internal
 * \brief Test drawing the outline of a circle on a page
 *
 * This test draws the outline of a circle and checks that this is done.
 *
 * \param test Current test case.
 */
static void run_draw_circle_outline_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Fill page buffer holding the outlined circle
	set_buffer(expected_page, 0x00);
	expected_page[47] = 0x1C;
	expected_page[48] = 0x22;
	expected_page[49] = 0x41;
	expected_page[50] = 0x41;
	expected_page[51] = 0x41;
	expected_page[52] = 0x22;
	expected_page[53] = 0x1C;

	// Fill empty page buffer
	set_buffer(expected_empty, 0x00);

	// Draw the outline of a circle with radius 3 and centre at position 50, 11
	gfx_mono_draw_circle(50, 11, 3, GFX_PIXEL_SET, GFX_WHOLE);

	// Get all pages from display and check that the circle is drawn
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		if (page == 1) {
			test_assert_true(test, is_page_correct(actual, expected_page),
					"Page %d with outlined circle not matching expected page",
					page);
		} else {
			test_assert_true(test, is_page_correct(actual, expected_empty),
					"Empty page %d not matching expected page", page);
		}
	}
}

/**
 * \internal
 * \brief Test drawing a filled circle spanning two pages
 *
 * This test draws a filled circle spanning two pages and checks that this is
 * done.
 *
 * \param test Current test case.
 */
static void run_draw_filled_circle_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page1[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page2[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Fill first page buffer holding the top part of the circle
	set_buffer(expected_page1, 0x00);
	expected_page1[36] = 0x80;
	expected_page1[37] = 0xC0;
	expected_page1[38] = 0xE0;
	expected_page1[39] = 0xE0;
	expected_page1[40] = 0xE0;
	expected_page1[41] = 0xE0;
	expected_page1[42] = 0xE0;
	expected_page1[43] = 0xC0;
	expected_page1[44] = 0x80;

	// Fill second page buffer holding the lower part of the circle
	set_buffer(expected_page2, 0x00);
	expected_page2[35] = 0x1F;
	expected_page2[36] = 0x3F;
	expected_page2[37] = 0x7F;
	expected_page2[38] = 0xFF;
	expected_page2[39] = 0xFF;
	expected_page2[40] = 0xFF;
	expected_page2[41] = 0xFF;
	expected_page2[42] = 0xFF;
	expected_page2[43] = 0x7F;
	expected_page2[44] = 0x3F;
	expected_page2[45] = 0x1F;

	// Fill empty page buffer
	set_buffer(expected_empty, 0x00);

	// Draw a filled circle with radius 5 and centre at position 40, 18
	gfx_mono_draw_filled_circle(40, 18, 5, GFX_PIXEL_SET, GFX_WHOLE);

	// Get all pages from display and check that the circle is drawn
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		if (page == 1) {
			test_assert_true(test, is_page_correct(actual, expected_page1),
					"Page %d with filled circle not matching expected page",
					page);
		} else if (page == 2) {
			test_assert_true(test, is_page_correct(actual, expected_page2),
					"Page %d with filled circle not matching expected page",
					page);
		} else {
			test_assert_true(test, is_page_correct(actual, expected_empty),
					"Empty page %d not matching expected page", page);
		}
	}
}

/**
 * \internal
 * \brief Test drawing a vertical line
 *
 * This test draws a vertical line and checks that this is done.
 *
 * \param test Current test case.
 */
static void run_draw_vertical_line_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page1[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page2[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Fill page buffer holding the top of the line
	set_buffer(expected_page1, 0x00);
	expected_page1[4] = 0xFC;

	// Fill page buffer holding the bottom of the line
	set_buffer(expected_page2, 0x00);
	expected_page2[4] = 0x1F;

	// Fill empty page buffer
	set_buffer(expected_empty, 0x00);

	// Draw a vertical line at position 4, 2 with length 11
	gfx_mono_draw_vertical_line(4, 2, 11, GFX_PIXEL_SET);

	// Get all pages from display and check that the line is drawn
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		if (page == 0) {
			test_assert_true(test, is_page_correct(actual, expected_page1),
					"Page %d with line not matching expected page",
					page);
		} else if (page == 1) {
			test_assert_true(test, is_page_correct(actual, expected_page2),
					"Page %d with line not matching expected page",
					page);
		} else {
			test_assert_true(test, is_page_correct(actual, expected_empty),
					"Empty page %d not matching expected page", page);
		}
	}
}

/**
 * \internal
 * \brief Test drawing a horizontal line
 *
 * This test draws a horizontal line and checks that this is done.
 *
 * \param test Current test case.
 */
static void run_draw_horizontal_line_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;
	uint8_t i;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Fill page buffer holding the line
	set_buffer(expected_page, 0x00);
	for (i = 0; i < 50; i++) {
		expected_page[i + 10] = 0x10;
	}

	// Fill empty page buffer
	set_buffer(expected_empty, 0x00);

	// Draw a horizontal line at postition 10, 20 with length 50
	gfx_mono_draw_horizontal_line(10, 20, 50, GFX_PIXEL_SET);

	// Get all pages from display and check that the line is drawn
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		if (page == 2) {
			test_assert_true(test, is_page_correct(actual, expected_page),
					"Page %d with line not matching expected page",
					page);
		} else {
			test_assert_true(test, is_page_correct(actual, expected_empty),
					"Empty page %d not matching expected page", page);
		}
	}
}

/**
 * \internal
 * \brief Test drawing a line between to points
 *
 * This test draws a line between two points and checks that this is done.
 *
 * \param test Current test case.
 */
static void run_draw_diagonal_line_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page1[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page2[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Fill first page buffer holding the line
	set_buffer(expected_page1, 0x00);
	expected_page1[0] = 0x03;
	expected_page1[1] = 0x0C;
	expected_page1[2] = 0x30;
	expected_page1[3] = 0xC0;

	// Fill second page buffer holding the line
	set_buffer(expected_page2, 0x00);
	expected_page2[4] = 0x01;

	// Fill empty page buffer
	set_buffer(expected_empty, 0x00);

	// Draw a line between 0,0 and 4, 8
	gfx_mono_draw_line(0, 0, 4, 8, GFX_PIXEL_SET);

	// Get all pages from display and check that the line is drawn
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		if (page == 0) {
			test_assert_true(test, is_page_correct(actual, expected_page1),
					"Page %d with line not matching expected page",
					page);
		} else if (page == 1) {
			test_assert_true(test, is_page_correct(actual, expected_page2),
					"Page %d with line not matching expected page",
					page);
		} else {
			test_assert_true(test, is_page_correct(actual, expected_empty),
					"Empty page %d not matching expected page", page);
		}
	}
}

/**
 * \internal
 * \brief Test drawing a bitmap stored in FLASH
 *
 * This test draws a bitmap to position x = 60, y = 9 and checks that
 * it is aligned with display pages and that it is drawn correctly.
 *
 * \param test Current test case.
 */
static void run_draw_flash_bitmap_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page1[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page2[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;
	struct gfx_mono_bitmap smiley_flash;

	// Setup bitmap for bitmap stored in FLASH
	smiley_flash.type = GFX_MONO_BITMAP_PROGMEM;
	smiley_flash.width = 8;
	smiley_flash.height = 16;
	smiley_flash.data.progmem = flash_bitmap;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Fill first page buffer holding smileys
	set_buffer(expected_page1, 0x00);
	expected_page1[60] = 0x3C;
	expected_page1[61] = 0x42;
	expected_page1[62] = 0x95;
	expected_page1[63] = 0xA1;
	expected_page1[64] = 0xA1;
	expected_page1[65] = 0x95;
	expected_page1[66] = 0x42;
	expected_page1[67] = 0x3C;

	// Fill second page buffer holding smileys
	set_buffer(expected_page2, 0x00);
	expected_page2[60] = 0x3C;
	expected_page2[61] = 0x42;
	expected_page2[62] = 0x95;
	expected_page2[63] = 0xA1;
	expected_page2[64] = 0xA1;
	expected_page2[65] = 0x95;
	expected_page2[66] = 0x42;
	expected_page2[67] = 0x3C;

	// Fill empty page buffer
	set_buffer(expected_empty, 0x00);

	// Output bitmap
	gfx_mono_put_bitmap(&smiley_flash, 60, 9);

	// Get all pages from display and check that the bitmap is drawn
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		if (page == 1) {
			test_assert_true(test, is_page_correct(actual, expected_page1),
					"Page %d with smileys not matching expected page",
					page);
		} else if (page == 2) {
			test_assert_true(test, is_page_correct(actual, expected_page2),
					"Page %d with smileys not matching expected page",
					page);
		} else {
			test_assert_true(test, is_page_correct(actual, expected_empty),
					"Empty page %d not matching expected page", page);
		}
	}
}

/**
 * \internal
 * \brief Test drawing a bitmap stored in RAM
 *
 * This test draws a bitmap to position x = 50, y = 5 and checks that
 * it is aligned with display pages and that it is drawn correctly.
 *
 * \param test Current test case.
 */
static void run_draw_ram_bitmap_test(const struct test_case *test)
{
	uint8_t actual[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page1[GFX_MONO_LCD_WIDTH];
	uint8_t expected_page2[GFX_MONO_LCD_WIDTH];
	uint8_t expected_empty[GFX_MONO_LCD_WIDTH];
	uint8_t page;
	struct gfx_mono_bitmap smiley;

	// Setup bitmap struct for bitmap stored in RAM
	smiley.type = GFX_MONO_BITMAP_RAM;
	smiley.width = 8;
	smiley.height = 16;
	smiley.data.pixmap = smiley_data;

	// Clear entire display
	gfx_mono_draw_filled_rect(0, 0, GFX_MONO_LCD_WIDTH, GFX_MONO_LCD_HEIGHT,
			GFX_PIXEL_CLR);

	// Fill first page buffer holding smileys
	set_buffer(expected_page1, 0x00);
	expected_page1[50] = 0x3C;
	expected_page1[51] = 0x42;
	expected_page1[52] = 0x95;
	expected_page1[53] = 0xA1;
	expected_page1[54] = 0xA1;
	expected_page1[55] = 0x95;
	expected_page1[56] = 0x42;
	expected_page1[57] = 0x3C;

	// Fill second page buffer holding smileys
	set_buffer(expected_page2, 0x00);
	expected_page2[50] = 0x3C;
	expected_page2[51] = 0x42;
	expected_page2[52] = 0x95;
	expected_page2[53] = 0xA1;
	expected_page2[54] = 0xA1;
	expected_page2[55] = 0x95;
	expected_page2[56] = 0x42;
	expected_page2[57] = 0x3C;

	// Fill empty page buffer
	set_buffer(expected_empty, 0x00);

	// Output bitmap
	gfx_mono_put_bitmap(&smiley, 50, 5);

	// Get all pages from display and check that the bitmap is drawn
	for (page = 0; page < GFX_MONO_LCD_PAGES; page++) {
		gfx_mono_get_page(actual, page, 0, GFX_MONO_LCD_WIDTH);
		if (page == 0) {
			test_assert_true(test, is_page_correct(actual, expected_page1),
					"Page %d with smileys not matching expected page", page);
		} else if (page == 1) {
			test_assert_true(test, is_page_correct(actual, expected_page2),
					"Page %d with smileys not matching expected page", page);
		} else {
			test_assert_true(test, is_page_correct(actual, expected_empty),
					"Empty page %d not matching expected page", page);
		}
	}
}
//@}

/**
 * \brief Run gfx_mono unit tests
 */
int main (void)
{
	const usart_serial_options_t usart_serial_options = {
		.baudrate   = CONF_TEST_BAUDRATE,
		.charlength = CONF_TEST_CHARLENGTH,
		.paritytype = CONF_TEST_PARITY,
		.stopbits   = CONF_TEST_STOPBITS,
	};

	sysclk_init();
	board_init();
	gfx_mono_init();

	stdio_serial_init(CONF_TEST_USART, &usart_serial_options);

	// Define all the test cases
	DEFINE_TEST_CASE(clear_display_test, NULL, run_clear_display_test, NULL,
			"Clear display test");
	DEFINE_TEST_CASE(set_display_test, NULL, run_set_display_test, NULL,
			"Set display test");
	DEFINE_TEST_CASE(draw_rectangles_test, NULL, run_draw_rectangles_test,
			NULL, "Draw filled rectangles test");
	DEFINE_TEST_CASE(draw_filled_rectangle_test, NULL,
			run_draw_filled_rectangle_test, NULL,
			"Draw filled rectangle in one page test");
	DEFINE_TEST_CASE(draw_rectangle_two_pages_test, NULL,
			run_draw_rectangle_two_pages_test, NULL,
			"Draw filled rectangle in two pages test");
	DEFINE_TEST_CASE(draw_rectangle_outline_test, NULL,
			run_draw_rectangle_outline_test, NULL,
			"Draw rectangle outline test");
	DEFINE_TEST_CASE(draw_filled_circle_test, NULL,
			run_draw_filled_circle_test, NULL, "Draw filled circle test");
	DEFINE_TEST_CASE(draw_circle_outline_test, NULL,
			run_draw_circle_outline_test, NULL, "Draw circle outline test");
	DEFINE_TEST_CASE(draw_vertical_line_test, NULL,
			run_draw_vertical_line_test, NULL, "Draw vertical line test");
	DEFINE_TEST_CASE(draw_horizontal_line_test, NULL,
			run_draw_horizontal_line_test, NULL, "Draw horizontal line test");
	DEFINE_TEST_CASE(draw_diagonal_line_test, NULL,
			run_draw_diagonal_line_test, NULL,
			"Draw a line between two points test");
	DEFINE_TEST_CASE(draw_flash_bitmap_test, NULL, run_draw_flash_bitmap_test,
			NULL, "Draw bitmap stored in FLASH test");
	DEFINE_TEST_CASE(draw_ram_bitmap_test, NULL, run_draw_ram_bitmap_test,
			NULL, "Draw bitmap stored in RAM test");

	// Put test case addresses in an array
	DEFINE_TEST_ARRAY(gfx_mono_tests) = {
			&clear_display_test,
			&set_display_test,
			&draw_rectangles_test,
			&draw_filled_rectangle_test,
			&draw_rectangle_two_pages_test,
			&draw_rectangle_outline_test,
			&draw_filled_circle_test,
			&draw_circle_outline_test,
			&draw_horizontal_line_test,
			&draw_vertical_line_test,
			&draw_diagonal_line_test,
			&draw_flash_bitmap_test,
			&draw_ram_bitmap_test,
	};

	// Define the test suite
	DEFINE_TEST_SUITE(gfx_mono_suite, gfx_mono_tests, "gfx_mono test suite");

	// Set up the test data pointer and run all tests in the suite
	test_suite_run(&gfx_mono_suite);

	while (1) {
		/* Intentionally left empty. */
	}
}


text:
//
//  CCViewController.h
//  UITouchPassingViewExample
//
//  Created by . Carlin on 3/15/14.
//  Copyright (c) 2014 Carlin Creations. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface CCViewController : UIViewController

    /** When the togglePassing button is tapped */
    - (IBAction)togglePassingTapped:(id)sender;

@end


text:
package aima.logic.fol.inference;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import aima.logic.fol.SubstVisitor;
import aima.logic.fol.Unifier;
import aima.logic.fol.VariableCollector;
import aima.logic.fol.parsing.FOLVisitor;
import aima.logic.fol.parsing.ast.AtomicSentence;
import aima.logic.fol.parsing.ast.ConnectedSentence;
import aima.logic.fol.parsing.ast.Constant;
import aima.logic.fol.parsing.ast.Function;
import aima.logic.fol.parsing.ast.NotSentence;
import aima.logic.fol.parsing.ast.Predicate;
import aima.logic.fol.parsing.ast.QuantifiedSentence;
import aima.logic.fol.parsing.ast.Term;
import aima.logic.fol.parsing.ast.TermEquality;
import aima.logic.fol.parsing.ast.Variable;

/**
 * Abstract base class for Demodulation and Paramodulation algorithms.
 */

/**
 * @author Ciaran O'Reilly
 *
 */
public abstract class AbstractModulation {
	//
	// PROTECTED ATTRIBUTES
	protected VariableCollector variableCollector = new VariableCollector();
	protected Unifier unifier = new Unifier();
	protected SubstVisitor substVisitor = new SubstVisitor();

	//
	// PROTECTED METODS
	//
	protected abstract boolean isValidMatch(Term toMatch,
			Set<Variable> toMatchVariables, Term possibleMatch,
			Map<Variable, Term> substitution);

	protected IdentifyCandidateMatchingTerm getMatchingSubstitution(
			Term toMatch, AtomicSentence expression) {

		IdentifyCandidateMatchingTerm icm = new IdentifyCandidateMatchingTerm(
				toMatch, expression);

		if (icm.isMatch()) {
			return icm;
		}

		// indicates no match
		return null;
	}

	protected class IdentifyCandidateMatchingTerm implements FOLVisitor {
		private Term toMatch = null;
		private Set<Variable> toMatchVariables = null;
		private Term matchingTerm = null;
		private Map<Variable, Term> substitution = null;

		public IdentifyCandidateMatchingTerm(Term toMatch,
				AtomicSentence expression) {
			this.toMatch = toMatch;
			this.toMatchVariables = variableCollector
					.collectAllVariables(toMatch);

			expression.accept(this, null);
		}

		public boolean isMatch() {
			return null != matchingTerm;
		}

		public Term getMatchingTerm() {
			return matchingTerm;
		}

		public Map<Variable, Term> getMatchingSubstitution() {
			return substitution;
		}

		//
		// START-FOLVisitor
		public Object visitPredicate(Predicate p, Object arg) {
			for (Term t : p.getArgs()) {
				// Finish processing if have found a match
				if (null != matchingTerm) {
					break;
				}
				t.accept(this, null);
			}
			return p;
		}

		public Object visitTermEquality(TermEquality equality, Object arg) {
			for (Term t : equality.getArgs()) {
				// Finish processing if have found a match
				if (null != matchingTerm) {
					break;
				}
				t.accept(this, null);
			}
			return equality;
		}

		public Object visitVariable(Variable variable, Object arg) {

			if (null != (substitution = unifier.unify(toMatch, variable))) {
				if (isValidMatch(toMatch, toMatchVariables, variable,
						substitution)) {
					matchingTerm = variable;
				}
			}

			return variable;
		}

		public Object visitConstant(Constant constant, Object arg) {
			if (null != (substitution = unifier.unify(toMatch, constant))) {
				if (isValidMatch(toMatch, toMatchVariables, constant,
						substitution)) {
					matchingTerm = constant;
				}
			}

			return constant;
		}

		public Object visitFunction(Function function, Object arg) {
			if (null != (substitution = unifier.unify(toMatch, function))) {
				if (isValidMatch(toMatch, toMatchVariables, function,
						substitution)) {
					matchingTerm = function;
				}
			}

			if (null == matchingTerm) {
				// Try the Function's arguments
				for (Term t : function.getArgs()) {
					// Finish processing if have found a match
					if (null != matchingTerm) {
						break;
					}
					t.accept(this, null);
				}
			}

			return function;
		}

		public Object visitNotSentence(NotSentence sentence, Object arg) {
			throw new IllegalStateException(
					"visitNotSentence() should not be called.");
		}

		public Object visitConnectedSentence(ConnectedSentence sentence,
				Object arg) {
			throw new IllegalStateException(
					"visitConnectedSentence() should not be called.");
		}

		public Object visitQuantifiedSentence(QuantifiedSentence sentence,
				Object arg) {
			throw new IllegalStateException(
					"visitQuantifiedSentence() should not be called.");
		}

		// END-FOLVisitor
		//
	}

	protected class ReplaceMatchingTerm implements FOLVisitor {
		private Term toReplace = null;
		private Term replaceWith = null;
		private boolean replaced = false;

		public ReplaceMatchingTerm() {
		}

		public AtomicSentence replace(AtomicSentence expression,
				Term toReplace, Term replaceWith) {
			this.toReplace = toReplace;
			this.replaceWith = replaceWith;

			return (AtomicSentence) expression.accept(this, null);
		}

		//
		// START-FOLVisitor
		public Object visitPredicate(Predicate p, Object arg) {
			List<Term> newTerms = new ArrayList<Term>();
			for (Term t : p.getTerms()) {
				Term subsTerm = (Term) t.accept(this, arg);
				newTerms.add(subsTerm);
			}
			return new Predicate(p.getPredicateName(), newTerms);
		}

		public Object visitTermEquality(TermEquality equality, Object arg) {
			Term newTerm1 = (Term) equality.getTerm1().accept(this, arg);
			Term newTerm2 = (Term) equality.getTerm2().accept(this, arg);
			return new TermEquality(newTerm1, newTerm2);
		}

		public Object visitVariable(Variable variable, Object arg) {
			if (!replaced) {
				if (toReplace.equals(variable)) {
					replaced = true;
					return replaceWith;
				}
			}
			return variable;
		}

		public Object visitConstant(Constant constant, Object arg) {
			if (!replaced) {
				if (toReplace.equals(constant)) {
					replaced = true;
					return replaceWith;
				}
			}
			return constant;
		}

		public Object visitFunction(Function function, Object arg) {
			if (!replaced) {
				if (toReplace.equals(function)) {
					replaced = true;
					return replaceWith;
				}
			}

			List<Term> newTerms = new ArrayList<Term>();
			for (Term t : function.getTerms()) {
				Term subsTerm = (Term) t.accept(this, arg);
				newTerms.add(subsTerm);
			}
			return new Function(function.getFunctionName(), newTerms);
		}

		public Object visitNotSentence(NotSentence sentence, Object arg) {
			throw new IllegalStateException(
					"visitNotSentence() should not be called.");
		}

		public Object visitConnectedSentence(ConnectedSentence sentence,
				Object arg) {
			throw new IllegalStateException(
					"visitConnectedSentence() should not be called.");
		}

		public Object visitQuantifiedSentence(QuantifiedSentence sentence,
				Object arg) {
			throw new IllegalStateException(
					"visitQuantifiedSentence() should not be called.");
		}

		// END-FOLVisitor
		//
	}
}


text:
require 'net/http'

module WebService
  attr_accessor :headers,:uri

  def service_request(host, port, request, use_ssl=false)
    http = Net::HTTP.new(host, port)
    if use_ssl
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      http.use_ssl = true
    end
    http.start { |htttp| htttp.request(request) }
  end

  def get(host, port, endpoint, headers)
    request = Net::HTTP::Get.new(endpoint, headers)
    response = service_request(host, port, request)
    response
  end

  def get_uri uri, headers
    @uri = URI.parse(uri)
    get(@uri.host, @uri.port, @uri.path, headers)
  end
end


text:
module Experimental
  module Population
    class Default
      def self.in?(obj, experiment)
        true
      end
    end
  end
end


text:
using GitHub.Authentication;
using GitHub.Models;
using GitHub.Services;
using Microsoft.TeamFoundation.Git.Controls.Extensibility;
using Microsoft.VisualStudio.ComponentModelHost;
using NSubstitute;
using Rothko;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UnitTests
{
    internal static class Substitutes
    {
        public static IGitRepositoriesExt IGitRepositoriesExt { get { return Substitute.For<IGitRepositoriesExt>(); } }
        public static IGitService IGitService { get { return Substitute.For<IGitService>(); } }

        public static IVSServices IVSServices
        {
            get
            {
                var ret = Substitute.For<IVSServices>();
                ret.GetLocalClonePathFromGitProvider().Returns(@"c:\foo\bar");
                return ret;
            }
        }

        public static IOperatingSystem OperatingSystem
        {
            get
            {
                var ret = Substitute.For<IOperatingSystem>();
                // this expansion happens when the GetLocalClonePathFromGitProvider call is setup by default
                // see IVSServices property above
                ret.Environment.ExpandEnvironmentVariables(Args.String).Returns(x => x[0]);
                return ret;
            }
        }

        public static IExportFactoryProvider ExportFactoryProvider { get { return Substitute.For<IExportFactoryProvider>(); } }

        public static IRepositoryCreationService RepositoryCreationService { get { return Substitute.For<IRepositoryCreationService>(); } }
        public static IRepositoryCloneService RepositoryCloneService { get { return Substitute.For<IRepositoryCloneService>(); } }

        public static IRepositoryHosts RepositoryHosts { get { return Substitute.For<IRepositoryHosts>(); } }
        public static IConnection Connection { get { return Substitute.For<IConnection>(); } }
        public static IConnectionManager ConnectionManager { get { return Substitute.For<IConnectionManager>(); } }
        public static ITwoFactorChallengeHandler TwoFactorChallengeHandler { get { return Substitute.For<ITwoFactorChallengeHandler>(); } }

        /// <summary>
        /// This returns a service provider with everything mocked except for
        /// RepositoryCloneService and RepositoryCreationService, which are real
        /// instances.
        /// </summary>
        public static IServiceProvider ServiceProvider { get { return GetServiceProvider();  } }

        /// <summary>
        /// This returns a service provider with mocked IRepositoryCreationService and
        /// IRepositoryCloneService as well as all other services mocked. The regular
        /// GetServiceProvider method (and ServiceProvider property return a IServiceProvider
        /// with real RepositoryCloneService and RepositoryCreationService instances.
        /// </summary>
        /// <returns></returns>
        public static IServiceProvider GetFullyMockedServiceProvider()
        {
            return GetServiceProvider(RepositoryCloneService, RepositoryCreationService);
        }

        /// <summary>
        /// This returns a service provider with everything mocked except for
        /// RepositoryCloneService and RepositoryCreationService, which are real
        /// instances.
        /// </summary>
        /// <param name="cloneService"></param>
        /// <param name="creationService"></param>
        /// <returns></returns>
        public static IServiceProvider GetServiceProvider(
            IRepositoryCloneService cloneService = null,
            IRepositoryCreationService creationService = null,
            IAvatarProvider avatarProvider = null)
        {
            var ret = Substitute.For<IServiceProvider, IUIProvider>();

            var gitservice = IGitService;
            var cm = Substitute.For<SComponentModel, IComponentModel>();
            var cc = new CompositionContainer(CompositionOptions.IsThreadSafe | CompositionOptions.DisableSilentRejection);
            cc.ComposeExportedValue(gitservice);
            ((IComponentModel)cm).DefaultExportProvider.Returns(cc);
            ret.GetService(typeof(SComponentModel)).Returns(cm);

            var os = OperatingSystem;
            var vs = IVSServices;
            var clone = cloneService ?? new RepositoryCloneService(os, vs);
            var create = creationService ?? new RepositoryCreationService(clone);
            avatarProvider = avatarProvider ?? Substitute.For<IAvatarProvider>();
            ret.GetService(typeof(IGitRepositoriesExt)).Returns(IGitRepositoriesExt);
            ret.GetService(typeof(IGitService)).Returns(gitservice);
            ret.GetService(typeof(IVSServices)).Returns(vs);
            ret.GetService(typeof(IOperatingSystem)).Returns(os);
            ret.GetService(typeof(IRepositoryCloneService)).Returns(clone);
            ret.GetService(typeof(IRepositoryCreationService)).Returns(create);
            ret.GetService(typeof(IRepositoryHosts)).Returns(RepositoryHosts);
            ret.GetService(typeof(IExportFactoryProvider)).Returns(ExportFactoryProvider);
            ret.GetService(typeof(IConnection)).Returns(Connection);
            ret.GetService(typeof(IConnectionManager)).Returns(ConnectionManager);
            ret.GetService(typeof(IAvatarProvider)).Returns(avatarProvider);
            ret.GetService(typeof(ITwoFactorChallengeHandler)).Returns(TwoFactorChallengeHandler);
            return ret;
        }

        public static IGitRepositoriesExt GetGitExt(this IServiceProvider provider)
        {
            return provider.GetService(typeof(IGitRepositoriesExt)) as IGitRepositoriesExt;
        }

        public static IVSServices GetVSServices(this IServiceProvider provider)
        {
            return provider.GetService(typeof(IVSServices)) as IVSServices;
        }

        public static IGitService GetGitService(this IServiceProvider provider)
        {
            return provider.GetService(typeof(IGitService)) as IGitService;
        }

        public static IOperatingSystem GetOperatingSystem(this IServiceProvider provider)
        {
            return provider.GetService(typeof(IOperatingSystem)) as IOperatingSystem;
        }

        public static IRepositoryCloneService GetRepositoryCloneService(this IServiceProvider provider)
        {
            return provider.GetService(typeof(IRepositoryCloneService)) as IRepositoryCloneService;
        }

        public static IRepositoryCreationService GetRepositoryCreationService(this IServiceProvider provider)
        {
            return provider.GetService(typeof(IRepositoryCreationService)) as IRepositoryCreationService;
        }

        public static IRepositoryHosts GetRepositoryHosts(this IServiceProvider provider)
        {
            return provider.GetService(typeof(IRepositoryHosts)) as IRepositoryHosts;
        }

        public static IExportFactoryProvider GetExportFactoryProvider(this IServiceProvider provider)
        {
            return provider.GetService(typeof(IExportFactoryProvider)) as IExportFactoryProvider;
        }

        public static IConnection GetConnection(this IServiceProvider provider)
        {
            return provider.GetService(typeof(IConnection)) as IConnection;
        }

        public static IConnectionManager GetConnectionManager(this IServiceProvider provider)
        {
            return provider.GetService(typeof(IConnectionManager)) as IConnectionManager;
        }

        public static IAvatarProvider GetAvatarProvider(this IServiceProvider provider)
        {
            return provider.GetService(typeof(IAvatarProvider)) as IAvatarProvider;
        }

        public static ITwoFactorChallengeHandler GetTwoFactorChallengeHandler(this IServiceProvider provider)
        {
            return provider.GetService(typeof(ITwoFactorChallengeHandler)) as ITwoFactorChallengeHandler;
        }
    }
}


text:
package org.ihtsdo.buildcloud.rest.controller.helper;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class ControllerHelper {

    public static ResponseEntity<Void> getCreatedResponse(String id) {
        return getCreatedResponse(id, "");
    }

    public static ResponseEntity<Void> getCreatedResponse(String id, String removePathPart) {
        HttpHeaders httpHeaders = getCreatedLocationHeaders(id, removePathPart, null);
        return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED);
    }

    public static ResponseEntity<Void> getCreatedResponse(String id, MultiValueMap<String, String> queryParams) {
        HttpHeaders httpHeaders = getCreatedLocationHeaders(id, null, queryParams);
        return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED);
    }

    public static HttpHeaders getCreatedLocationHeaders(String id) {
        return getCreatedLocationHeaders(id, null, null);
    }

    public static HttpHeaders getCreatedLocationHeaders(String id, String removePathPart, MultiValueMap<String, String> params) {
        RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
        Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
        HttpServletRequest request = ((ServletRequestAttributes) attrs).getRequest();

        String requestUrl = request.getRequestURL().toString();
        // Decode branch path
        requestUrl = requestUrl.replace("%7C", "/");
        if (!StringUtils.isEmpty(removePathPart)) {
            requestUrl = requestUrl.replace(removePathPart, "");
        }

        HttpHeaders httpHeaders = new HttpHeaders();
        if (params != null) {
            httpHeaders.setLocation(ServletUriComponentsBuilder.fromHttpUrl(requestUrl).path("/{id}").queryParams(params).buildAndExpand(id).toUri());
        } else {
            httpHeaders.setLocation(ServletUriComponentsBuilder.fromHttpUrl(requestUrl).path("/{id}").buildAndExpand(id).toUri());
        }
        return httpHeaders;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ivy-module version="1.4">
    <info organisation="myorg" module="helloworld" revision="1.1" status="release" publication="20080811152510" />
    <configurations>
        <conf name="default" />
        <conf name="ide" extends="default" description="+ Javadocs and sources" />
    </configurations>
    <publications>
        <artifact name="helloworld" type="jar" ext="jar" conf="default" />
        <artifact name="helloworld-doc" type="javadoc" ext="zip" conf="ide" />
    </publications>
</ivy-module>


text:
"""
Created on Tue Aug  9 00:26:10 2016

@author: ajaver
"""
import os
import argparse

from tierpsy.processing.CheckFilesForProcessing import CheckFilesForProcessing
from tierpsy.processing.ProcessLocal import ProcessLocalParser
from tierpsy.processing.helper import find_valid_files, \
remove_border_checkpoints, get_results_dir, get_masks_dir
from tierpsy.processing.run_multi_cmd import RunMultiCMD

from tierpsy.helper.params import TrackerParams
from tierpsy.helper.params.docs_process_param import dflt_args_list, process_valid_options

class ProcessMultipleFilesParser(argparse.ArgumentParser):
    def __init__(self):
        description = "Process worm video in the local drive using several parallel processes"
        super().__init__(description=description)

        for name, dflt_val, help in dflt_args_list:

            args_d = {'help' : help}
            if isinstance(dflt_val, bool):
                args_d['action'] = 'store_true'
            else:
                args_d['default'] = dflt_val
                if isinstance(dflt_val, (int, float)):
                    args_d['type'] = type(dflt_val)

            if isinstance(dflt_val, (list, tuple)):
                args_d['nargs'] = '+'

            if name in process_valid_options:
                args_d['choices'] = process_valid_options[name]

            self.add_argument('--' + name, **args_d)

def processMultipleFilesFun(
        video_dir_root,
        mask_dir_root,
        results_dir_root,
        tmp_dir_root,
        json_file,
        videos_list,
        pattern_include,
        pattern_exclude,
        max_num_process,
        refresh_time,
        only_summary,
        force_start_point='',
        end_point='',
        is_copy_video=False,
        analysis_checkpoints=[],
        unmet_requirements = False,
        copy_unfinished = False,
        is_debug = True
        ):

    assert video_dir_root or mask_dir_root

    # get a name for the directories if they were not given
    if not video_dir_root:
        video_dir_root = mask_dir_root

    if not mask_dir_root:
        mask_dir_root = get_masks_dir(video_dir_root)

    if not results_dir_root:
        results_dir_root = get_results_dir(mask_dir_root)

    param = TrackerParams(json_file)

    json_file = param.json_file

    if not analysis_checkpoints:
      analysis_checkpoints = param.p_dict['analysis_checkpoints'].copy()

    if True:#os.name == 'nt' or 'm4v' in pattern_include:
        # This is giving problems in windows, specially while frozen. It shouldn't affect too much since it only speed up the check up of the files progress
        is_parallel_check = False
    else:
        is_parallel_check = True

    is_parallel_check = False

    remove_border_checkpoints(analysis_checkpoints, force_start_point, 0)
    remove_border_checkpoints(analysis_checkpoints, end_point, -1)

    walk_args = {'root_dir': video_dir_root,
                 'pattern_include' : pattern_include,
                  'pattern_exclude' : pattern_exclude}

    check_args = {'video_dir_root': video_dir_root,
                  'mask_dir_root': mask_dir_root,
                  'results_dir_root' : results_dir_root,
                  'tmp_dir_root' : tmp_dir_root,
                  'json_file' : json_file,
                  'analysis_checkpoints': analysis_checkpoints,
                  'is_copy_video': is_copy_video,
                  'copy_unfinished': copy_unfinished,
                  'is_parallel_check': is_parallel_check}

    #get the list of valid videos
    if not videos_list:
        valid_files = find_valid_files(**walk_args)
    else:
        with open(videos_list, 'r') as fid:
            valid_files = fid.read().split('\n')
            #valid_files = [os.path.realpath(x) for x in valid_files]

    files_checker = CheckFilesForProcessing(**check_args)

    cmd_list = files_checker.filterFiles(valid_files, print_cmd=is_debug)

    if unmet_requirements:
         files_checker._printUnmetReq()
    elif not only_summary:
        RunMultiCMD(
            cmd_list,
            local_obj = ProcessLocalParser,
            max_num_process = max_num_process,
            refresh_time = refresh_time,
            is_debug = is_debug)

def tierpsy_process():
    args = ProcessMultipleFilesParser().parse_args()
    processMultipleFilesFun(**vars(args))


text:
package com.mobilepetroleum;

public class Exceptions {

    private Exceptions() {}

    public static RuntimeException runtime(Throwable cause, String message, Object... args) {
        return new RuntimeException(String.format(message, args), cause);
    }

    public static RuntimeException runtime(String message, Object... args) {
        return new RuntimeException(String.format(message, args));
    }

}


text:
public class Solution {
    public boolean isSubtree(TreeNode s, TreeNode t) {
        if (s == null) return false;
        if (s.val == t.val && isEqual(s, t)) return true;
        return isSubtree(s.left, t) || isSubtree(s.right, t);
    }

    private boolean isEqual(TreeNode a, TreeNode b) {
        if (a == null && b == null) return true;
        if ((a == null && b != null) || (a != null && b == null)) return false;
        if (a.val != b.val) return false;
        return isEqual(a.left, b.left) && isEqual(a.right, b.right);
    }
}


text:
using System;

namespace DotNet.Basics.Tasks.Repeating
{
    public class RepeatTimeoutPredicate
    {
        private DateTime _startTime;

        public RepeatTimeoutPredicate(TimeSpan timeout)
        {
            Timeout = timeout;
            _startTime = DateTime.MaxValue;
            Init();
        }

        public TimeSpan Timeout { get; }

        public void Init()
        {
            _startTime = DateTime.UtcNow;
        }

        public bool ShouldBreak()
        {
            return DateTime.UtcNow - _startTime > Timeout;
        }

        public void LoopCallback()
        { }
    }
}


text:
module Main where

import System.Environment (getArgs)
import System.Executable.Hash.Internal (injectExecutableHash)

main :: IO ()
main = do
    args <- getArgs
    case args of
        [exe] -> injectExecutableHash exe
        _ -> error "Usage: inject-executable-hash <executable>"


text:
namespace DotNetty.Common.Concurrency
{
    public interface ICallable<out T>
    {
        T Call();
    }
}