text:
const BROWSER_TYPE = require('core/browser_type');
const LOAD = require('core/load');
const UtilMethods = require('util/util_methods');

/**
The DOM Element abstraction engine
**/
class _ELEM extends UtilMethods {
  constructor(options) {
    super();
    if (!options) {
      options = {};
    }
    // Main control for refresh speed
    this.ELEMTickerInterval = options.ELEMTickerInterval || 33;
    this._gradientIdCount = 0;
  }

  // Sets up object members
  reset() {

    this._flushTime = 0;
    this._flushCounter = 0;
    this._idleDelay = 500;

    this._timer = null;
    this._minDelay = this.ELEMTickerInterval;
    this._flushing = false;
    this._needFlush = false;
    this._slowness = 1;

    this._elements = {};
    this._nextElemId = 0;
    this._freeElemIds = [];

    this._styleCache = {};
    this._styleTodo = {};
    this._elemTodo = [];
    this._elemTodoH = {};
  }

  // Adds an element reference
  // Returns the element id
  _add(_elem) {
    let _id;
    if (this._freeElemIds.length !== 0) {
      _id = this._freeElemIds.shift();
    }
    else {
      _id = this._nextElemId;
      this._nextElemId += 1;
    }
    this._elements[_id] = _elem;
    return _id;
  }

  // Initializes cache object helpers
  _initCache(_id) {
    this._styleTodo[_id] = [];
    this._styleCache[_id] = {};
    this._elemTodoH[_id] = false;
  }

  // Adds an existing document element by its id attribute.
  // Optionally give _parentId to give a scope for the search,
  // which is much faster for finding from a small subset of
  // the DOM rather than the entire document).
  // Returns null, if no such element was found
  bindId(_idAttr, _parentId) {
    const _elem = this.isNumber(_parentId) ?
      this._elements[_parentId].getElementById(_idAttr) : document.getElementById(_idAttr);
    if (this.isNullOrUndefined(_elem)) {
      return null;
    }
    else {
      const _id = this._add(_elem);
      this._initCache(_id);
      return _id;
    }
  }

  // Binds the document element
  bind(_elem) {
    const _id = this._add(_elem);
    this._initCache(_id);
    return _id;
  }

  // Returns an element by its id
  get(_id) {
    return this._elements[_id];
  }

  // Returns an element by its id attribute
  getByAttrId(_attrId) {
    return this.get(this.bindId(_attrId));
  }

  // Sets the innerHTML contents of the element
  setHTML(_id, _html) {
    const _elem = this._elements[_id];
    if (_elem && _elem.innerHTML !== _html) {
      _elem.innerHTML = _html;
    }
  }

  // Returns the innerHTML of the element
  getHTML(_id) {
    return this._elements[_id].innerHTML;
  }

  // Deletes an element and its associated metadata
  del(_id) {
    const _elem = this._elements[_id];
    const i = this._elemTodo.indexOf(_id);
    if (i !== -1) {
      this._elemTodo.splice(i, 1);
    }
    delete this._styleCache[_id];
    delete this._elemTodoH[_id];
    delete this._elements[_id];
    this._freeElemIds.push(_id);
    const _parent = _elem.parentNode;
    if (_parent) {
      _parent.removeChild(_elem);
    }
    else {
      console.warn('ELEM.del(', _id,
        '): Invalid parent: ', _parent,
        'for elem:', _elem);
    }
  }

  // Places the source element inside the target element
  append(_srcId, _tgtId) {
    this._elements[_tgtId].appendChild(this._elements[_srcId]);
  }

  moveToParent(_id, _parentId) {
    const _elem = this._elements[_id];
    _elem.parentNode.removeChild(_elem);
    this._elements[_parentId].appendChild(_elem);
  }

  // Replaces all styles of an element with a block of css text
  setCSS(_id, _css) {
    this._elements[_id].style.cssText = _css;
  }

  // Returns the current css text of an element
  getCSS(_id) {
    return this._elements[_id].style.cssText;
  }

  // Returns the visible size of an element as a [ width, height ] tuple
  getVisibleSize(_id) {
    let _elem = this._elements[_id];
    let [w, h] = [_elem.offsetWidth, _elem.offsetHeight];
    let _parent = _elem.parentNode;
    while (_parent && _parent.nodeName.toLowerCase() !== 'body') {
      if (this._getComputedStyle(_parent, 'overflow') === 'visible') {
        if (w > _parent.clientWidth) {
          w = _parent.clientWidth - _elem.offsetLeft;
        }
        if (h > _parent.clientHeight) {
          h = _parent.clientHeight - _elem.offsetTop;
        }
      }
      _elem = _elem.parentNode;
      if (!_parent.parentNode) {
        break;
      }
      _parent = _parent.parentNode;
    }
    return [w, h];
  }

  // Returns the full offset size of the element as a [ width, height ] tuple
  getSize(_id) {
    const _elem = this._elements[_id];
    let [w, h] = [0, 0];
    if (this._isSVGElem(_elem)) {
      const _rect = _elem.getBoundingClientRect();
      [w, h] = [_rect.width, _rect.height];
    }
    else if (_elem) {
      [w, h] = [_elem.offsetWidth, _elem.offsetHeight];
    }
    else {
      console.warn('ELEM.getSize(', _id, '): Element not found');
    }
    return [w, h];
  }

  // Returns the position of the element as a [ x, y ] tuple
  getPosition(_id) {
    const _elem = this._elements[_id];
    let [x, y] = [0, 0];
    if (this._isSVGElem(_elem)) {
      const _rect = _elem.getBoundingClientRect();
      [x, y] = [_rect.left, _rect.top];
    }
    else if (_elem) {
      [x, y] = [_elem.offsetLeft, _elem.offsetTop];
    }
    else {
      console.warn('ELEM.getPosition(', _id, '): Element not found');
    }
    return [x, y];
  }

  // Returns the scroll position of the element as a [ x, y ] tuple
  getScrollPosition(_id) {
    const _elem = this._elements[_id];
    let [x, y] = [0, 0];
    if (_elem) {
      [x, y] = [_elem.scrollLeft, _elem.scrollTop];
    }
    else {
      console.warn('ELEM.getScrollPosition(', _id, '): Element not found');
    }
    return [x, y];
  }

  // Returns the scroll size of the element as a [ width, height ] tuple
  getScrollSize(_id) {
    const _elem = this._elements[_id];
    let [w, h] = [0, 0];
    if (_elem) {
      [w, h] = [_elem.scrollWidth, _elem.scrollHeight];
    }
    else {
      console.warn('ELEM.getScrollSize(', _id, '): Element not found');
    }
    return [w, h];
  }

  _getVisibleLeftOrTop(_id, _noOwnScroll, _offsetProp, _scrollProp) {
    let _elem = this._elements[_id];
    let a = 0;
    if (_elem) {
      while (this.isntNullOrUndefined(_elem) && _elem !== document.body) {
        const _pos = this._getComputedStyle(_elem, 'position');
        if (_pos === 'fixed') {
          a += _elem[_offsetProp] + document.body[_scrollProp];
          break;
        }
        if (_pos === 'absolute' || _pos === 'relative' || _elem === this._elements[_id]) {
          a += _elem[_offsetProp];
        }
        if (!_noOwnScroll || _elem !== this._elements[_id]) {
          a -= _elem[_scrollProp];
        }
        _elem = _elem.parentNode;
      }
    }
    else {
      console.warn('ELEM._getVisibleLeftOrTopPosition(', _id, '): Element not found');
    }
    return a;
  }

  // Calculates the visible left position of an element
  // If _noOwnScroll is true, method not include scrollLeft of element itself.
  _getVisibleLeftPosition(_id, _noOwnScroll) {
    return this._getVisibleLeftOrTop(_id, _noOwnScroll, 'offsetLeft', 'scrollLeft');
  }

  // Calculates the visible top position of an element
  // If _noOwnScroll is true, method not include scrollTop of element itself.
  _getVisibleTopPosition(_id, _noOwnScroll) {
    return this._getVisibleLeftOrTop(_id, _noOwnScroll, 'offsetTop', 'scrollTop');
  }

  // Returns the visible position of the element as a [ left, top ] tuple
  // If _noOwnScroll is true, method not include scrollLeft and scrollTop of element itself.
  getVisiblePosition(_id, _noOwnScroll) {
    return [
      this._getVisibleLeftPosition(_id, _noOwnScroll),
      this._getVisibleTopPosition(_id, _noOwnScroll)
    ];
  }

  // Returns the opacity on the element as a number equaling or between 0 and 1
  getOpacity(_id) {
    const _elem = this._elements[_id];
    const _opacity = this._getComputedStyle(_elem, 'opacity');
    return parseFloat(_opacity);
  }

  // Sets the opcity of the element as a number equaling or between 0 and 1
  setOpacity(_id, _opacity) {
    this._elements[_id].style.setProperty('opacity', _opacity.toString(), '');
  }

  // Wrapper for getStyle, returns an integer number instead of a string
  getIntStyle(_id, _key) {
    return parseInt(this.getStyle(_id, _key), 10);
  }

  // Sets element position ( id, [ x, y ] )
  setPosition(_id, x, y) {
    if (!y && y !== 0 && this.isArray(x)) {
      [x, y] = x; // assume tuple
    }
    this.setStyle(_id, 'left', `${x}px`);
    this.setStyle(_id, 'top', `${y}px`);
  }

  // Shortcut for filling parent dimensions with optional offset(s)
  stretchToParentBounds(_id, l, t, r, b) {
    if (this.isNullOrUndefined(l)) {
      [l, t, r, b] = [0, 0, 0, 0];
    }
    else if (this.isArray(l)) {
      [l, t, r, b] = l;
    }
    else if (this.isNullOrUndefined(t)) {
      [l, t, r, b] = [l, l, l, l];
    }
    this.setStyle(_id, 'position', 'absolute');
    this.setStyle(_id, 'display', 'block');
    this.setStyle(_id, 'left', `${l}px`);
    this.setStyle(_id, 'top', `${t}px`);
    this.setStyle(_id, 'width', 'auto');
    this.setStyle(_id, 'height', 'auto');
    this.setStyle(_id, 'right', `${r}px`);
    this.setStyle(_id, 'bottom', `${b}px`);
  }

  // Sets box coordinates [ x, y, width, height ]
  setBoxCoords(_id, _coords) {
    const [x, y, w, h] = _coords;
    this.setStyle(_id, 'left', `${x}px`);
    this.setStyle(_id, 'top', `${y}px`);
    this.setStyle(_id, 'width', `${w}px`);
    this.setStyle(_id, 'height', `${h}px`);
  }

  // Gets box coordinates [ x, y, width, height ]
  getBoxCoords(_id) {
    const [x, y] = this.getPosition(_id);
    const [w, h] = this.getSize(_id);
    return [x, y, w, h];
  }

  // Returns the visible box coordinates of the element as a [ left, top, width, height ]
  getVisibleBoxCoords(_id, _noOwnScroll) {
    const [x, y] = this.getVisiblePosition(_id, _noOwnScroll);
    const [w, h] = this.getSize(_id);
    return [x, y, w, h];
  }

  // Computes extra size (padding and border size) of element
  _getExtraSize(_id, _side) {
    return (
      this.getIntStyle(_id, `padding-${_side}`) +
      this.getIntStyle(_id, `border-${_side}-width`)
    );
  }

  // Returns left-side padding and border size
  _getExtraLeftWidth(_id) {
    return this._getExtraSize(_id, 'left');
  }

  // Returns right-side padding and border size
  _getExtraRightWidth(_id) {
    return this._getExtraSize(_id, 'right');
  }

  // Returns top-side padding and border size
  _getExtraTopWidth(_id) {
    return this._getExtraSize(_id, 'top');
  }

  // Returns right-side padding and border size
  _getExtraBottomWidth(_id) {
    return this._getExtraSize(_id, 'bottom');
  }

  // Returns extra width of element (caused by padding and borders)
  getExtraWidth(_id) {
    return (
      this._getExtraSize(_id, 'left') +
      this._getExtraSize(_id, 'right')
    );
  }

  // Returns extra height of element (caused by padding and borders)
  getExtraHeight(_id) {
    return (
      this._getExtraSize(_id, 'top') +
      this._getExtraSize(_id, 'bottom')
    );
  }

  isFullScreen() {
    return !!(
      document.fullScreenElement ||
      document.mozFullScreen ||
      document.webkitIsFullScreen
    );
  }

  // Sets delay between refreshes based on the target frame rate
  setFPS(_fps) {
    this._minDelay = Math.round(1000 / _fps);
    if (this._minDelay < this.ELEMTickerInterval) {
      this._minDelay = this.ELEMTickerInterval;
    }
  }

  // Sets slowness (weighted factor for slow browsers; essentially frame-skip)
  // The d-efault 1.0 does not change the FPS, larger numbers gives more time for logic by skipping frames
  setSlowness(_slow) {
    this._slowness = _slow;
  }

  // Sets the idle delay in ms
  // This is the maximum time between setting a style or
  // property into the buffer and flushing the buffer to the DOM
  setIdleDelay(_idleDelay) {
    this._idleDelay = _idleDelay;
  }

  // Resets the flushLoop
  _resetFlushLoop(_delay, _timeDelay) {
    const _this = this;
    if (!_timeDelay) {
      _timeDelay = _delay;
    }
    this._timer = setTimeout(() => {
      _this.flushLoop(_delay);
    }, _timeDelay);
  }

  // Computes a default delay time based on various params
  _defaultDelay() {
    let _delay = Math.round(
      this._slowness * (this._flushTime / this._flushCounter)
    );
    if (_delay < this._minDelay || !_delay) {
      _delay = this._minDelay;
    }
    return _delay;
  }

  // Flushes buffered styles and properties into the DOM
  flushLoop(_delay) {
    if (!_delay && _delay !== 0) {
      _delay = this._defaultDelay();
    }
    clearTimeout(this._timer);
    if (this._flushing) {
      _delay *= 2;
      this._resetFlushLoop(_delay);
    }
    else if (!this._needFlush) {
      // go into 'sleep mode'
      this._resetFlushLoop(_delay, this._idleDelay);
    }
    else {
      _delay = this._defaultDelay();
      this._flushing = true;
      this._resetFlushLoop(_delay);
    }
    this._performFlush();
    this._flushing = false;
  }

  // Alias for flushLoop
  flush() {
    this.flushLoop();
  }

  flushElem(_elemIds) {
    if (this.isNumber(_elemIds)) {
      _elemIds = [_elemIds];
    }
    const _this = this;
    _elemIds.forEach(_id => {
      if (_this._elemTodoH[_id]) {
        _this._elemTodoH[_id] = false;
        _this._flushStyleCache(_id);
      }
    });
  }

  // Performs the flush of flushLoop
  _performFlush() {
    const _flushStartTime = this.msNow();
    this._flushTime -= _flushStartTime;
    const _loopMaxL = this._elemTodo.length;
    if (_loopMaxL > 0) {
      const _currTodo = this._elemTodo.splice(0, _loopMaxL);
      for (let i = 0; i < _loopMaxL; i++) {
        this._flushLoopFlushed++;
        const _id = _currTodo.shift();
        if (this.isntNumber(_id)) {
          console.warn('ELEM._performFlush; no id:', _id);
        }
        else {
          this._elemTodoH[_id] = false;
          this._flushStyleCache(_id);
        }
      }
    }
    this._flushCounter++;
    this._flushTime += this.msNow();
    this._needFlush = this._elemTodo.length !== 0;
  }

  // Return true if element is SVGElement
  _isSVGElem(_elem) {
    try {
      return _elem instanceof SVGElement;
    }
    catch (e) {
      // not all browsers have SVGElement:
      return false;
    }
  }

  // Gets an element attribute directly from the element
  _getAttrDirect(_id, _key) {
    const _elem = this._elements[_id];
    let _attr = _elem.getAttribute(_key);
    if (_attr === null) {
      _attr = _elem[_key];
    }
    return _attr;
  }

  _setAttrDirect(_id, _key, _value) {
    const _elem = this._elements[_id];
    _elem[_key] = _value;
    _elem.setAttribute(_key, _value);
  }

  // Gets a named element attribute from the cache or selectively direct
  getAttr(_id, _key, _noCache) {
    if (this.isntNullOrUndefined(this._elements[_id])) {
      return this._getAttrDirect(_id, _key);
    }
    else {
      return null;
    }
  }

  // Sets a named element attribute into the cache and buffer or selectively direct
  setAttr(_id, _key, _value, _noCache) {
    if (this.isntNullOrUndefined(this._elements[_id])) {
      this._setAttrDirect(_id, _key, _value);
    }
  }

  _hasAttrDirect(_id, _key) {
    return this._elements[_id].hasAttribute(_key);
  }

  _delAttrDirect(_id, _key) {
    this._elements[_id].removeAttribute(_key);
  }

  // Deletes a named element attribute
  delAttr(_id, _key, _noCache) {
    if (this.isntNullOrUndefined(this._elements[_id])) {
      if (this._hasAttrDirect(_id, _key)) {
        this._delAttrDirect(_id, _key);
      }
    }
  }

  // Get classnames of element
  _getClassNames(_id) {
    const _elem = this._elements[_id];
    if (this._isSVGElem(_elem)) {
      return _elem.className.baseVal;
    }
    else {
      return _elem.className;
    }
  }

  // Set classnames for element
  _setClassNames(_id, _className) {
    const _elem = this._elements[_id];
    if (this._isSVGElem(_elem)) {
      _elem.className.baseVal = _className;
    }
    else {
      _elem.className = _className;
    }
  }

  // Checks if the element has a named CSS className
  hasClassName(_id, _className) {
    if (this.isntNullOrUndefined(this._elements[_id])) {
      const _classNames = this._getClassNames(_id).split(' ');
      return _classNames.includes(_className);
    }
    return null;
  }

  // Adds a named CSS className to the element
  addClassName(_id, _className) {
    if (this.isntNullOrUndefined(this._elements[_id])) {
      if (!this.hasClassName(_id, _className)) {
        const _elem = this._elements[_id];
        if (this._getClassNames(_id).trim() === '') {
          this._setClassNames(_id, _className);
        }
        else {
          const _classNames = this._getClassNames(_id).trim().split(' ');
          _classNames.push(_className);
          this._setClassNames(_id, _classNames.join(' '));
        }
      }
    }
  }

  // Removes a named CSS className of the element
  delClassName(_id, _className) {
    if (this.isntNullOrUndefined(this._elements[_id])) {
      if (this.hasClassName(_id, _className)) {
        const _elem = this._elements[_id];
        const _classNames = this._getClassNames(_id).split(' ');
        _classNames.splice(_classNames.indexOf(_className), 1);
        this._setClassNames(_id, _classNames.join(' '));
      }
    }
  }

  removeClassName(_id, _className) {
    return this.delClassName(_id, _className);
  }

  // Checks if buffers need to be flushed
  _checkNeedFlush() {
    if (!this._needFlush) {
      this._needFlush = true;
      if (!this._flushing) {
        clearTimeout(this._timer);
        this._resetFlushLoop(this._minDelay);
      }
    }
  }

  // Low-level style property setter
  _setElementStyle(_elem, _key, _value) {
    _elem.style.setProperty(_key, _value, '');
  }

  // Camelizes string (mostly used for IE attribute name conversions)
  _camelize(_str) {
    return _str.replace(/((-)([a-z])(\w))/g, ($0, $1, $2, $3, $4) => {
      return $3.toUpperCase() + $4;
    });
  }

  // Decamelizes string (used for js property to css property conversion)
  _deCamelize(_str) {
    return _str.replace(/(([A-Z])(\w))/g, ($0, $1, $2, $3) => {
      return '-' + $2.toLowerCase() + $3;
    });
  }

  // Sets and buffers the named style attribute value or selectively direct
  setStyle(_id, _key, _value, _noCache) {
    if (this.isntNullOrUndefined(this._elements[_id])) {
      if (!_id && _id !== 0) {
        console.error(
          'ERROR; no id in ELEM.setStyle',
          _id, _key, _value, _noCache
        );
      }
      let _cached = this._styleCache[_id];
      const _elem = this._elements[_id];
      if (!_cached && _cached !== 0 && _cached !== '') {
        this._initCache(_id);
        _cached = this._styleCache[_id];
      }
      _key = this._deCamelize(_key);
      if (_value !== _cached[_key]) {
        _cached[_key] = _value;
        if (_noCache) {
          if (_key === 'opacity') {
            this.setOpacity(_id, _value);
          }
          else {
            this._setElementStyle(_elem, _key, _value);
          }
        }
        else {
          const _styleTodo = this._styleTodo[_id];
          if (!_styleTodo.includes(_key)) {
            _styleTodo.push(_key);
          }
          if (!this._elemTodoH[_id]) {
            this._elemTodo.push(_id);
            this._elemTodoH[_id] = true;
            this._checkNeedFlush();
          }
        }
      }
    }
  }

  // Sets multiple styles at once
  setStyles(_id, _styles, _noCache) {
    const _this = this;
    if (this.isObject(_styles)) {
      _styles = Object.entries(_styles);
    }
    if (this.isArray(_styles)) {
      _styles.forEach(([_key, _value]) => {
        _this.setStyle(_id, _key, _value, _noCache);
      });
    }
    else {
      console.error('ERROR calling ELEM.setStyles; _styles is not an object nor Array:', typeof _styles);
    }
  }

  // Creates a new element inside another element
  make(_targetId, _tagName, _options) {
    if (!_targetId) {
      _targetId = 0;
    }
    if (!_tagName) {
      _tagName = 'DIV';
    }
    else {
      _tagName = _tagName.toUpperCase();
    }
    const _elem = document.createElement(_tagName);
    const _id = this._add(_elem);
    this._initCache(_id);
    if (_options) {
      let _attrs;
      if (this.isntNullOrUndefined(_options.attrs)) {
        _attrs = _options.attrs;
      }
      else if (this.isntNullOrUndefined(_options.attr)) {
        _attrs = _options.attr;
      }
      if (this.isObjectOrArray(_attrs)) {
        if (this.isObject(_attrs)) {
          _attrs = Object.entries(_attrs);
        }
        if (this.isArray(_attrs)) {
          _attrs.forEach(([_key, _value]) => {
            this.setAttr(_id, _key, _value, true);
          });
        }
      }
      const _classes = _options.classes;
      if (this.isArray(_classes)) {
        _classes.forEach(_className => {
          this.addClassName(_id, _className);
        });
      }
      if (_options.styles) {
        this.setStyles(_id, _options.styles);
      }
      if (_options.html) {
        this.setHTML(_id, _options.html);
      }
    }
    if (this._elements[_targetId] !== _elem.parentNode) {
      this._elements[_targetId].appendChild(_elem);
    }
    return _id;
  }

  // Returns window scroll position as [ left, top ]
  windowScroll() {
    return [
      (window.pageXOffset || document.documentElement.scrollLeft),
      (window.pageYOffset || document.documentElement.scrollTop)
    ];
  }

  // Returns inner size of the browser window as [ width, height ]
  windowSize() {
    let [w, h] = [window.innerWidth, window.innerHeight];
    if ((!w && w !== 0) || (!h && h !== 0)) {
      const _docElem = document.documentElement;
      w = _docElem.clientWidth;
      h = _docElem.clientHeight;
    }
    return [w, h];
  }

  // Returns computed style of element
  _getComputedStyle(_elem, _key) {
    return document
      .defaultView
      .getComputedStyle(_elem, null)
      .getPropertyValue(_key);
  }

  // Gets the named element style attribute value.
  getStyle(_id, _key, _noCache) {
    let _value = null;
    if (this._styleCache[_id]) {
      const _cached = this._styleCache[_id];
      _key = this._deCamelize(_key);
      if (this.isNullOrUndefined(_cached[_key]) || _noCache) {
        if (_key === 'opacity') {
          _value = this.getOpacity(_id);
        }
        else {
          _value = this._getComputedStyle(this._elements[_id], _key);
        }
        _cached[_key] = _value;
      }
      else {
        _value = _cached[_key];
      }
    }
    return _value;
  }

  // Style buffer flushing method
  _flushStyleCache(_id) {
    const _elem = this._elements[_id];
    if (_elem) {
      const _styleTodo = this._styleTodo[_id];
      const _cached = this._styleCache[_id];
      const _loopMaxP = _styleTodo.length;
      if (_loopMaxP !== 0) {
        const _currTodo = _styleTodo.splice(0, _loopMaxP);
        for (let i = 0; i < _loopMaxP; i++) {
          const _key = _currTodo.shift();
          if (_key === 'opacity') {
            this.setOpacity(_id, _cached[_key]);
          }
          else {
            this._setElementStyle(_elem, _key, _cached[_key]);
          }
        }
      }
    }
  }

  // Final phase of startup, when document is loaded
  _init() {
    if (this.isFunction(window.RSenceInit)) {
      window.RSenceInit();
    }
    if (!this._timer) {
      this.bind(document.body);
    }
    this._resetFlushLoop(this._minDelay);
  }

  /*
  Returns an array of key, value style string pair containing the gradient style supported by the current browser.

  The format of the colorSteps Object with the following items:
    Key      Description
    start    Default background color in a valid hexadecimal color format, also the start color
    end      Default gradient end color for dumber browsers
    type     Currently only 'linearTopBottom' is supported
    steps    An Array containing color, percent (number without suffix) pairs, like [ 10, '#fff']
  */
  _standardGradientSteps(_startColor, _stepsIn, _endColor) {
    const _steps = [`${_startColor} 0%`];
    if (_stepsIn.length !== 0) {
      _stepsIn.forEach(_step => {
        _steps.push(`${_step[1]} ${_step[0]}%`);
      });
    }
    _steps.push(`${_endColor} 100%`);
    return _steps;
  }

  _linearGradientStyle(_gradient) {
    // Firefox 3.6 and newer
    let _key;
    let _steps;
    let _value;
    if (BROWSER_TYPE.firefox) {
      _key = 'background';
      _steps = this._standardGradientSteps(_gradient.start, _gradient.steps, _gradient.end).join(', ');
      _value = `-moz-linear-gradient(top, ${_steps})`;
    }
    // Chrome and Safari
    else if (BROWSER_TYPE.safari || BROWSER_TYPE.chrome) {
      _key = 'background';
      // Chrome10+,Safari5.1+
      _steps = this._standardGradientSteps(_gradient.start, _gradient.steps, _gradient.end).join(',');
      _value = `-webkit-linear-gradient(top, ${_steps})`;
    }
    // Opera 11.10+
    else if (BROWSER_TYPE.opera) {
      _key = 'background';
      _steps = this._standardGradientSteps(_gradient.start, _gradient.steps, _gradient.end).join(',');
      _value = `-o-linear-gradient(top, ${_steps})`;
    }
    else {
      // Old browsers
      _key = 'background';
      _value = _gradient.start;
      // W3C standard:
      // _steps = this._standardGradientSteps(_gradient.start,_gradient.steps,_gradient.end).join(',');
      // _value = `linear-gradient(to bottom, ${_steps})`;
    }
    return [_key, _value];
  }

  _linearGradientCSS(_gradient) {
    this._linearGradientStyle(_gradient).join(': ') + ';';
  }

  // Simply checks whether navigator language includes the string _lang
  hasLang(_lang) {
    return BROWSER_TYPE.lang.includes(_lang);
  }

  get ELEM() {
    console.warn(
      "ELEM#ELEM is deprecated, use `const ELEM = require('core/elem')`; instead of `const {ELEM} = require('core/elem');`");
    return this;
  }

  get LOAD() {
    console.warn(
      "ELEM#LOAD is deprecated, use `const LOAD = require('core/load');` instead of `const {LOAD} = require('core/elem');`");
    return LOAD;
  }

  get BROWSER_TYPE() {
    console.warn(
      "ELEM#BROWSER_TYPE is deprecated, use `const BROWSER_TYPE = require('core/browser_type');` instead of `const {BROWSER_TYPE} = require('core/elem');`");
    return BROWSER_TYPE;
  }

}

const ELEM = new _ELEM();
LOAD(() => {
  ELEM.reset();
  ELEM._init();
});

module.exports = ELEM;


text:
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;

namespace NetCoreForce.Models
{
	///
	/// Secure Agent Plug-in
	///<para>SObject Name: SecureAgentPlugin</para>
	///<para>Custom Object: False</para>
	///
	public class SfSecureAgentPlugin : SObject
	{
		[JsonIgnore]
		public static string SObjectTypeName
		{
			get { return "SecureAgentPlugin"; }
		}

		///
		/// Secure Agent Plug-in ID
		/// <para>Name: Id</para>
		/// <para>SF Type: id</para>
		/// <para>Nillable: False</para>
		///
		[JsonProperty(PropertyName = "id")]
		[Updateable(false), Createable(false)]
		public string Id { get; set; }

		///
		/// Deleted
		/// <para>Name: IsDeleted</para>
		/// <para>SF Type: boolean</para>
		/// <para>Nillable: False</para>
		///
		[JsonProperty(PropertyName = "isDeleted")]
		[Updateable(false), Createable(false)]
		public bool? IsDeleted { get; set; }

		///
		/// Created Date
		/// <para>Name: CreatedDate</para>
		/// <para>SF Type: datetime</para>
		/// <para>Nillable: False</para>
		///
		[JsonProperty(PropertyName = "createdDate")]
		[Updateable(false), Createable(false)]
		public DateTimeOffset? CreatedDate { get; set; }

		///
		/// Created By ID
		/// <para>Name: CreatedById</para>
		/// <para>SF Type: reference</para>
		/// <para>Nillable: False</para>
		///
		[JsonProperty(PropertyName = "createdById")]
		[Updateable(false), Createable(false)]
		public string CreatedById { get; set; }

		///
		/// ReferenceTo: User
		/// <para>RelationshipName: CreatedBy</para>
		///
		[JsonProperty(PropertyName = "createdBy")]
		[Updateable(false), Createable(false)]
		public SfUser CreatedBy { get; set; }

		///
		/// Last Modified Date
		/// <para>Name: LastModifiedDate</para>
		/// <para>SF Type: datetime</para>
		/// <para>Nillable: False</para>
		///
		[JsonProperty(PropertyName = "lastModifiedDate")]
		[Updateable(false), Createable(false)]
		public DateTimeOffset? LastModifiedDate { get; set; }

		///
		/// Last Modified By ID
		/// <para>Name: LastModifiedById</para>
		/// <para>SF Type: reference</para>
		/// <para>Nillable: False</para>
		///
		[JsonProperty(PropertyName = "lastModifiedById")]
		[Updateable(false), Createable(false)]
		public string LastModifiedById { get; set; }

		///
		/// ReferenceTo: User
		/// <para>RelationshipName: LastModifiedBy</para>
		///
		[JsonProperty(PropertyName = "lastModifiedBy")]
		[Updateable(false), Createable(false)]
		public SfUser LastModifiedBy { get; set; }

		///
		/// System Modstamp
		/// <para>Name: SystemModstamp</para>
		/// <para>SF Type: datetime</para>
		/// <para>Nillable: False</para>
		///
		[JsonProperty(PropertyName = "systemModstamp")]
		[Updateable(false), Createable(false)]
		public DateTimeOffset? SystemModstamp { get; set; }

		///
		/// Secure Agent ID
		/// <para>Name: SecureAgentId</para>
		/// <para>SF Type: reference</para>
		/// <para>Nillable: False</para>
		///
		[JsonProperty(PropertyName = "secureAgentId")]
		[Updateable(false), Createable(false)]
		public string SecureAgentId { get; set; }

		///
		/// ReferenceTo: SecureAgent
		/// <para>RelationshipName: SecureAgent</para>
		///
		[JsonProperty(PropertyName = "secureAgent")]
		[Updateable(false), Createable(false)]
		public SfSecureAgent SecureAgent { get; set; }

		///
		/// Name
		/// <para>Name: PluginName</para>
		/// <para>SF Type: string</para>
		/// <para>Nillable: True</para>
		///
		[JsonProperty(PropertyName = "pluginName")]
		[Updateable(false), Createable(false)]
		public string PluginName { get; set; }

		///
		/// Type
		/// <para>Name: PluginType</para>
		/// <para>SF Type: string</para>
		/// <para>Nillable: True</para>
		///
		[JsonProperty(PropertyName = "pluginType")]
		[Updateable(false), Createable(false)]
		public string PluginType { get; set; }

		///
		/// Requested Version
		/// <para>Name: RequestedVersion</para>
		/// <para>SF Type: string</para>
		/// <para>Nillable: True</para>
		///
		[JsonProperty(PropertyName = "requestedVersion")]
		[Updateable(false), Createable(false)]
		public string RequestedVersion { get; set; }

		///
		/// Update Window Start
		/// <para>Name: UpdateWindowStart</para>
		/// <para>SF Type: datetime</para>
		/// <para>Nillable: True</para>
		///
		[JsonProperty(PropertyName = "updateWindowStart")]
		[Updateable(false), Createable(false)]
		public DateTimeOffset? UpdateWindowStart { get; set; }

		///
		/// Update Window End
		/// <para>Name: UpdateWindowEnd</para>
		/// <para>SF Type: datetime</para>
		/// <para>Nillable: True</para>
		///
		[JsonProperty(PropertyName = "updateWindowEnd")]
		[Updateable(false), Createable(false)]
		public DateTimeOffset? UpdateWindowEnd { get; set; }

	}
}

redpajama_set_name: RedPajamaGithub


text:
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { Observable, of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

import { ProductResolved } from './product';
import { ProductService } from './product.service';

@Injectable({
  providedIn: 'root'
})
export class ProductResolver implements Resolve<ProductResolved> {

  constructor(private productService: ProductService) { }

  resolve(route: ActivatedRouteSnapshot,
          state: RouterStateSnapshot): Observable<ProductResolved> {
    const id = Number(route.paramMap.get('id'));
    if (isNaN(id)) {
      const message = `Product id was not a number: ${id}`;
      console.error(message);
      return of({ product: null, error: message });
    }

    return this.productService.getProduct(id)
      .pipe(
        map(product => ({ product, error: '' })),
        catchError(error => {
          const message = `Retrieval error: ${error}`;
          console.error(message);
          return of({ product: null, error: message });
        })
      );
  }

}


text:
'use strict'
// **Github:** https://github.com/toajs/toa-pm
//
// **License:** MIT

module.exports = function (app, handle) {
  handle = handle || defaultHandle
  if (typeof handle === 'function') handle = {message: handle}

  const events = Object.keys(handle)
  const bindHanles = {}

  events.forEach((event) => {
    bindHanles[event] = handle[event].bind(app)
    process.on(event, bindHanles[event])
  })

  app.server.once('close', function () {
    events.forEach((event) => process.removeListener(event, bindHanles[event]))
  })
}

/**
 * Default handle accept a 'shutdown' message to stop from accepting new connections and keeps existing connections.
 * The server is finally closed and exit gracefully when all connections are ended.
 * For example: `pm2 gracefulReload app`
 */
function defaultHandle (message) {
  if (message === 'shutdown') {
    this.server.close(() => process.exit(0))
  }
}


text:
@interface CrittercismExampleAppViewController : UIViewController <CrittercismDelegate> {

}

-(void) throwSignal;
-(void) throwNestedSignal;
-(void) throwExceptionInThread;
-(void) throwSignalInThread;
-(void) throwRandomException;

//static void staticException();
//static void staticSignal();
//
//-(void) nestedStaticException;
//-(void) nestedStaticSignal;

-(IBAction) feedbackHit:(id) sender;
-(IBAction) leaveBreadcrumbPressed:(id) sender;
-(IBAction) attachMetadataHit:(id) sender;
-(IBAction) crashHit:(id) sender;
-(IBAction) exceptionHit:(id) sender;
-(IBAction) critterHit:(id) sender;
-(IBAction) viewDataHit:(id) sender;
-(void)crittercismDidCrashOnLastLoad;

@end


text:
namespace DanTup.DartVS.ProjectSystem
{
	using System;
	using System.Collections.ObjectModel;
	using System.Runtime.InteropServices;
	using Microsoft.VisualStudio.Project;
	using File = System.IO.File;
	using Path = System.IO.Path;
	using VSCOMPONENTSELECTORDATA = Microsoft.VisualStudio.Shell.Interop.VSCOMPONENTSELECTORDATA;

	[ComVisible(true)]
	public class DartReferenceContainerNode : ReferenceContainerNode
	{
		private static ReadOnlyCollection<string> _supportedReferenceTypes =
			new ReadOnlyCollection<string>(new string[]
				{
					ProjectFileConstants.ProjectReference,
					DartProjectFileConstants.JarReference,
					DartProjectFileConstants.MavenReference,
				});

		public DartReferenceContainerNode(DartProjectNode root)
			: base(root)
		{
			if (root == null)
				throw new ArgumentNullException("root");
		}

		protected override ReadOnlyCollection<string> SupportedReferenceTypes
		{
			get
			{

				return _supportedReferenceTypes;
			}
		}

		protected override ReferenceNode CreateFileComponent(VSCOMPONENTSELECTORDATA selectorData, string wrapperTool = null)
		{
			if (File.Exists(selectorData.bstrFile))
			{
				if (string.Equals(Path.GetExtension(selectorData.bstrFile), ".jar", StringComparison.OrdinalIgnoreCase))
				{
					return CreateJarReferenceNode(selectorData.bstrFile);
				}
				else
				{
					throw new InvalidOperationException("Cannot add a file reference to a non-jar file.");
				}
			}

			return base.CreateFileComponent(selectorData, wrapperTool);
		}

		protected override ReferenceNode CreateReferenceNode(string referenceType, ProjectElement element)
		{
			switch (referenceType)
			{
			case ProjectFileConstants.ProjectReference:
				return CreateProjectReferenceNode(element);

			case DartProjectFileConstants.JarReference:
				return CreateJarReferenceNode(element);

			case DartProjectFileConstants.MavenReference:
				return CreateMavenReferenceNode(element);

			default:
				return null;
			}
		}

		protected virtual ReferenceNode CreateJarReferenceNode(ProjectElement element)
		{
			return new JarReferenceNode(ProjectManager, element);
		}

		protected virtual ReferenceNode CreateMavenReferenceNode(ProjectElement element)
		{
			throw new NotImplementedException();
		}

		protected virtual ReferenceNode CreateJarReferenceNode(string fileName)
		{
			return new JarReferenceNode(ProjectManager, fileName);
		}

		protected virtual ReferenceNode CreateMavenReferenceNode(string fileName)
		{
			throw new NotImplementedException();
		}
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * See https://github.com/openiddict/openiddict-core for more information concerning
 * the license and the contributors participating to this project.
 */

using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AspNet.Security.OpenIdConnect.Extensions;
using AspNet.Security.OpenIdConnect.Primitives;
using AuthorizationServer.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using OpenIddict.Abstractions;
using OpenIddict.Mvc.Internal;
using OpenIddict.Server;

namespace AuthorizationServer.Controllers
{
    public class AuthorizationController : Controller
    {
        private readonly IOptions<IdentityOptions> _identityOptions;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly UserManager<ApplicationUser> _userManager;

        public AuthorizationController(
            IOptions<IdentityOptions> identityOptions,
            SignInManager<ApplicationUser> signInManager,
            UserManager<ApplicationUser> userManager)
        {
            _identityOptions = identityOptions;
            _signInManager = signInManager;
            _userManager = userManager;
        }

        [HttpPost("~/connect/token"), Produces("application/json")]
        public async Task<IActionResult> Exchange([ModelBinder(BinderType = typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request)
        {
            if (request.IsPasswordGrantType())
            {
                var user = await _userManager.FindByNameAsync(request.Username);
                if (user == null)
                {
                    return BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    });
                }

                // Ensure the user is allowed to sign in.
                if (!await _signInManager.CanSignInAsync(user))
                {
                    return BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user is not allowed to sign in."
                    });
                }

                // Reject the token request if two-factor authentication has been enabled by the user.
                if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user))
                {
                    return BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user is not allowed to sign in."
                    });
                }

                // Ensure the user is not already locked out.
                if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user))
                {
                    return BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    });
                }

                // Ensure the password is valid.
                if (!await _userManager.CheckPasswordAsync(user, request.Password))
                {
                    if (_userManager.SupportsUserLockout)
                    {
                        await _userManager.AccessFailedAsync(user);
                    }

                    return BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    });
                }

                if (_userManager.SupportsUserLockout)
                {
                    await _userManager.ResetAccessFailedCountAsync(user);
                }

                // Create a new authentication ticket.
                var ticket = await CreateTicketAsync(request, user);

                return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
            }

            else if (request.IsRefreshTokenGrantType())
            {
                // Retrieve the claims principal stored in the refresh token.
                var info = await HttpContext.Authentication.GetAuthenticateInfoAsync(
                    OpenIddictServerDefaults.AuthenticationScheme);

                // Retrieve the user profile corresponding to the refresh token.
                // Note: if you want to automatically invalidate the refresh token
                // when the user password/roles change, use the following line instead:
                // var user = _signInManager.ValidateSecurityStampAsync(info.Principal);
                var user = await _userManager.GetUserAsync(info.Principal);
                if (user == null)
                {
                    return BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The refresh token is no longer valid."
                    });
                }

                // Ensure the user is still allowed to sign in.
                if (!await _signInManager.CanSignInAsync(user))
                {
                    return BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The user is no longer allowed to sign in."
                    });
                }

                // Create a new authentication ticket, but reuse the properties stored
                // in the refresh token, including the scopes originally granted.
                var ticket = await CreateTicketAsync(request, user, info.Properties);

                return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
            }

            return BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                ErrorDescription = "The specified grant type is not supported."
            });
        }

        private async Task<AuthenticationTicket> CreateTicketAsync(
            OpenIdConnectRequest oidcRequest, ApplicationUser user,
            AuthenticationProperties properties = null)
        {
            // Create a new ClaimsPrincipal containing the claims that
            // will be used to create an id_token, a token or a code.
            var principal = await _signInManager.CreateUserPrincipalAsync(user);

            // Create a new authentication ticket holding the user identity.
            var ticket = new AuthenticationTicket(principal, properties,
                OpenIddictServerDefaults.AuthenticationScheme);

            if (!oidcRequest.IsRefreshTokenGrantType())
            {
                // Set the list of scopes granted to the client application.
                // Note: the offline_access scope must be granted
                // to allow OpenIddict to return a refresh token.
                ticket.SetScopes(new[]
                {
                    OpenIdConnectConstants.Scopes.OpenId,
                    OpenIdConnectConstants.Scopes.Email,
                    OpenIdConnectConstants.Scopes.Profile,
                    OpenIdConnectConstants.Scopes.OfflineAccess,
                    OpenIddictConstants.Scopes.Roles
                }.Intersect(oidcRequest.GetScopes()));
            }

            ticket.SetResources("resource_server");

            // Note: by default, claims are NOT automatically included in the access and identity tokens.
            // To allow OpenIddict to serialize them, you must attach them a destination, that specifies
            // whether they should be included in access tokens, in identity tokens or in both.

            foreach (var claim in ticket.Principal.Claims)
            {
                // Never include the security stamp in the access and identity tokens, as it's a secret value.
                if (claim.Type == _identityOptions.Value.ClaimsIdentity.SecurityStampClaimType)
                {
                    continue;
                }

                var destinations = new List<string>
                {
                    OpenIdConnectConstants.Destinations.AccessToken
                };

                // Only add the iterated claim to the id_token if the corresponding scope was granted to the client application.
                // The other claims will only be added to the access_token, which is encrypted when using the default format.
                if ((claim.Type == OpenIdConnectConstants.Claims.Name && ticket.HasScope(OpenIdConnectConstants.Scopes.Profile)) ||
                    (claim.Type == OpenIdConnectConstants.Claims.Email && ticket.HasScope(OpenIdConnectConstants.Scopes.Email)) ||
                    (claim.Type == OpenIdConnectConstants.Claims.Role && ticket.HasScope(OpenIddictConstants.Claims.Roles)))
                {
                    destinations.Add(OpenIdConnectConstants.Destinations.IdentityToken);
                }

                claim.SetDestinations(destinations);
            }

            return ticket;
        }
    }
}


text:
@interface DQPhoneShopColorPackCell : UICollectionViewCell

@property (nonatomic, strong, readonly) UILabel *titleLabel;
@property (nonatomic, strong, readonly) UILabel *saleLabel;
@property (nonatomic, strong, readonly) DQButton *purchaseButton;
@property (nonatomic, assign) BOOL isPurchased;

- (void)setColors:(NSArray *)colors;

@end


text:
package org.elasticsoftware.elasticactors.kafka.testapp.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsoftware.elasticactors.ActorSystem;
import org.elasticsoftware.elasticactors.ServiceActor;
import org.elasticsoftware.elasticactors.configuration.ClusteringConfiguration;
import org.elasticsoftware.elasticactors.kafka.configuration.NodeConfiguration;
import org.elasticsoftware.elasticactors.spring.ActorAnnotationBeanNameGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.aspectj.EnableSpringConfigured;
import org.springframework.core.env.Environment;

import javax.annotation.PostConstruct;

/**
 * @author Joost van de Wijgerd
 */
@Configuration
@EnableSpringConfigured
@EnableMBeanExport
@PropertySource(value = {"classpath:system.properties", "classpath:application.properties"}, ignoreResourceNotFound = true )
@ComponentScan(
        basePackages = {"org.elasticsoftware.elasticactors.base.serialization","org.elasticsoftware.elasticactors.kafka"},
        nameGenerator = ActorAnnotationBeanNameGenerator.class,
        includeFilters = {@ComponentScan.Filter(value = {ServiceActor.class}, type = FilterType.ANNOTATION)})
@Import(value = {ClusteringConfiguration.class, NodeConfiguration.class})
public class ContainerConfiguration {
    private Environment environment;
    private ActorSystem actorSystem;
    private ObjectMapper objectMapper;

    @Autowired
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Autowired
    public void setActorSystem(ActorSystem actorSystem) {
        this.actorSystem = actorSystem;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @PostConstruct
    public void init() throws Exception {
    }

}


text:
from __future__ import print_function
import sys, os

sys.path.insert(1, os.path.join("..", "..", ".."))
import h2o
from tests import pyunit_utils
from h2o.automl import H2OAutoML

def test_automl_creates_interpretable_SE_iff_monotonic_models_exist():
    train = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
    y = 'CAPSULE'
    train[y] = train[y].asfactor()

    aml_mono = H2OAutoML(project_name="test_automl_creates_interpretable_se",
                         max_models=2,
                         include_algos=["GBM", "XGBoost", "StackedEnsemble"],
                         monotone_constraints=dict(
                             AGE=1, DPROS=1, DCAPS=1, PSA=1, VOL=1, GLEASON=1
                         ),
                         seed=1234)
    aml_mono.train(y=y, training_frame=train)

    assert (aml_mono
            .leaderboard
            .as_data_frame()["model_id"]
            .apply(lambda model_name: "Monotonic" in model_name).any())

    # If we don't have monotonic constraints we shouldn't have monotonically constrained SE
    aml = H2OAutoML(project_name="test_automl_doesnt_create_interpretable_se",
                    max_models=2,
                    include_algos=["GBM", "XGBoost", "StackedEnsemble"],
                    seed=1234)
    aml.train(y=y, training_frame=train)

    assert not (aml
                .leaderboard
                .as_data_frame()["model_id"]
                .apply(lambda model_name: "Monotonic" in model_name).any())

def test_automl_creates_interpretable_SE_with_only_monotonic_models():
    train = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
    y = 'CAPSULE'
    train[y] = train[y].asfactor()

    aml_mono = H2OAutoML(project_name="test_automl_creates_interpretable_se",
                         max_models=5,
                         include_algos=["GBM", "GLM", "XGBoost", "StackedEnsemble"],
                         monotone_constraints=dict(
                             AGE=1, DPROS=1, DCAPS=1, PSA=1, VOL=1, GLEASON=1
                         ),
                         seed=1234)
    aml_mono.train(y=y, training_frame=train)

    leaderboard = (aml_mono
        .leaderboard
        .as_data_frame()["model_id"])

    assert leaderboard.apply(lambda model_name: "Monotonic" in model_name).any()

    se_name = leaderboard[leaderboard.apply(lambda model_name: "Monotonic" in model_name)]
    se_mono = h2o.get_model(se_name.iloc[0])

    assert leaderboard.apply(lambda model_name: 'GLM' in model_name).any()
    assert all(['GBM' in bm or 'XGBoost' in bm for bm in se_mono.base_models])

pyunit_utils.run_tests([
    test_automl_creates_interpretable_SE_iff_monotonic_models_exist,
    test_automl_creates_interpretable_SE_with_only_monotonic_models
])


text:
require 'spec_helper'

module Pillar

	describe Configuration do

		before(:each) do
	    Pillar.configure do |config|
			end
	  end

		describe "#hosts" do

	    it "should be be default" do
	    	expect(Pillar.configuration.hosts).to eq(['127.0.0.1'])
			end

			it "should be be custom" do
				Pillar.configure do |config|
					config.hosts = ['127.0.0.1', '127.0.0.2', '127.0.0.3']
				end
				expect(Pillar.configuration.hosts).to eq(['127.0.0.1', '127.0.0.2', '127.0.0.3'])
			end

	  end

	  describe "#log_path" do

			it "should be be default" do
				expect(Pillar.configuration.log_path).to eq('/var/log/pillar.log')
			end

			it "should be be custom" do
				Pillar.configure do |config|
					config.log_path = '/my/custom/path'
				end
				expect(Pillar.configuration.log_path).to eq('/my/custom/path')
			end

	  end

	end

end


text:
function Validation_stats = as_eval_seg_quality(axonlist_control,axonlist_test,img)

% Validation methods that can be used :
% - Correlation coefficient (2D) between the 2 binary images segmented
% - Number of objects in each binary image (test vs control)
% - % of axons of test that are also in control (use centroids)

img_BW_control=as_display_label(axonlist_control,size(img),'axonEquivDiameter','axon');
img_BW_test=as_display_label(axonlist_test,size(img),'axonEquivDiameter','axon');

img_BW_control=im2bw(img_BW_control,0);
img_BW_test=im2bw(img_BW_test,0);

imshow(img_BW_control);
imshow(img_BW_test);

% Sensitivity stats

[sensitivity, TP, FP, FN,~,~,J]=eval_sensitivity_new(img_BW_test,img_BW_control);

% Correlation coefficient
corr_coef=corr2(img_BW_control,img_BW_test);
Validation_stats.corr_coef=corr_coef;

% Number of objects in each binary image

[~,num_control] = bwlabel(img_BW_control,8);
[~,num_test] = bwlabel(img_BW_test,8);

Validation_stats.num_objects_control=num_control;
Validation_stats.num_objects_test=num_test;

% Number of pixels in both, only control or only test

pixels_in_both = img_BW_control&img_BW_test;
pixels_only_control = logical(img_BW_control-pixels_in_both);
pixels_only_test = logical(img_BW_test-pixels_in_both);

nbr_pixels_in_both = sum(sum(pixels_in_both));
nbr_pixels_only_control = sum(sum(pixels_only_control));
nbr_pixels_only_test = sum(sum(pixels_only_test));

Validation_stats.nbr_pix_in_both=nbr_pixels_in_both;
Validation_stats.nbr_pix_only_control=nbr_pixels_only_control;
Validation_stats.nbr_pix_only_test=nbr_pixels_only_test;

% Jaccard & others

intersection_img=img_BW_control&img_BW_test;
union_img=img_BW_control|img_BW_test;

a=sum(sum(intersection_img));
b=sum(sum(pixels_only_control));
c=sum(sum(pixels_only_test));
d=sum(sum(union_img));

n=a+b+c+d;

Validation_stats.Jaccard=a/(a+b+c);
Validation_stats.PatternDifference=(4*b*c)/n^2;
Validation_stats.SizeDifference=(b+c)^2/n^2;
Validation_stats.ShapeDifference=(n*(b+c)-(b-c)^2)/n^2;

% Plot comparison results

% figure(1);
% sc(sc(pixels_in_both,[1 1 1],pixels_in_both)+sc(pixels_only_control,[0 0.5 0],pixels_only_control)+sc(pixels_only_test,[1 0 0],pixels_only_test));

end


text:
/*
Styles Switcher.
*/
.style-switcher {
	height: 100%;
	left: -290px;
	position: fixed;
	top: 150px;
	width: 290px;
	z-index: 20000;
	-webkit-transition: all 0.3s ease;
	transition: all 0.3s ease;
}
.style-switcher.open {
	left: 0;
}
.style-switcher .stoggler {
	background: #fff;
	border-image: none;
	border-radius: 0 5px 5px 0;
	box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
	color: #777;
	cursor: pointer;
	display: block;
	font-size: 24px;
	height: 55px;
	line-height: 55px;
	position: absolute;
	right: -49px;
	text-align: center;
	top: 0;
	width: 50px;
	z-index: 1;
	-webkit-transition: all 0.3s ease;
	transition: all 0.3s ease;
}
.style-switcher .stoggler:hover {
	box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
}
.style-switcher .stoggler i {
	line-height: 55px;
}
.style-switcher h2, .style-switcher h3 {
	color: #777;
	font-size: 14px;
	font-weight: normal;
}
.style-switcher h2 {
	border-bottom: 1px solid #eee;
    font-size: 15px;
    font-weight: 700;
    margin: 0 0 20px;
    padding-bottom: 5px;
    text-transform: uppercase;
}
.style-switcher h3 {
	margin-top: 15px;
}
.style-switcher select {
    border: 1px solid #ddd;
	height: 28px;
	width: 100%;
}
.style-switcher .spanel {
	background: #fff none repeat scroll 0 0;
	box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
	float: left;
	height: auto;
	padding: 32px 25px;
	position: relative;
	width: 100%;
	z-index: 2;
	top: 0;
}
.style-switcher ul {
	margin: 0;
	padding: 0;
}
.style-switcher #resetpreview {
	background: #777;
    border: none;
    border-radius: 2px;
    margin: 10px 0 0;
	-webkit-transition: all 0.3s ease;
	transition: all 0.3s ease;
}
.style-switcher #resetpreview:hover {
	background: #555;
}
.style-switcher .colors {
	list-style: none;
	margin: 0 0 10px;
	overflow: hidden;
}
.style-switcher .colors li {
	float: left;
	margin: 4px 2px 0;
}
.style-switcher .colors li a {
	cursor: pointer;
	display: block;
	height: 17px;
	width: 17px;
}
#bg a {
	border: 1px solid #ccc;
}
.green-bg {
	background-color: #3acf87 !important;
}
.blue-bg {
	background-color: #2db2ea !important;
}
.orange-bg {
	background-color: #fa5b0f !important;
}
.navy-bg {
	background-color: #495d7f !important;
}
.yellow-bg {
	background-color: #ffb400 !important;
}
.peach-bg {
	background-color: #fcab55 !important;
}
.red-bg {
	background-color: #dd3737 !important;
}
.beige-bg {
	background-color: #bfa980 !important;
}
.pink-bg {
	background-color: #d64391 !important;
}
.cyan-bg {
	background-color: #37b6bd !important;
}
.celadon-bg {
	background-color: #74aea1 !important;
}
.brown-bg {
	background-color: #784e3d !important;
}
.cherry-bg {
	background-color: #911938 !important;
}
.gray-bg {
	background-color: #808080 !important;
}
.purple-bg {
	background-color: #917ae9 !important;
}
.dark-bg {
	background-color: #404040 !important;
}
.green-text {
	color: #3acf87 !important;
}
.blue-text {
	color: #2db2ea !important;
}
.orange-text {
	color: #fa5b0f !important;
}
.navy-text {
	color: #495d7f !important;
}
.yellow-text {
	color: #ffb400 !important;
}
.peach-text {
	color: #fcab55 !important;
}
.red-text {
	color: #dd3737 !important;
}
.beige-text {
	color: #bfa980 !important;
}
.pink-text {
	color: #d64391 !important;
}
.cyan-text {
	color: #37b6bd !important;
}
.celadon-text {
	color: #74aea1 !important;
}
.brown-text {
	color: #784e3d !important;
}
.cherry-text {
	color: #911938 !important;
}
.white-text {
	color: #ffffff !important;
}
.purple-text {
	color: #917ae9 !important;
}
.dark-text {
	color: #404040 !important;
}
#saletextcolor .green-text {
	background-color: #3acf87 !important;
}
#saletextcolor .blue-text {
	background-color: #2db2ea !important;
}
#saletextcolor .orange-text {
	background-color: #fa5b0f !important;
}
#saletextcolor .navy-text {
	background-color: #495d7f !important;
}
#saletextcolor .yellow-text {
	background-color: #ffb400 !important;
}
#saletextcolor .peach-text {
	background-color: #fcab55 !important;
}
#saletextcolor .red-text {
	background-color: #dd3737 !important;
}
#saletextcolor .beige-text {
	background-color: #bfa980 !important;
}
#saletextcolor .pink-text {
	background-color: #d64391 !important;
}
#saletextcolor .cyan-text {
	background-color: #37b6bd !important;
}
#saletextcolor .celadon-text {
	background-color: #74aea1 !important;
}
#saletextcolor .brown-text {
	background-color: #784e3d !important;
}
#saletextcolor .cherry-text {
	background-color: #911938 !important;
}
#saletextcolor .white-text {
	background-color: #ffffff !important;
}
#saletextcolor .purple-text {
	background-color: #917ae9 !important;
}
#saletextcolor .dark-text {
	background-color: #404040 !important;
}
.bg0 {
	background-image: url("../images/bg/pattern0.png") !important;
	background-repeat: repeat !important;
}
.bg1 {
	background-image: url("../images/bg/pattern1.png") !important;
	background-repeat: repeat !important;
}
.bg2 {
	background-image: url("../images/bg/pattern2.png") !important;
	background-repeat: repeat !important;
}
.bg3 {
	background-image: url("../images/bg/pattern3.png") !important;
	background-repeat: repeat !important;
}
.bg4 {
	background-image: url("../images/bg/pattern4.png") !important;
	background-repeat: repeat !important;
}
.bg5 {
	background-image: url("../images/bg/pattern5.png") !important;
	background-repeat: repeat !important;
}
.bg6 {
	background-image: url("../images/bg/pattern6.png") !important;
	background-repeat: repeat !important;
}
.bg7 {
	background-image: url("../images/bg/pattern7.png") !important;
	background-repeat: repeat !important;
}
.bg8 {
	background-image: url("../images/bg/pattern8.png") !important;
	background-repeat: repeat !important;
}
.bg9 {
	background-image: url("../images/bg/pattern9.png") !important;
	background-repeat: repeat !important;
}
.bg10 {
	background-image: url("../images/bg/pattern10.png") !important;
	background-repeat: repeat !important;
}
.bg11 {
	background-image: url("../images/bg/pattern11.png") !important;
	background-repeat: repeat !important;
}
.bg12 {
	background-image: url("../images/bg/pattern12.png") !important;
	background-repeat: repeat !important;
}
.bg13 {
	background-image: url("../images/bg/pattern13.png") !important;
	background-repeat: repeat !important;
}
.bg14 {
	background-image: url("../images/bg/pattern14.png") !important;
	background-repeat: repeat !important;
}
.bg15 {
	background-image: url("../images/bg/pattern15.png") !important;
	background-repeat: repeat !important;
}
.bg16 {
	background-image: url("../images/bg/pattern16.png") !important;
	background-repeat: repeat !important;
}
.bg17 {
	background-image: url("../images/bg/pattern17.png") !important;
	background-repeat: repeat !important;
}
.bg18 {
	background-image: url("../images/bg/pattern18.png") !important;
	background-repeat: repeat !important;
}
.bg19 {
	background-image: url("../images/bg/pattern19.png") !important;
	background-repeat: repeat !important;
}
.bg20 {
	background-image: url("../images/bg/pattern20.png") !important;
	background-repeat: repeat !important;
}
.bg21 {
	background-image: url("../images/bg/pattern21.png") !important;
	background-repeat: repeat !important;
}
.bg22 {
	background-image: url("../images/bg/pattern22.png") !important;
	background-repeat: repeat !important;
}
.bg23 {
	background-image: url("../images/bg/pattern23.png") !important;
	background-repeat: repeat !important;
}
.bg24 {
	background-image: url("../images/bg/pattern24.png") !important;
	background-repeat: repeat !important;
}
.bg25 {
	background-image: url("../images/bg/pattern25.png") !important;
	background-repeat: repeat !important;
}
.bg26 {
	background-image: url("../images/bg/pattern26.png") !important;
	background-repeat: repeat !important;
}
.bg27 {
	background-image: url("../images/bg/pattern27.png") !important;
	background-repeat: repeat !important;
}
.bg28 {
	background-image: url("../images/bg/pattern28.png") !important;
	background-repeat: repeat !important;
}
.bg29 {
	background-image: url("../images/bg/pattern29.png") !important;
	background-repeat: repeat !important;
}
.bg30 {
	background-image: url("../images/bg/pattern30.png") !important;
	background-repeat: repeat !important;
}
.presets {
    margin-top: 20px;
}
ul.preset {
	margin-left: -5px;
    margin-right: -5px;
    margin-top: 10px;
}
ul.preset li {
    float: left;
    list-style: none;
    margin: 0 0 5px;
	padding: 0 5px;
    width: 50%;
}
ul.preset li a {
	color: #fff;
    display: block;
    padding: 5px 0;
    text-align: center;
    text-transform: uppercase;
}
ul.preset li a.preset1 {
	background: #C43B68;
}
ul.preset li a.preset2 {
	background: #5ed9e7;
}
ul.preset li a.preset3 {
	background: #D95380;
}
ul.preset li a.preset4 {
	background: #FFB548;
}
ul.preset li a.preset5 {
	background: #3ACF87;
}
ul.preset li a.preset6 {
	background: #DB6163;
}
.home-layouts {
	clear: both;
	float: left;
    margin-top: 20px;
}
.layout-scroll {
	float: left;
	height: 250px;
	width: 240px;
}
.layout-scroll ul {
	float: left;
	margin: 0;
	padding: 0;
	list-style: none;
	width: 100%;
}
.layout-scroll ul li {
	float: left;
	margin: 0 0 6px;
	padding: 0 6px 0 0;
	width: 50%;
}
.layout-scroll ul li a {
	background: #999;
    border: 1px solid #eee;
    color: #fff;
    float: left;
    text-align: center;
    text-transform: uppercase;
    width: 100%;
}
.layout-scroll ul li a:hover {
	border: 1px solid #777;
}
@-webkit-keyframes spinnerRotate
{
    from{-webkit-transform:rotate(0deg);}
    to{-webkit-transform:rotate(360deg);}
}
@-moz-keyframes spinnerRotate
{
    from{-moz-transform:rotate(0deg);}
    to{-moz-transform:rotate(360deg);}
}
@-ms-keyframes spinnerRotate
{
    from{-ms-transform:rotate(0deg);}
    to{-ms-transform:rotate(360deg);}
}
.stoggler .fa {
    -webkit-animation-name: spinnerRotate;
    -webkit-animation-duration: 5s;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;
    -moz-animation-name: spinnerRotate;
    -moz-animation-duration: 5s;
    -moz-animation-iteration-count: infinite;
    -moz-animation-timing-function: linear;
    -ms-animation-name: spinnerRotate;
    -ms-animation-duration: 5s;
    -ms-animation-iteration-count: infinite;
    -ms-animation-timing-function: linear;
}


text:
package org.apache.lucene.queries.function.valuesource;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.FloatDocValues;
import org.apache.lucene.search.IndexSearcher;

import java.io.IOException;
import java.util.Map;

/**
 * ReciprocalFloatFunction implements a reciprocal function f(x) = a/(mx+b), based on
 * the float value of a field or function as exported by {@link org.apache.lucene.queries.function.ValueSource}.
 *

 *
 * When a and b are equal, and x>=0, this function has a maximum value of 1 that drops as x increases.
 * Increasing the value of a and b together results in a movement of the entire function to a flatter part of the curve.
 *
These properties make this an idea function for boosting more recent documents.
 *
Example:  recip(ms(NOW,mydatefield),3.16e-11,1,1)
 *
A multiplier of 3.16e-11 changes the units from milliseconds to years (since there are about 3.16e10 milliseconds
 * per year).  Thus, a very recent date will yield a value close to 1/(0+1) or 1,
 * a date a year in the past will get a multiplier of about 1/(1+1) or 1/2,
 * and date two years old will yield 1/(2+1) or 1/3.
 *
 * @see org.apache.lucene.queries.function.FunctionQuery
 *
 *
 */
public class ReciprocalFloatFunction extends ValueSource {
  protected final ValueSource source;
  protected final float m;
  protected final float a;
  protected final float b;

  /**
   *  f(source) = a/(m*float(source)+b)
   */
  public ReciprocalFloatFunction(ValueSource source, float m, float a, float b) {
    this.source=source;
    this.m=m;
    this.a=a;
    this.b=b;
  }

  @Override
  public FunctionValues getValues(Map context, AtomicReaderContext readerContext) throws IOException {
    final FunctionValues vals = source.getValues(context, readerContext);
    return new FloatDocValues(this) {
      @Override
      public float floatVal(int doc) {
        return a/(m*vals.floatVal(doc) + b);
      }
      @Override
      public String toString(int doc) {
        return Float.toString(a) + "/("
                + m + "*float(" + vals.toString(doc) + ')'
                + '+' + b + ')';
      }
    };
  }

  @Override
  public void createWeight(Map context, IndexSearcher searcher) throws IOException {
    source.createWeight(context, searcher);
  }

  @Override
  public String description() {
    return Float.toString(a) + "/("
           + m + "*float(" + source.description() + ")"
           + "+" + b + ')';
  }

  @Override
  public int hashCode() {
    int h = Float.floatToIntBits(a) + Float.floatToIntBits(m);
    h ^= (h << 13) | (h >>> 20);
    return h + (Float.floatToIntBits(b)) + source.hashCode();
  }

  @Override
  public boolean equals(Object o) {
    if (ReciprocalFloatFunction.class != o.getClass()) return false;
    ReciprocalFloatFunction other = (ReciprocalFloatFunction)o;
    return this.m == other.m
            && this.a == other.a
            && this.b == other.b
            && this.source.equals(other.source);
  }
}


text:
namespace Stripe
{
    using System.Collections.Generic;
    using Newtonsoft.Json;

    public class EventListOptions : ListOptionsWithCreated
    {
        [JsonProperty("delivery_success")]
        public bool? DeliverySuccess { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("types")]
        public List<string> Types { get; set; }
    }
}


text:
{% extends 'observacoes/base.html' %}
{% block body %}

    {% set observacoe=observacoe or None %}
    {% set errors=errors or None %}

{% trans %}Observacoe Form{% endtrans %}

                    <form action="{{ save_path }}" method="post" role="form">
                        {{ csrf_input() }}

                        {{ form_input(_('Setor'),'setor',observacoe.setor,errors.setor) }}
                        {{ form_input(_('Linha'),'linha',observacoe.linha,errors.linha) }}
                        {{ form_input(_('Data'),'data',observacoe.data,errors.data) }}
                        {{ form_input(_('Comportamento'),'comportamento',observacoe.comportamento,errors.comportamento) }}
                        {{ form_input(_('Nome'),'nome',observacoe.nome,errors.nome) }}
                        <button type="submit" class="btn btn-success">{% trans %}Save{% endtrans %}</button>
                    </form>

{% endblock %}


text:
package com.andreabaccega.formedittextvalidator;

import java.util.regex.Pattern;

import android.os.Build;
import android.util.Patterns;

/**
 * Validates a web url in the format:
 * scheme + authority + path
 * @author Andrea Baccega <me@andreabaccega.com>
 *
 */
public class WebUrlValidator extends PatternValidator {
	public WebUrlValidator(String _customErrorMessage) {
		//TODO: Fix the pattern for api level < 8
		super(_customErrorMessage, Build.VERSION.SDK_INT>=8?Patterns.WEB_URL:Pattern.compile(".*"));
	}
}


text:
import "./foo.spec";
import "./list-mania.spec";
import "./schema.spec";
import "./serialization-demo.spec";
import "./upgrade.spec";


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/loot/quest/shared_sean_questn_alog.iff"
	result.attribute_template_id = -1
	result.stfName("item_n","sean_questn_alog")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
<!DOCTYPE html>

    <title>Events</title>
    <meta charset="utf-8">
    <link href="../../content/shared/styles/examples-offline.css" rel="stylesheet">
    <link href="../../../styles/kendo.common.min.css" rel="stylesheet">
    <link href="../../../styles/kendo.rtl.min.css" rel="stylesheet">
    <link href="../../../styles/kendo.default.min.css" rel="stylesheet">

        Back

ProgressBar

        <button id="startProgress" class="k-button">Start progress</button>

Console log


text:
1. Pregunta clau

Com es vàren formar els primers regnes cristians?

Els  expercits musulmans van envair la península ibèrica, una granja estrea del nord peninsular va quedar fora del control dels emirs andalusins.

Els primers emirs de Còrdova van exigir tributs als habitatns d'aquestes terres a cavni de deixar que s'hi quedaren.

Van aparèixer diversos nuclis de resistència a la domnació islàmica en els territoris al voltant de les muntanyes d'Astúries i la franja cantàbrica.

Sorgeix la Marca Hispànica, creada pels reis francs.


text:
package io.github.tryexceptelse.jdex.fe;

/**
 * UI interface implemented by either GUI or TUI
 */
public interface Ui {
    /**
     * method called in order to maintain user interface
     * This method should be called each iteration of the main loop.
      */
    void run(String[] args);
}


text:
package com.vaadin.addon.sqlcontainer.query.generator.filter;

import com.vaadin.addon.sqlcontainer.query.generator.StatementHelper;
import com.vaadin.data.Container.Filter;
import com.vaadin.data.util.filter.IsNull;

public class IsNullTranslator implements FilterTranslator {

    public boolean translatesFilter(Filter filter) {
        return filter instanceof IsNull;
    }

    public String getWhereStringForFilter(Filter filter, StatementHelper sh) {
        IsNull in = (IsNull) filter;
        return QueryBuilder.quote(in.getPropertyId()) + " IS NULL";
    }
}


text:
/**
 * @author yzimroni
 */

package com.yanayzimroni.bukkit.offlinemessage.messages;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;

import com.yanayzimroni.bukkit.offlinemessage.OfflineMessagePlugin;

public class MySqlMessagesManager implements MessagesManager {

	private String prefix;
	private Connection conn;

	public MySqlMessagesManager(String host, int port, String database, String user, String password, String prefix) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, user, password);
			setPrefix(prefix);
			conn.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS " + getPrefix() + "offlinemessage (ID int(11) NOT NULL AUTO_INCREMENT,Player varchar(36) NOT NULL,Message varchar(1000) NOT NULL,PRIMARY KEY (ID)) DEFAULT CHARSET=utf8;");
		}
		catch(Exception ex) {
			ex.printStackTrace();
		}
	}

	@Override
	public void sendMessage(final UUID uuid, final String message) {
		Bukkit.getScheduler().runTaskAsynchronously(OfflineMessagePlugin.plugin, new Runnable() {

			@Override
			public void run() {
				try {
					PreparedStatement pre = conn.prepareStatement("INSERT INTO " + getPrefix() + "offlinemessage (Player, Message) VALUES (?, ?);");
					pre.setString(1, uuid.toString());
					pre.setString(2, message);
					pre.executeUpdate();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void sendMessage(OfflinePlayer player, String message) {
		sendMessage(player.getUniqueId(), message);
	}

	@Override
	public void sendMessages(final UUID uuid, final String... messages) {
		Bukkit.getScheduler().runTaskAsynchronously(OfflineMessagePlugin.plugin, new Runnable() {
			@Override
			public void run() {
				try {
					String values = "";
					for (int i = 0; i<messages.length; i++) {
						if (!values.isEmpty()) values += ",";
						values += "VALUES (?, ?)";
					}
					PreparedStatement pre = conn.prepareStatement("INSERT INTO " + getPrefix() + "offlinemessage (Player, Message) " + values);
					int index = 1;
					for (String message : messages) {
						pre.setString(index, uuid.toString());
						index++;
						pre.setString(index, message);
					}

					pre.executeUpdate();

				} catch (SQLException e) {
					e.printStackTrace();
				}

			}
		});
	}

	@Override
	public void sendMessages(OfflinePlayer player, String... messages) {
		sendMessages(player.getUniqueId(), messages);
	}

	@Override
	public List<String> getMessages(UUID uuid) {
		try {
			List<String> messages = new ArrayList<String>();
			PreparedStatement pre = conn.prepareStatement("SELECT Message FROM " + getPrefix() + "offlinemessage WHERE Player = ?");
			pre.setString(1, uuid.toString());
			ResultSet rs = pre.executeQuery();
			while (rs.next()) {
				messages.add(rs.getString("Message"));
			}
			return messages;
		} catch (SQLException e) {
			e.printStackTrace();

		}
		return null;
	}

	@Override
	public List<String> getMessages(OfflinePlayer player) {
		return getMessages(player.getUniqueId());
	}

	@Override
	public void resetMessages(final UUID uuid) {
		Bukkit.getScheduler().runTaskAsynchronously(OfflineMessagePlugin.plugin, new Runnable() {
			@Override
			public void run() {
				try {
					PreparedStatement pre = conn.prepareStatement("DELETE FROM " + getPrefix() + "offlinemessage WHERE Player = ?");
					pre.setString(1, uuid.toString());
					pre.executeUpdate();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void resetMessages(OfflinePlayer player) {
		resetMessages(player.getUniqueId());
	}

	@Override
	public String getType() {
		return "MySQL";
	}

	/**
	 * @return the prefix
	 */
	public String getPrefix() {
		return prefix;
	}

	/**
	 * @param prefix the prefix to set
	 */
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

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

}


text:
.class final Lcom/zte/mifavor/preference/SeekBarVolumizer$Observer;
.super Landroid/database/ContentObserver;
.source "SeekBarVolumizer.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/zte/mifavor/preference/SeekBarVolumizer;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x12
    name = "Observer"
.end annotation

# instance fields
.field final synthetic this$0:Lcom/zte/mifavor/preference/SeekBarVolumizer;

# direct methods
.method public constructor <init>(Lcom/zte/mifavor/preference/SeekBarVolumizer;Landroid/os/Handler;)V
    .locals 0
    .param p2, "handler"    # Landroid/os/Handler;

    .prologue
    .line 282
    iput-object p1, p0, Lcom/zte/mifavor/preference/SeekBarVolumizer$Observer;->this$0:Lcom/zte/mifavor/preference/SeekBarVolumizer;

    .line 283
    invoke-direct {p0, p2}, Landroid/database/ContentObserver;-><init>(Landroid/os/Handler;)V

    .line 284
    return-void
.end method

# virtual methods
.method public onChange(Z)V
    .locals 3
    .param p1, "selfChange"    # Z

    .prologue
    .line 288
    invoke-super {p0, p1}, Landroid/database/ContentObserver;->onChange(Z)V

    .line 289
    iget-object v1, p0, Lcom/zte/mifavor/preference/SeekBarVolumizer$Observer;->this$0:Lcom/zte/mifavor/preference/SeekBarVolumizer;

    # getter for: Lcom/zte/mifavor/preference/SeekBarVolumizer;->mSeekBar:Landroid/widget/SeekBar;
    invoke-static {v1}, Lcom/zte/mifavor/preference/SeekBarVolumizer;->access$200(Lcom/zte/mifavor/preference/SeekBarVolumizer;)Landroid/widget/SeekBar;

    move-result-object v1

    if-eqz v1, :cond_0

    iget-object v1, p0, Lcom/zte/mifavor/preference/SeekBarVolumizer$Observer;->this$0:Lcom/zte/mifavor/preference/SeekBarVolumizer;

    # getter for: Lcom/zte/mifavor/preference/SeekBarVolumizer;->mAudioManager:Landroid/media/AudioManager;
    invoke-static {v1}, Lcom/zte/mifavor/preference/SeekBarVolumizer;->access$400(Lcom/zte/mifavor/preference/SeekBarVolumizer;)Landroid/media/AudioManager;

    move-result-object v1

    if-eqz v1, :cond_0

    .line 290
    iget-object v1, p0, Lcom/zte/mifavor/preference/SeekBarVolumizer$Observer;->this$0:Lcom/zte/mifavor/preference/SeekBarVolumizer;

    # getter for: Lcom/zte/mifavor/preference/SeekBarVolumizer;->mAudioManager:Landroid/media/AudioManager;
    invoke-static {v1}, Lcom/zte/mifavor/preference/SeekBarVolumizer;->access$400(Lcom/zte/mifavor/preference/SeekBarVolumizer;)Landroid/media/AudioManager;

    move-result-object v1

    iget-object v2, p0, Lcom/zte/mifavor/preference/SeekBarVolumizer$Observer;->this$0:Lcom/zte/mifavor/preference/SeekBarVolumizer;

    # getter for: Lcom/zte/mifavor/preference/SeekBarVolumizer;->mStreamType:I
    invoke-static {v2}, Lcom/zte/mifavor/preference/SeekBarVolumizer;->access$500(Lcom/zte/mifavor/preference/SeekBarVolumizer;)I

    move-result v2

    invoke-virtual {v1, v2}, Landroid/media/AudioManager;->getStreamVolume(I)I

    move-result v0

    .line 291
    .local v0, "volume":I
    iget-object v1, p0, Lcom/zte/mifavor/preference/SeekBarVolumizer$Observer;->this$0:Lcom/zte/mifavor/preference/SeekBarVolumizer;

    # getter for: Lcom/zte/mifavor/preference/SeekBarVolumizer;->mUiHandler:Lcom/zte/mifavor/preference/SeekBarVolumizer$H;
    invoke-static {v1}, Lcom/zte/mifavor/preference/SeekBarVolumizer;->access$600(Lcom/zte/mifavor/preference/SeekBarVolumizer;)Lcom/zte/mifavor/preference/SeekBarVolumizer$H;

    move-result-object v1

    invoke-virtual {v1, v0}, Lcom/zte/mifavor/preference/SeekBarVolumizer$H;->postUpdateSlider(I)V

    .line 293
    .end local v0    # "volume":I
    :cond_0
    return-void
.end method


text:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/include/autoprepend.php');
// +----------------------------------------------------------------------+
// | PHP version 5                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 2002-2006 James Heinrich, Allan Hansen                 |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2 of the GPL license,         |
// | that is bundled with this package in the file license.txt and is     |
// | available through the world-wide-web at the following url:           |
// | http://www.gnu.org/copyleft/gpl.html                                 |
// +----------------------------------------------------------------------+
// | getID3() - http://getid3.sourceforge.net or http://www.getid3.org    |
// +----------------------------------------------------------------------+
// | Authors: James Heinrich <infoØgetid3*org>                            |
// |          Allan Hansen <ahØartemis*dk>                                |
// +----------------------------------------------------------------------+
// | module.graphic.jpeg.php                                              |
// | Module for analyzing JPEG graphic files.                             |
// | dependencies: exif support in PHP (optional)                         |
// +----------------------------------------------------------------------+
//
// $Id: module.graphic.jpeg.php,v 1.1 2013-09-30 09:31:10 raphael Exp $

class getid3_jpeg extends getid3_handler
{

    public function Analyze() {

        $getid3 = $this->getid3;

        $getid3->info['fileformat']                  = 'jpg';
        $getid3->info['video']['dataformat']         = 'jpg';
        $getid3->info['video']['lossless']           = false;
        $getid3->info['video']['bits_per_sample']    = 24;
        $getid3->info['video']['pixel_aspect_ratio'] = (float)1;

        fseek($getid3->fp, $getid3->info['avdataoffset'], SEEK_SET);

        list($getid3->info['video']['resolution_x'], $getid3->info['video']['resolution_y'], $type) = getimagesize($getid3->filename);

        if ($type != 2) {
            throw new getid3_exception('File detected as JPEG, but is currupt.');
        }

        if (function_exists('exif_read_data')) {

            $getid3->info['jpg']['exif'] = exif_read_data($getid3->filename, '', true, false);

        } else {

            $getid3->warning('EXIF parsing only available when compiled with --enable-exif (or php_exif.dll enabled for Windows).');
        }

        return true;
    }

}

?>


text:
require_relative 'creative_asset_utils'
require_relative 'dfareporting_utils'

def create_flash_inpage_creative(dfareporting, args)
  util = CreativeAssetUtils.new(dfareporting, args[:profile_id])

  # Upload the flash asset
  flash_asset_id = util.uploadAsset(args[:advertiser_id],
      args[:path_to_flash_asset_file], 'FLASH')

  # Upload the backup image asset
  backup_image_asset_id = util.uploadAsset(args[:advertiser_id],
      args[:path_to_backup_image_file], 'HTML_IMAGE')

  # Construct the creative structure
  creative = {
    :advertiserId => args[:advertiser_id],
    :backupImageTargetWindow => { :targetWindowOption => 'NEW_WINDOW' },
    :clickTags => [{ :name => 'click_tag' }],
    :creativeAssets => [
      {
        :assetIdentifier => flash_asset_id,
        :role => 'PRIMARY',
        :windowMode => 'TRANSPARENT'
      },
      {
        :assetIdentifier => backup_image_asset_id,
        :role => 'BACKUP_IMAGE'
      }
    ],
    :name => 'Example flash in-page creative',
    :size => { :id => args[:size_id] },
    :type => 'FLASH_INPAGE'
  }

  # Insert the creative
  result = dfareporting.creatives.insert(
    :profileId => args[:profile_id]
  ).body(creative).execute()

  puts 'Created flash in-page creative with ID %d and name "%s".' %
      [result.data.id, result.data.name]
end

if __FILE__ == $0
  # Retrieve command line arguments
  args = DfaReportingUtils.get_arguments(
      ARGV, :profile_id, :advertiser_id, :size_id, :path_to_flash_asset_file,
      :path_to_backup_image_file)

  # Authenticate and initialize API service
  dfareporting = DfaReportingUtils.setup()

  create_flash_inpage_creative(dfareporting, args)
end


text:
#include <cc7tests/TestManager.h>
#include <cc7tests/PerformanceTimer.h>
#include <cc7tests/detail/StringUtils.h>

#include <cc7/DebugFeatures.h>
#include <algorithm>

namespace cc7
{
namespace tests
{
	// ------------------------------------------------------------------------------------
	// MARK: Instantiation

	TestManager::TestManager() :
		_test_manager_name("CC7"),
		_assertion_breakpoint_enabled(false),
		_log_capturig_enabled(false),
		_old_assertion_setup({nullptr, nullptr}),
		_old_log_setup({nullptr, nullptr})
	{

	}

	TestManager::~TestManager()
	{
	}

	extern const UnitTestCreationInfoList _GetDefaultUnitTestCreationInfoList();

	TestManager * TestManager::createDefaultManager()
	{
		TestManager * tm = new TestManager();
		tm->addUnitTestList(_GetDefaultUnitTestCreationInfoList());
		return tm;
	}

	TestManager * TestManager::createEmptyManager()
	{
		return new TestManager();
	}

	void TestManager::releaseManager(cc7::tests::TestManager *manager)
	{
		delete manager;
	}

	// ------------------------------------------------------------------------------------
	// MARK: Breakpoints configuration

	void TestManager::setAssertionBreakpointEnabled(bool enabled)
	{
		_assertion_breakpoint_enabled = enabled;
	}

	bool TestManager::assertionBreakpointEnabled() const
	{
		return _assertion_breakpoint_enabled;
	}

	void TestManager::setIncidentBreakpointEnabled(bool enabled)
	{
		tl().setIncidentBreakpointEnabled(enabled);
	}

	bool TestManager::incidentBreakpointEnabled() const
	{
		return tl().incidentBreakpointEnabled();
	}

	void TestManager::setLogCapturingEnabled(bool enabled)
	{
		_log_capturig_enabled = enabled;
	}

	bool TestManager::logCapturingEnabled() const
	{
		return _log_capturig_enabled;
	}

	// ------------------------------------------------------------------------------------
	// MARK: Tests registration

	void TestManager::addUnitTest(UnitTestCreationInfo test_info)
	{
		bool valid_info = test_info != nullptr &&
						  test_info->factory != nullptr &&
						  test_info->name != nullptr;
		if (valid_info) {
			if (std::find(_registered_tests.begin(), _registered_tests.end(), test_info) == _registered_tests.end()) {
				// Not added yet
				_registered_tests.push_back(test_info);
			} else {
				CC7_LOG("TestManager: '%s' is already registered in this manager.", test_info->name);
			}
		} else {
			CC7_ASSERT(false, "test_info is NULL or contains invalid information");
		}
	}

	void TestManager::addUnitTestList(const UnitTestCreationInfoList & test_info_list)
	{
		_registered_tests.reserve(_registered_tests.size() + test_info_list.size());
		for (auto test_info : test_info_list) {
			addUnitTest(test_info);
		}
	}

	// ------------------------------------------------------------------------------------
	// MARK: Tests execution

	bool TestManager::runAllTests()
	{
		const std::string empty;
		return runTestsWithFilter(empty, empty);
	}

	bool TestManager::runTestsWithFilter(const std::string & incl, const std::string & excl)
	{
		// Keep current assertion handler and setup ours
		setupAssertionHandler();
		setupLogCapturingHandler();

		// Prepare tags for filtering
		auto included_tags = detail::SplitString(incl, ' ');
		auto excluded_tags = detail::SplitString(excl, ' ');

		_test_log.clearLogData();

		logHeader("== " + _test_manager_name + " Unit Tests Log");

		if (included_tags.size() > 0 || excluded_tags.size() > 0) {
			if (included_tags.size()) {
				logMessage(detail::FormattedString(" * included tags : %s", incl.c_str()));
			}
			if (excluded_tags.size()) {
				logMessage(detail::FormattedString(" * excluded tags : %s", excl.c_str()));
			}
			logSeparator();
		}

		bool tests_result = true;
		double elapsed_time = 0.0;

		if (_registered_tests.size() > 0) {
			//
			PerformanceTimer timer;
			tests_result = executeFilteredTests(included_tags, excluded_tags);
			elapsed_time = timer.elapsedTime();
			//
		} else {
			//
			logMessage("WARNING: There's no registered test!");
			//
		}

		// Keep elapsed time & report results to log
		tl().setElapsedTime(elapsed_time);
		TestLogData::Counters log_data_counters = tl().logDataCounters();
		logHeader(detail::FormattedString("== RESULTS:  %d passed,  %d failed,  %d skipped,  time %s",
										  log_data_counters.passed_tests,
										  log_data_counters.failed_tests,
										  log_data_counters.skipped_tests,
										  PerformanceTimer::humanReadableTime(elapsed_time).c_str()));

		// Set previous assertion handler back
		restoreLogCapturingHandler();
		restoreAssertionHandler();
		return tests_result;
	}

	static std::string BuildFullTestDescription(UnitTestCreationInfo ti, size_t index, size_t count)
	{
		return detail::FormattedString("Test [ %d / %d ] ::: %s", (int)index + 1, (int)count, ti->name);
	}

	bool TestManager::executeFilteredTests(const std::vector<std::string> & included_tags, const std::vector<std::string> & excluded_tags)
	{
		bool final_result = true;

		bool include_all = included_tags.size() == 0;
		bool no_excludes = excluded_tags.size() == 0;

		size_t test_index = 0;
		for (auto ti : _registered_tests) {
			// Build text for headers
			std::string full_test_desc = BuildFullTestDescription(ti, test_index++, _registered_tests.size());
			//
			// apply test filter
			//
			bool should_run = false;
			if (no_excludes && include_all) {
				// no filter
				should_run = true;
			} else if (ti->tags) {
				// has tags, split test tags by space
				std::vector<std::string> test_tags = detail::SplitString(std::string(ti->tags), ' ');
				if (test_tags.size() > 0) {
					bool is_included = false;
					if (!include_all) {
						for (std::string incl : included_tags) {
							if (std::find(test_tags.begin(), test_tags.end(), incl) != test_tags.end()) {
								is_included = true;		// found tag from included vector
								break;
							}
						}
					} else {
						is_included = true;
					}
					bool is_excluded = false;
					for (std::string excl : excluded_tags) {
						if (std::find(test_tags.begin(), test_tags.end(), excl) != test_tags.end()) {
							is_excluded = true;		// found tag from excluded vector
							break;
						}
					}
					should_run = is_included && !is_excluded;

				} else {
					// test tags string has wrong format, assume that there's no tag at all
					should_run = include_all;
				}
			} else {
				// test has no tags, if included is not present, then ignore this test
				should_run = include_all;
			}
			if (should_run) {
				bool test_result = executeTest(ti, full_test_desc);
				if (test_result) {
					tl().addPassedTest();
				} else {
					tl().addFailedTest();
				}
				final_result = final_result && test_result;
			} else {
				std::string skipped = full_test_desc + " ::: SKIPPED";
				logMessage(skipped);
				tl().addSkippedTest();
			}
		}

		return final_result;
	}

	bool TestManager::executeTest(UnitTestCreationInfo ti, const std::string & full_test_desc)
	{
		bool test_result = false;

		detail::UnitTestFactoryFunction test_factory = ti->factory;
		UnitTest * unit_test = test_factory ? test_factory() : nullptr;

		if (unit_test != nullptr) {
			std::string begin_message = full_test_desc + " ::: START";
			logMessage(begin_message);

			// Set indentation and run test
			tl().setIndentationLevel(2);
			PerformanceTimer timer;
			double elapsed_time = 0.0;

			try {
				test_result = unit_test->runTest(this, &_test_log);
				elapsed_time = timer.elapsedTime();
			} catch (std::exception & exc) {
				std::string message("FAILED: Exception: ");
				message.append(exc.what());
				logMessage(message);
				test_result = false;
			} catch (...) {
				logMessage(std::string("FAILED: An unknown exception occured."));
				test_result = false;
			}

			// Clear indentation & dump result
			tl().setIndentationLevel(0);

			std::string end_message = full_test_desc;
			if (test_result) {
				end_message += " ::: OK ::: " + PerformanceTimer::humanReadableTime(elapsed_time);
			} else {
				end_message += " ::: FAILED";
			}
			logMessage(end_message);
			logSeparator();

			// destroy unit test object
			delete unit_test;
		} else {
			CC7_ASSERT(false, "Unable to create '%s'", full_test_desc.c_str());
		}

		return test_result;
	}

	// ------------------------------------------------------------------------------------
	// MARK: Logging

	void TestManager::setTestManagerName(const std::string &name)
	{
		_test_manager_name = name;
	}

	const std::string & TestManager::testManagerName() const
	{
		return _test_manager_name;
	}

	static const std::string s_normal_line("----------------------------------------------------------------------------");
	static const std::string s_header_line("============================================================================");
	static const size_t min_line = 12;

	void TestManager::logHeader(const std::string & message)
	{
		size_t indent = tl().indentationLevel();
		indent = std::min(indent, s_header_line.length() - min_line);
		const char * line_begin = s_header_line.c_str() + indent;
		tl().logFormattedMessage("%s\n%s\n%s", line_begin, message.c_str(), line_begin);
	}

	void TestManager::logMessage(const std::string & message)
	{
		tl().logMessage(message);
	}

	void TestManager::logSeparator()
	{
		size_t indent = tl().indentationLevel();
		indent = std::min(indent, s_normal_line.length() - min_line);
		const char * line_begin = s_normal_line.c_str() + indent;
		tl().logMessage(line_begin);
	}

	// Log capturing

	void TestManager::_LogHandler(void * handler_data, const char * message)
	{
		TestManager * manager = reinterpret_cast<TestManager*>(handler_data);
		if (manager && manager->_log_capturig_enabled) {
			std::string msg;
			size_t len = strlen(message);
			msg.reserve(len + 7);
			msg.assign("> CC7: ");
			msg.append(message, len);
			manager->tl().logMessage(msg);
		}
	}

	void TestManager::setupLogCapturingHandler()
	{
#ifdef ENABLE_CC7_LOG
		_old_log_setup = cc7::debug::GetLogHandler();
		cc7::debug::SetLogHandler({_LogHandler, this});
#endif
	}

	void TestManager::restoreLogCapturingHandler()
	{
#ifdef ENABLE_CC7_LOG
		cc7::debug::SetLogHandler(_old_log_setup);
		_old_log_setup = {nullptr, nullptr};
#endif
	}

	void TestManager::systemLog(const char * message)
	{
#ifdef ENABLE_CC7_LOG
		if (_log_capturig_enabled) {
			// Log capturing is enabled, we have to put message directly to the
			// previously used handler
			if (_old_log_setup.handler_data) {
				_old_log_setup.handler(_old_log_setup.handler_data, message);
			}
		} else {
			CC7_LOG("%s", message);
		}
#endif
	}

	// ------------------------------------------------------------------------------------
	// MARK: Private assertion handler

	void TestManager::_AssertionHandler(void * handler_data, const char * file, int line, const char * message)
	{
		TestManager * manager = reinterpret_cast<TestManager*>(handler_data);
		if (manager) {
			manager->tl().logMessage(message);
			manager->addAssertion(message);
		}
	}

	void TestManager::addAssertion(const char * message)
	{
		if (_assertion_breakpoint_enabled) {
			systemLog(message);
			CC7_BREAKPOINT();
		}
	}

	void TestManager::setupAssertionHandler()
	{
#ifdef ENABLE_CC7_ASSERT
		_old_assertion_setup = cc7::debug::GetAssertionHandler();
		cc7::debug::SetAssertionHandler({_AssertionHandler, this});
#endif
	}

	void TestManager::restoreAssertionHandler()
	{
#ifdef ENABLE_CC7_ASSERT
		cc7::debug::SetAssertionHandler(_old_assertion_setup);
		_old_assertion_setup = { nullptr, nullptr };
#endif
	}

}
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.ManagedElasticsearch.Clusters;
using Tests.Framework.MockData;
using Xunit;

namespace Tests.Search.Search
{
	public class InvalidSearchApiTests : SearchApiTests
	{
		public InvalidSearchApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { }

		protected override bool ExpectIsValid => false;

		protected override int ExpectStatusCode => 400;

		protected override object ExpectJson => new
		{
			from = 10,
			size = 20,
			aggs = new
			{
				startDates = new
				{
					date_range = new
					{
						ranges = new[]
						{
							new { from = "-1m" }
						}
					}
				}
			}
		};

		protected override Func<SearchDescriptor<Project>, ISearchRequest> Fluent => s => s
			.From(10)
			.Size(20)
			.Aggregations(a => a
				.DateRange("startDates", t => t
					.Ranges(ranges => ranges.From("-1m"))
				)
			);

		protected override SearchRequest<Project> Initializer => new SearchRequest<Project>()
		{
			From = 10,
			Size = 20,
			Aggregations = new DateRangeAggregation("startDates")
			{
				Ranges = new List<DateRangeExpression>
				{
					new DateRangeExpression { From = "-1m" }
				}
			}
		};

		protected override void ExpectResponse(ISearchResponse<Project> response)
		{
			response.IsValid.Should().BeFalse();
			var serverError = response.ServerError;
			serverError.Should().NotBeNull();
			serverError.Status.Should().Be(400);
			serverError.Error.Reason.Should().Be("all shards failed");
			serverError.Error.RootCause.First().Reason.Should().Contain("[-1m]");

		}
	}
}