text:
import React, { Children } from 'react'
import {
  applyChangeToValue,
  countSuggestions,
  escapeRegex,
  findStartOfMentionInPlainText,
  getEndOfLastMention,
  getMentions,
  getPlainText,
  getSubstringIndex,
  makeMentionsMarkup,
  mapPlainTextIndex,
  readConfigFromChildren,
  spliceString,
  isNumber,
  keys,
  omit,
  getSuggestionHtmlId,
} from './utils'

import Highlighter from './Highlighter'
import PropTypes from 'prop-types'
import ReactDOM from 'react-dom'
import SuggestionsOverlay from './SuggestionsOverlay'
import { defaultStyle } from './utils'

export const makeTriggerRegex = function(trigger, options = {}) {
  if (trigger instanceof RegExp) {
    return trigger
  } else {
    const { allowSpaceInQuery } = options
    const escapedTriggerChar = escapeRegex(trigger)

    // first capture group is the part to be replaced on completion
    // second capture group is for extracting the search query
    return new RegExp(
      `(?:^|\\s)(${escapedTriggerChar}([^${
        allowSpaceInQuery ? '' : '\\s'
      }${escapedTriggerChar}]*))$`
    )
  }
}

const getDataProvider = function(data, ignoreAccents) {
  if (data instanceof Array) {
    // if data is an array, create a function to query that
    return function(query, callback) {
      const results = []
      for (let i = 0, l = data.length; i < l; ++i) {
        const display = data[i].display || data[i].id
        if (getSubstringIndex(display, query, ignoreAccents) >= 0) {
          results.push(data[i])
        }
      }
      return results
    }
  } else {
    // expect data to be a query function
    return data
  }
}

const KEY = { TAB: 9, RETURN: 13, ESC: 27, UP: 38, DOWN: 40 }

let isComposing = false

const propTypes = {
  /**
   * If set to `true` a regular text input element will be rendered
   * instead of a textarea
   */
  singleLine: PropTypes.bool,
  allowSpaceInQuery: PropTypes.bool,
  allowSuggestionsAboveCursor: PropTypes.bool,
  forceSuggestionsAboveCursor: PropTypes.bool,
  ignoreAccents: PropTypes.bool,
  a11ySuggestionsListLabel: PropTypes.string,

  value: PropTypes.string,
  onKeyDown: PropTypes.func,
  onSelect: PropTypes.func,
  onBlur: PropTypes.func,
  onChange: PropTypes.func,
  suggestionsPortalHost:
    typeof Element === 'undefined'
      ? PropTypes.any
      : PropTypes.PropTypes.instanceOf(Element),
  inputRef: PropTypes.oneOfType([
    PropTypes.func,
    PropTypes.shape({
      current:
        typeof Element === 'undefined'
          ? PropTypes.any
          : PropTypes.instanceOf(Element),
    }),
  ]),

  children: PropTypes.oneOfType([
    PropTypes.element,
    PropTypes.arrayOf(PropTypes.element),
  ]).isRequired,
}

class MentionsInput extends React.Component {
  static propTypes = propTypes

  static defaultProps = {
    ignoreAccents: false,
    singleLine: false,
    allowSuggestionsAboveCursor: false,
    onKeyDown: () => null,
    onSelect: () => null,
    onBlur: () => null,
  }

  constructor(props) {
    super(props)
    this.suggestions = {}
    this.uuidSuggestionsOverlay = Math.random()
      .toString(16)
      .substring(2)

    this.handleCopy = this.handleCopy.bind(this)
    this.handleCut = this.handleCut.bind(this)
    this.handlePaste = this.handlePaste.bind(this)

    this.state = {
      focusIndex: 0,

      selectionStart: null,
      selectionEnd: null,

      suggestions: {},

      caretPosition: null,
      suggestionsPosition: {},
    }
  }

  componentDidMount() {
    document.addEventListener('copy', this.handleCopy)
    document.addEventListener('cut', this.handleCut)
    document.addEventListener('paste', this.handlePaste)

    this.updateSuggestionsPosition()
  }

  componentDidUpdate(prevProps, prevState) {
    // Update position of suggestions unless this componentDidUpdate was
    // triggered by an update to suggestionsPosition.
    if (prevState.suggestionsPosition === this.state.suggestionsPosition) {
      this.updateSuggestionsPosition()
    }

    // maintain selection in case a mention is added/removed causing
    // the cursor to jump to the end
    if (this.state.setSelectionAfterMentionChange) {
      this.setState({ setSelectionAfterMentionChange: false })
      this.setSelection(this.state.selectionStart, this.state.selectionEnd)
    }
  }

  componentWillUnmount() {
    document.removeEventListener('copy', this.handleCopy)
    document.removeEventListener('cut', this.handleCut)
    document.removeEventListener('paste', this.handlePaste)
  }

  render() {
    return (
      <div ref={this.setContainerElement} {...this.props.style}>
        {this.renderControl()}
        {this.renderSuggestionsOverlay()}
      </div>
    )
  }

  setContainerElement = (el) => {
    this.containerElement = el
  }

  getInputProps = () => {
    let { readOnly, disabled, style } = this.props

    // pass all props that neither we, nor substyle, consume through to the input control
    let props = omit(
      this.props,
      ['style', 'classNames', 'className'], // substyle props
      keys(propTypes)
    )

    return {
      ...props,
      ...style('input'),

      value: this.getPlainText(),

      ...(!readOnly &&
        !disabled && {
          onChange: this.handleChange,
          onSelect: this.handleSelect,
          onKeyDown: this.handleKeyDown,
          onBlur: this.handleBlur,
          onCompositionStart: this.handleCompositionStart,
          onCompositionEnd: this.handleCompositionEnd,
          onScroll: this.updateHighlighterScroll,
        }),

      ...(this.isOpened() && {
        role: 'combobox',
        'aria-controls': this.uuidSuggestionsOverlay,
        'aria-expanded': true,
        'aria-autocomplete': 'list',
        'aria-haspopup': 'listbox',
        'aria-activedescendant': getSuggestionHtmlId(
          this.uuidSuggestionsOverlay,
          this.state.focusIndex
        ),
      }),
    }
  }

  renderControl = () => {
    let { singleLine, style } = this.props
    let inputProps = this.getInputProps()

    return (
      <div {...style('control')}>
        {this.renderHighlighter()}
        {singleLine
          ? this.renderInput(inputProps)
          : this.renderTextarea(inputProps)}
      </div>
    )
  }

  renderInput = (props) => {
    return <input type="text" ref={this.setInputRef} {...props} />
  }

  renderTextarea = (props) => {
    return <textarea ref={this.setInputRef} {...props} />
  }

  setInputRef = (el) => {
    this.inputElement = el
    const { inputRef } = this.props
    if (typeof inputRef === 'function') {
      inputRef(el)
    } else if (inputRef) {
      inputRef.current = el
    }
  }

  setSuggestionsElement = (el) => {
    this.suggestionsElement = el
  }

  renderSuggestionsOverlay = () => {
    if (!isNumber(this.state.selectionStart)) {
      // do not show suggestions when the input does not have the focus
      return null
    }

    const { position, left, top } = this.state.suggestionsPosition

    const suggestionsNode = (
      <SuggestionsOverlay
        id={this.uuidSuggestionsOverlay}
        style={this.props.style('suggestions')}
        position={position}
        left={left}
        top={top}
        focusIndex={this.state.focusIndex}
        scrollFocusedIntoView={this.state.scrollFocusedIntoView}
        containerRef={this.setSuggestionsElement}
        suggestions={this.state.suggestions}
        onSelect={this.addMention}
        onMouseDown={this.handleSuggestionsMouseDown}
        onMouseEnter={this.handleSuggestionsMouseEnter}
        isLoading={this.isLoading()}
        isOpened={this.isOpened()}
        ignoreAccents={this.props.ignoreAccents}
        a11ySuggestionsListLabel={this.props.a11ySuggestionsListLabel}
      >
        {this.props.children}
      </SuggestionsOverlay>
    )
    if (this.props.suggestionsPortalHost) {
      return ReactDOM.createPortal(
        suggestionsNode,
        this.props.suggestionsPortalHost
      )
    } else {
      return suggestionsNode
    }
  }

  renderHighlighter = () => {
    const { selectionStart, selectionEnd } = this.state
    const { singleLine, children, value, style } = this.props

    return (
      <Highlighter
        containerRef={this.setHighlighterElement}
        style={style('highlighter')}
        value={value}
        singleLine={singleLine}
        selectionStart={selectionStart}
        selectionEnd={selectionEnd}
        onCaretPositionChange={this.handleCaretPositionChange}
      >
        {children}
      </Highlighter>
    )
  }

  setHighlighterElement = (el) => {
    this.highlighterElement = el
  }

  handleCaretPositionChange = (position) => {
    this.setState({ caretPosition: position })
  }

  // Returns the text to set as the value of the textarea with all markups removed
  getPlainText = () => {
    return getPlainText(
      this.props.value || '',
      readConfigFromChildren(this.props.children)
    )
  }

  executeOnChange = (event, ...args) => {
    if (this.props.onChange) {
      return this.props.onChange(event, ...args)
    }

    if (this.props.valueLink) {
      return this.props.valueLink.requestChange(event.target.value, ...args)
    }
  }

  handlePaste(event) {
    if (event.target !== this.inputElement) {
      return
    }
    if (!this.supportsClipboardActions(event)) {
      return
    }

    event.preventDefault()

    const { selectionStart, selectionEnd } = this.state
    const { value, children } = this.props

    const config = readConfigFromChildren(children)

    const markupStartIndex = mapPlainTextIndex(
      value,
      config,
      selectionStart,
      'START'
    )
    const markupEndIndex = mapPlainTextIndex(value, config, selectionEnd, 'END')

    const pastedMentions = event.clipboardData.getData('text/react-mentions')
    const pastedData = event.clipboardData.getData('text/plain')

    const newValue = spliceString(
      value,
      markupStartIndex,
      markupEndIndex,
      pastedMentions || pastedData
    ).replace(/\r/g, '')

    const newPlainTextValue = getPlainText(newValue, config)

    const eventMock = { target: { ...event.target, value: newValue } }

    this.executeOnChange(
      eventMock,
      newValue,
      newPlainTextValue,
      getMentions(newValue, config)
    )
  }

  saveSelectionToClipboard(event) {
    const { selectionStart, selectionEnd } = this.state
    const { children, value } = this.props

    const config = readConfigFromChildren(children)

    const markupStartIndex = mapPlainTextIndex(
      value,
      config,
      selectionStart,
      'START'
    )
    const markupEndIndex = mapPlainTextIndex(value, config, selectionEnd, 'END')

    event.clipboardData.setData(
      'text/plain',
      event.target.value.slice(selectionStart, selectionEnd)
    )
    event.clipboardData.setData(
      'text/react-mentions',
      value.slice(markupStartIndex, markupEndIndex)
    )
  }

  supportsClipboardActions(event) {
    return !!event.clipboardData
  }

  handleCopy(event) {
    if (event.target !== this.inputElement) {
      return
    }
    if (!this.supportsClipboardActions(event)) {
      return
    }

    event.preventDefault()

    this.saveSelectionToClipboard(event)
  }

  handleCut(event) {
    if (event.target !== this.inputElement) {
      return
    }
    if (!this.supportsClipboardActions(event)) {
      return
    }

    event.preventDefault()

    this.saveSelectionToClipboard(event)

    const { selectionStart, selectionEnd } = this.state
    const { children, value } = this.props

    const config = readConfigFromChildren(children)

    const markupStartIndex = mapPlainTextIndex(
      value,
      config,
      selectionStart,
      'START'
    )
    const markupEndIndex = mapPlainTextIndex(value, config, selectionEnd, 'END')

    const newValue = [
      value.slice(0, markupStartIndex),
      value.slice(markupEndIndex),
    ].join('')
    const newPlainTextValue = getPlainText(newValue, config)

    const eventMock = { target: { ...event.target, value: newPlainTextValue } }

    this.executeOnChange(
      eventMock,
      newValue,
      newPlainTextValue,
      getMentions(value, config)
    )
  }

  // Handle input element's change event
  handleChange = (ev) => {
    isComposing = false
    // if we are inside iframe, we need to find activeElement within its contentDocument
    const currentDocument =
      (document.activeElement && document.activeElement.contentDocument) ||
      document
    if (currentDocument.activeElement !== ev.target) {
      // fix an IE bug (blur from empty input element with placeholder attribute trigger "input" event)
      return
    }

    const value = this.props.value || ''
    const config = readConfigFromChildren(this.props.children)

    let newPlainTextValue = ev.target.value

    // Derive the new value to set by applying the local change in the textarea's plain text
    let newValue = applyChangeToValue(
      value,
      newPlainTextValue,
      {
        selectionStartBefore: this.state.selectionStart,
        selectionEndBefore: this.state.selectionEnd,
        selectionEndAfter: ev.target.selectionEnd,
      },
      config
    )

    // In case a mention is deleted, also adjust the new plain text value
    newPlainTextValue = getPlainText(newValue, config)

    // Save current selection after change to be able to restore caret position after rerendering
    let selectionStart = ev.target.selectionStart
    let selectionEnd = ev.target.selectionEnd
    let setSelectionAfterMentionChange = false

    // Adjust selection range in case a mention will be deleted by the characters outside of the
    // selection range that are automatically deleted
    let startOfMention = findStartOfMentionInPlainText(
      value,
      config,
      selectionStart
    )

    if (
      startOfMention !== undefined &&
      this.state.selectionEnd > startOfMention
    ) {
      // only if a deletion has taken place
      selectionStart = startOfMention
      selectionEnd = selectionStart
      setSelectionAfterMentionChange = true
    }

    this.setState({
      selectionStart,
      selectionEnd,
      setSelectionAfterMentionChange: setSelectionAfterMentionChange,
    })

    let mentions = getMentions(newValue, config)

    // Propagate change
    // let handleChange = this.getOnChange(this.props) || emptyFunction;
    let eventMock = { target: { value: newValue } }
    // this.props.onChange.call(this, eventMock, newValue, newPlainTextValue, mentions);
    this.executeOnChange(eventMock, newValue, newPlainTextValue, mentions)
  }

  // Handle input element's select event
  handleSelect = (ev) => {
    // keep track of selection range / caret position
    this.setState({
      selectionStart: ev.target.selectionStart,
      selectionEnd: ev.target.selectionEnd,
    })

    // do nothing while a IME composition session is active
    if (isComposing) return

    // refresh suggestions queries
    const el = this.inputElement
    if (ev.target.selectionStart === ev.target.selectionEnd) {
      this.updateMentionsQueries(el.value, ev.target.selectionStart)
    } else {
      this.clearSuggestions()
    }

    // sync highlighters scroll position
    this.updateHighlighterScroll()

    this.props.onSelect(ev)
  }

  handleKeyDown = (ev) => {
    // do not intercept key events if the suggestions overlay is not shown
    const suggestionsCount = countSuggestions(this.state.suggestions)

    if (suggestionsCount === 0 || !this.suggestionsElement) {
      this.props.onKeyDown(ev)

      return
    }

    if (Object.values(KEY).indexOf(ev.keyCode) >= 0) {
      ev.preventDefault()
      ev.stopPropagation()
    }

    switch (ev.keyCode) {
      case KEY.ESC: {
        this.clearSuggestions()
        return
      }
      case KEY.DOWN: {
        this.shiftFocus(+1)
        return
      }
      case KEY.UP: {
        this.shiftFocus(-1)
        return
      }
      case KEY.RETURN: {
        this.selectFocused()
        return
      }
      case KEY.TAB: {
        this.selectFocused()
        return
      }
      default: {
        return
      }
    }
  }

  shiftFocus = (delta) => {
    const suggestionsCount = countSuggestions(this.state.suggestions)

    this.setState({
      focusIndex:
        (suggestionsCount + this.state.focusIndex + delta) % suggestionsCount,
      scrollFocusedIntoView: true,
    })
  }

  selectFocused = () => {
    const { suggestions, focusIndex } = this.state

    const { result, queryInfo } = Object.values(suggestions).reduce(
      (acc, { results, queryInfo }) => [
        ...acc,
        ...results.map((result) => ({ result, queryInfo })),
      ],
      []
    )[focusIndex]

    this.addMention(result, queryInfo)

    this.setState({
      focusIndex: 0,
    })
  }

  handleBlur = (ev) => {
    const clickedSuggestion = this._suggestionsMouseDown
    this._suggestionsMouseDown = false

    // only reset selection if the mousedown happened on an element
    // other than the suggestions overlay
    if (!clickedSuggestion) {
      this.setState({
        selectionStart: null,
        selectionEnd: null,
      })
    }

    window.setTimeout(() => {
      this.updateHighlighterScroll()
    }, 1)

    this.props.onBlur(ev, clickedSuggestion)
  }

  handleSuggestionsMouseDown = (ev) => {
    this._suggestionsMouseDown = true
  }

  handleSuggestionsMouseEnter = (focusIndex) => {
    this.setState({
      focusIndex,
      scrollFocusedIntoView: false,
    })
  }

  updateSuggestionsPosition = () => {
    let { caretPosition } = this.state
    const { suggestionsPortalHost, allowSuggestionsAboveCursor, forceSuggestionsAboveCursor } = this.props

    if (!caretPosition || !this.suggestionsElement) {
      return
    }

    let suggestions = this.suggestionsElement
    let highlighter = this.highlighterElement
    // first get viewport-relative position (highlighter is offsetParent of caret):
    const caretOffsetParentRect = highlighter.getBoundingClientRect()
    const caretHeight = getComputedStyleLengthProp(highlighter, 'font-size')
    const viewportRelative = {
      left: caretOffsetParentRect.left + caretPosition.left,
      top: caretOffsetParentRect.top + caretPosition.top + caretHeight,
    }
    const viewportHeight = Math.max(
      document.documentElement.clientHeight,
      window.innerHeight || 0
    )

    if (!suggestions) {
      return
    }

    let position = {}

    // if suggestions menu is in a portal, update position to be releative to its portal node
    if (suggestionsPortalHost) {
      position.position = 'fixed'
      let left = viewportRelative.left
      let top = viewportRelative.top
      // absolute/fixed positioned elements are positioned according to their entire box including margins; so we remove margins here:
      left -= getComputedStyleLengthProp(suggestions, 'margin-left')
      top -= getComputedStyleLengthProp(suggestions, 'margin-top')
      // take into account highlighter/textinput scrolling:
      left -= highlighter.scrollLeft
      top -= highlighter.scrollTop
      // guard for mentions suggestions list clipped by right edge of window
      const viewportWidth = Math.max(
        document.documentElement.clientWidth,
        window.innerWidth || 0
      )
      if (left + suggestions.offsetWidth > viewportWidth) {
        position.left = Math.max(0, viewportWidth - suggestions.offsetWidth)
      } else {
        position.left = left
      }
      // guard for mentions suggestions list clipped by bottom edge of window if allowSuggestionsAboveCursor set to true.
      // Move the list up above the caret if it's getting cut off by the bottom of the window, provided that the list height
      // is small enough to NOT cover up the caret
      if (
        (allowSuggestionsAboveCursor &&
        top + suggestions.offsetHeight > viewportHeight &&
          suggestions.offsetHeight < top - caretHeight) ||
          forceSuggestionsAboveCursor
      ) {
        position.top = Math.max(0, top - suggestions.offsetHeight - caretHeight)
      } else {
        position.top = top
      }
    } else {
      let left = caretPosition.left - highlighter.scrollLeft
      let top = caretPosition.top - highlighter.scrollTop
      // guard for mentions suggestions list clipped by right edge of window
      if (left + suggestions.offsetWidth > this.containerElement.offsetWidth) {
        position.right = 0
      } else {
        position.left = left
      }
      // guard for mentions suggestions list clipped by bottom edge of window if allowSuggestionsAboveCursor set to true.
      // move the list up above the caret if it's getting cut off by the bottom of the window, provided that the list height
      // is small enough to NOT cover up the caret
      if (
        allowSuggestionsAboveCursor &&
        viewportRelative.top -
          highlighter.scrollTop +
          suggestions.offsetHeight >
          viewportHeight &&
        suggestions.offsetHeight <
          caretOffsetParentRect.top - caretHeight - highlighter.scrollTop
      ) {
        position.top = top - suggestions.offsetHeight - caretHeight
      } else {
        position.top = top
      }
    }

    if (
      position.left === this.state.suggestionsPosition.left &&
      position.top === this.state.suggestionsPosition.top &&
      position.position === this.state.suggestionsPosition.position
    ) {
      return
    }

    this.setState({
      suggestionsPosition: position,
    })
  }

  updateHighlighterScroll = () => {
    const input = this.inputElement
    const highlighter = this.highlighterElement
    if (!input || !highlighter) {
      // since the invocation of this function is deferred,
      // the whole component may have been unmounted in the meanwhile
      return
    }
    highlighter.scrollLeft = input.scrollLeft
    highlighter.scrollTop = input.scrollTop
    highlighter.height = input.height
  }

  handleCompositionStart = () => {
    isComposing = true
  }

  handleCompositionEnd = () => {
    isComposing = false
  }

  setSelection = (selectionStart, selectionEnd) => {
    if (selectionStart === null || selectionEnd === null) return

    const el = this.inputElement
    if (el.setSelectionRange) {
      el.setSelectionRange(selectionStart, selectionEnd)
    } else if (el.createTextRange) {
      const range = el.createTextRange()
      range.collapse(true)
      range.moveEnd('character', selectionEnd)
      range.moveStart('character', selectionStart)
      range.select()
    }
  }

  updateMentionsQueries = (plainTextValue, caretPosition) => {
    // Invalidate previous queries. Async results for previous queries will be neglected.
    this._queryId++
    this.suggestions = {}
    this.setState({
      suggestions: {},
    })

    const value = this.props.value || ''
    const { children } = this.props
    const config = readConfigFromChildren(children)

    const positionInValue = mapPlainTextIndex(
      value,
      config,
      caretPosition,
      'NULL'
    )

    // If caret is inside of mention, do not query
    if (positionInValue === null) {
      return
    }

    // Extract substring in between the end of the previous mention and the caret
    const substringStartIndex = getEndOfLastMention(
      value.substring(0, positionInValue),
      config
    )
    const substring = plainTextValue.substring(
      substringStartIndex,
      caretPosition
    )

    // Check if suggestions have to be shown:
    // Match the trigger patterns of all Mention children on the extracted substring
    React.Children.forEach(children, (child, childIndex) => {
      if (!child) {
        return
      }

      const regex = makeTriggerRegex(child.props.trigger, this.props)
      const match = substring.match(regex)
      if (match) {
        const querySequenceStart =
          substringStartIndex + substring.indexOf(match[1], match.index)
        this.queryData(
          match[2],
          childIndex,
          querySequenceStart,
          querySequenceStart + match[1].length,
          plainTextValue
        )
      }
    })
  }

  clearSuggestions = () => {
    // Invalidate previous queries. Async results for previous queries will be neglected.
    this._queryId++
    this.suggestions = {}
    this.setState({
      suggestions: {},
      focusIndex: 0,
    })
  }

  queryData = (
    query,
    childIndex,
    querySequenceStart,
    querySequenceEnd,
    plainTextValue
  ) => {
    const { children, ignoreAccents } = this.props
    const mentionChild = Children.toArray(children)[childIndex]
    const provideData = getDataProvider(mentionChild.props.data, ignoreAccents)
    const syncResult = provideData(
      query,
      this.updateSuggestions.bind(
        null,
        this._queryId,
        childIndex,
        query,
        querySequenceStart,
        querySequenceEnd,
        plainTextValue
      )
    )
    if (syncResult instanceof Array) {
      this.updateSuggestions(
        this._queryId,
        childIndex,
        query,
        querySequenceStart,
        querySequenceEnd,
        plainTextValue,
        syncResult
      )
    }
  }

  updateSuggestions = (
    queryId,
    childIndex,
    query,
    querySequenceStart,
    querySequenceEnd,
    plainTextValue,
    results
  ) => {
    // neglect async results from previous queries
    if (queryId !== this._queryId) return

    // save in property so that multiple sync state updates from different mentions sources
    // won't overwrite each other
    this.suggestions = {
      ...this.suggestions,
      [childIndex]: {
        queryInfo: {
          childIndex,
          query,
          querySequenceStart,
          querySequenceEnd,
          plainTextValue,
        },
        results,
      },
    }

    const { focusIndex } = this.state
    const suggestionsCount = countSuggestions(this.suggestions)
    this.setState({
      suggestions: this.suggestions,
      focusIndex:
        focusIndex >= suggestionsCount
          ? Math.max(suggestionsCount - 1, 0)
          : focusIndex,
    })
  }

  addMention = (
    { id, display },
    { childIndex, querySequenceStart, querySequenceEnd, plainTextValue }
  ) => {
    // Insert mention in the marked up value at the correct position
    const value = this.props.value || ''
    const config = readConfigFromChildren(this.props.children)
    const mentionsChild = Children.toArray(this.props.children)[childIndex]
    const {
      markup,
      displayTransform,
      appendSpaceOnAdd,
      onAdd,
    } = mentionsChild.props

    const start = mapPlainTextIndex(value, config, querySequenceStart, 'START')
    const end = start + querySequenceEnd - querySequenceStart
    let insert = makeMentionsMarkup(markup, id, display)
    if (appendSpaceOnAdd) {
      insert += ' '
    }
    const newValue = spliceString(value, start, end, insert)

    // Refocus input and set caret position to end of mention
    this.inputElement.focus()

    let displayValue = displayTransform(id, display)
    if (appendSpaceOnAdd) {
      displayValue += ' '
    }
    const newCaretPosition = querySequenceStart + displayValue.length
    this.setState({
      selectionStart: newCaretPosition,
      selectionEnd: newCaretPosition,
      setSelectionAfterMentionChange: true,
    })

    // Propagate change
    const eventMock = { target: { value: newValue } }
    const mentions = getMentions(newValue, config)
    const newPlainTextValue = spliceString(
      plainTextValue,
      querySequenceStart,
      querySequenceEnd,
      displayValue
    )

    this.executeOnChange(eventMock, newValue, newPlainTextValue, mentions)

    if (onAdd) {
      onAdd(id, display, start, end)
    }

    // Make sure the suggestions overlay is closed
    this.clearSuggestions()
  }

  isLoading = () => {
    let isLoading = false
    React.Children.forEach(this.props.children, function(child) {
      isLoading = isLoading || (child && child.props.isLoading)
    })
    return isLoading
  }

  isOpened = () =>
    isNumber(this.state.selectionStart) &&
    (countSuggestions(this.state.suggestions) !== 0 || this.isLoading())

  _queryId = 0
}

/**
 * Returns the computed length property value for the provided element.
 * Note: According to spec and testing, can count on length values coming back in pixels. See https://developer.mozilla.org/en-US/docs/Web/CSS/used_value#Difference_from_computed_value
 */
const getComputedStyleLengthProp = (forElement, propertyName) => {
  const length = parseFloat(
    window.getComputedStyle(forElement, null).getPropertyValue(propertyName)
  )
  return isFinite(length) ? length : 0
}

const isMobileSafari =
  typeof navigator !== 'undefined' &&
  /iPhone|iPad|iPod/i.test(navigator.userAgent)

const styled = defaultStyle(
  {
    position: 'relative',
    overflowY: 'visible',

    input: {
      display: 'block',
      width: '100%',
      position: 'absolute',
      margin: 0,
      top: 0,
      left: 0,
      boxSizing: 'border-box',
      backgroundColor: 'transparent',
      fontFamily: 'inherit',
      fontSize: 'inherit',
      letterSpacing: 'inherit',
    },

    '&multiLine': {
      input: {
        height: '100%',
        bottom: 0,
        overflow: 'hidden',
        resize: 'none',

        // fix weird textarea padding in mobile Safari (see: http://stackoverflow.com/questions/6890149/remove-3-pixels-in-ios-webkit-textarea)
        ...(isMobileSafari
          ? {
              marginTop: 1,
              marginLeft: -3,
            }
          : null),
      },
    },
  },
  ({ singleLine }) => ({
    '&singleLine': singleLine,
    '&multiLine': !singleLine,
  })
)

export default styled(MentionsInput)


text:
// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2011 - 2018)
//   René Fritze     (2014, 2016, 2018)
//   René Milk       (2017)
//   Tobias Leibner  (2014, 2016 - 2017)

#ifndef DUNE_GDT_LOCAL_DISCRETEFUNCTION_HH
#define DUNE_GDT_LOCAL_DISCRETEFUNCTION_HH

#include <dune/xt/la/container/vector-interface.hh>
#include <dune/xt/grid/type_traits.hh>
#include <dune/xt/functions/interfaces/grid-function.hh>

#include <dune/gdt/discretefunction/dof-vector.hh>
#include <dune/gdt/exceptions.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {

template <class Vector, class GridView, size_t range_dim = 1, size_t range_dim_cols = 1, class RangeField = double>
class ConstLocalDiscreteFunction
  : public XT::Functions::
        ElementFunctionInterface<XT::Grid::extract_entity_t<GridView>, range_dim, range_dim_cols, RangeField>
{
  // No need to check the rest, is done in SpaceInterface.
  static_assert(XT::LA::is_vector<Vector>::value, "");
  static_assert(range_dim_cols == 1, "The matrix-valued case requires updates to evaluate/jacobian/derivative!");

  using ThisType = ConstLocalDiscreteFunction;
  using BaseType = XT::Functions::
      ElementFunctionInterface<XT::Grid::extract_entity_t<GridView>, range_dim, range_dim_cols, RangeField>;

public:
  using SpaceType = SpaceInterface<GridView, range_dim, range_dim_cols, RangeField>;
  using ConstDofVectorType = ConstDofVector<Vector, GridView>;
  using ConstLocalDofVectorType = typename ConstDofVectorType::ConstLocalDofVectorType;
  using LocalBasisType = typename SpaceType::GlobalBasisType::LocalizedType;

  using BaseType::d;
  using BaseType::r;
  using BaseType::rC;
  using typename BaseType::DerivativeRangeReturnType;
  using typename BaseType::DerivativeRangeSelector;
  using typename BaseType::DerivativeRangeType;
  using typename BaseType::DomainType;
  using typename BaseType::DynamicDerivativeRangeType;
  using typename BaseType::DynamicRangeType;
  using typename BaseType::ElementType;
  using typename BaseType::R;
  using typename BaseType::RangeReturnType;
  using typename BaseType::RangeSelector;
  using typename BaseType::RangeType;
  using typename BaseType::SingleDerivativeRangeReturnType;
  using typename BaseType::SingleDerivativeRangeType;

  ConstLocalDiscreteFunction(const SpaceType& spc, const ConstDofVectorType& dof_vector)
    : BaseType()
    , space_(spc.copy())
    , space_is_fv_(space_->type() == GDT::SpaceType::finite_volume)
    , dof_vector_(dof_vector.localize())
    , basis_(space_->basis().localize())
    , basis_values_(space_is_fv_ ? 0 : space_->mapper().max_local_size())
    , dynamic_basis_values_(basis_values_.size())
    , basis_derivatives_(basis_values_.size())
    , dynamic_basis_derivatives_(basis_values_.size())
  {}

  virtual ~ConstLocalDiscreteFunction() = default;

protected:
  void post_bind(const ElementType& ent) override
  {
    basis_->bind(ent);
    basis_size_ = basis_->size();
    dof_vector_.bind(ent);
  }

public:
  int order(const XT::Common::Parameter& /*param*/ = {}) const override final
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    return basis_->order();
  }

  const SpaceType& space() const
  {
    return *space_;
  }

  const LocalBasisType& basis() const
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    return *basis_;
  }

  const ConstLocalDofVectorType& dofs() const
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    return dof_vector_;
  }

  using BaseType::derivative;
  using BaseType::evaluate;
  using BaseType::jacobian;

  /**
   * \name ``These methods are required by XT::Functions::GridFunctionInterface.''
   * \{
   **/

  RangeReturnType evaluate(const DomainType& point_in_reference_element,
                           const XT::Common::Parameter& param = {}) const override final
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    RangeReturnType result(0);
    if (space_is_fv_) {
      for (size_t ii = 0; ii < r; ++ii)
        result[ii] = dof_vector_[ii];
    } else {
      basis_->evaluate(point_in_reference_element, basis_values_, param);
      for (size_t ii = 0; ii < basis_size_; ++ii)
        result.axpy(dof_vector_[ii], basis_values_[ii]);
    }
    return result;
  } // ... evaluate(...)

  DerivativeRangeReturnType jacobian(const DomainType& point_in_reference_element,
                                     const XT::Common::Parameter& param = {}) const override final
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    DerivativeRangeReturnType result(0);
    if (space_is_fv_) {
      return result;
    } else {
      basis_->jacobians(point_in_reference_element, basis_derivatives_, param);
      for (size_t ii = 0; ii < basis_size_; ++ii)
        result.axpy(dof_vector_[ii], basis_derivatives_[ii]);
    }
    return result;
  } // ... jacobian(...)

  DerivativeRangeReturnType derivative(const std::array<size_t, d>& alpha,
                                       const DomainType& point_in_reference_element,
                                       const XT::Common::Parameter& /*param*/ = {}) const override final
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    DUNE_THROW_IF(space_is_fv_,
                  Exceptions::discrete_function_error,
                  "arbitrary derivatives are not supported by the local finite elements!\n\n"
                      << "alpha = " << alpha << "\n"
                      << "point_in_reference_element = " << point_in_reference_element);
    DerivativeRangeReturnType result(0);
    for (size_t jj = 0; jj < d; ++jj) {
      if (alpha[jj] == 0) {
        for (size_t ii = 0; ii < r; ++ii)
          result[ii][jj] = dof_vector_[ii];
      } else
        DUNE_THROW(Exceptions::discrete_function_error,
                   "arbitrary derivatives are not supported by the local finite elements!\n\n"
                       << "alpha = " << alpha << "\n"
                       << "point_in_reference_element = " << point_in_reference_element);
    }
    return result;
  } // ... derivative(...)

  /**
   * \}
   * \name ``These methods are default implemented in XT::Functions::GridFunctionInterface and are overridden
   *         for improved performance.''
   * \{
   **/

  void evaluate(const DomainType& point_in_reference_element,
                DynamicRangeType& result,
                const XT::Common::Parameter& param = {}) const override final
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    RangeSelector::ensure_size(result);
    if (space_is_fv_) {
      for (size_t ii = 0; ii < r; ++ii)
        result[ii] = dof_vector_[ii];
    } else {
      result *= 0;
      basis_->evaluate(point_in_reference_element, dynamic_basis_values_, param);
      for (size_t ii = 0; ii < basis_size_; ++ii)
        result.axpy(dof_vector_[ii], dynamic_basis_values_[ii]);
    }
  } // ... evaluate(...)

  void jacobian(const DomainType& point_in_reference_element,
                DynamicDerivativeRangeType& result,
                const XT::Common::Parameter& param = {}) const override final
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    DerivativeRangeSelector::ensure_size(result);
    result *= 0;
    if (space_is_fv_) {
      return;
    } else {
      basis_->jacobians(point_in_reference_element, dynamic_basis_derivatives_, param);
      for (size_t ii = 0; ii < basis_size_; ++ii)
        result.axpy(dof_vector_[ii], dynamic_basis_derivatives_[ii]);
    }
  } // ... jacobian(...)

  void derivative(const std::array<size_t, d>& alpha,
                  const DomainType& point_in_reference_element,
                  DynamicDerivativeRangeType& result,
                  const XT::Common::Parameter& /*param*/ = {}) const override final
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    DUNE_THROW_IF(space_is_fv_,
                  Exceptions::discrete_function_error,
                  "arbitrary derivatives are not supported by the local finite elements!\n\n"
                      << "alpha = " << alpha << "\n"
                      << "point_in_reference_element = " << point_in_reference_element);
    DerivativeRangeSelector::ensure_size(result);
    result *= 0;
    for (size_t jj = 0; jj < d; ++jj) {
      if (alpha[jj] == 0) {
        for (size_t ii = 0; ii < r; ++ii)
          result[ii][jj] = dof_vector_[ii];
      } else
        DUNE_THROW(Exceptions::discrete_function_error,
                   "arbitrary derivatives are not supported by the local finite elements!\n\n"
                       << "alpha = " << alpha << "\n"
                       << "point_in_reference_element = " << point_in_reference_element);
    }
  } // ... derivative(...)

  /**
   * \}
   * \name ``These methods (used to access an individual range dimension) are default implemented in
   *         XT::Functions::GridFunctionInterface and are implemented for improved performance.''
   * \{
   **/

  R evaluate(const DomainType& point_in_reference_element,
             const size_t row,
             const size_t col = 0,
             const XT::Common::Parameter& param = {}) const override final
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    this->assert_correct_dims(row, col, "evaluate");
    if (space_is_fv_) {
      return dof_vector_[row];
    } else {
      R result(0);
      basis_->evaluate(point_in_reference_element, basis_values_, param);
      for (size_t ii = 0; ii < basis_size_; ++ii)
        result += dof_vector_[ii] * basis_values_[ii][row];
      return result;
    }
  } // ... evaluate(...)

  SingleDerivativeRangeReturnType jacobian(const DomainType& point_in_reference_element,
                                           const size_t row,
                                           const size_t col = 0,
                                           const XT::Common::Parameter& param = {}) const override final
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    this->assert_correct_dims(row, col, "jacobian");
    if (space_is_fv_) {
      return 0;
    } else {
      SingleDerivativeRangeReturnType result(0);
      basis_->jacobians(point_in_reference_element, basis_derivatives_, param);
      for (size_t ii = 0; ii < basis_size_; ++ii)
        result.axpy(dof_vector_[ii], basis_derivatives_[ii][row]);
      return result;
    }
  } // ... jacobian(...)

  /// \}

private:
  std::unique_ptr<const SpaceType> space_;
  const bool space_is_fv_;
  ConstLocalDofVectorType dof_vector_;
  std::unique_ptr<LocalBasisType> basis_;
  mutable size_t basis_size_;
  mutable std::vector<RangeType> basis_values_;
  mutable std::vector<DynamicRangeType> dynamic_basis_values_;
  mutable std::vector<DerivativeRangeType> basis_derivatives_;
  mutable std::vector<DynamicDerivativeRangeType> dynamic_basis_derivatives_;
}; // class ConstLocalDiscreteFunction

template <class V, class GV, size_t r = 1, size_t rC = 1, class R = double>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<V, GV, r, rC, R>
{
  using ThisType = LocalDiscreteFunction;
  using BaseType = ConstLocalDiscreteFunction<V, GV, r, rC, R>;

public:
  using typename BaseType::ElementType;
  using typename BaseType::SpaceType;

  using DofVectorType = DofVector<V, GV>;
  using LocalDofVectorType = typename DofVectorType::LocalDofVectorType;

  LocalDiscreteFunction(const SpaceType& spc, DofVectorType& dof_vector)
    : BaseType(spc, dof_vector)
    , dof_vector_(dof_vector.localize())
  {}

  LocalDiscreteFunction(const SpaceType& spc, DofVectorType& dof_vector, const ElementType& ent)
    : BaseType(spc, dof_vector, ent)
    , dof_vector_(dof_vector.localize(ent))
  {}

protected:
  void post_bind(const ElementType& ent) override final
  {
    BaseType::post_bind(ent);
    dof_vector_.bind(ent);
  }

public:
  LocalDofVectorType& dofs()
  {
    DUNE_THROW_IF(!this->is_bound_, Exceptions::not_bound_to_an_element_yet, "");
    return dof_vector_;
  }

private:
  LocalDofVectorType dof_vector_;
}; // class LocalDiscreteFunction

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_LOCAL_DISCRETEFUNCTION_HH

redpajama_set_name: RedPajamaGithub


text:
<project name="iwant" default="wish" basedir="">

	<property name="as-someone" location="../../.." />
	<property name="entry-src" location="${as-someone}/with/java" />

	<target name="wish" depends="entry-classes, empty-wish, nonempty-wish" />

	<target name="empty-wish" unless="wish">
		<echo message="Try again with -Dwish=list-of/targets" />
	</target>

	<target name="nonempty-wish" if="wish">
		<iwant>
			<wish>
				<arg value="${wish}" />
			</wish>
		</iwant>
	</target>

	<macrodef name="iwant">
		<element name="wish" />
		<sequential>
			<fail unless="entry-classes" />
			<fail unless="as-someone" />
			<java classpath="${entry-classes}" classname="org.fluentjava.iwant.entry.Iwant" failonerror="true" fork="true">
				<jvmarg value="-Xmx3G" />
				<arg file="${as-someone}" />
				<wish />
			</java>
		</sequential>
	</macrodef>

	<target name="entry-classes">
		<property name="entry-classes" location="${as-someone}/.i-cached/entry-classes" />
		<mkdir dir="${entry-classes}" />
		<javac debug="true" destdir="${entry-classes}" encoding="UTF-8" includeantruntime="false" source="11" srcdir="${entry-src}" />
	</target>

</project>


text:
@interface OrgApacheLuceneSearchBlendedTermQuery () {
 @public
  IOSObjectArray *terms_;
  IOSFloatArray *boosts_;
  IOSObjectArray *contexts_;
  OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *rewriteMethod_;
}

- (instancetype)initWithOrgApacheLuceneIndexTermArray:(IOSObjectArray *)terms
                                       withFloatArray:(IOSFloatArray *)boosts
             withOrgApacheLuceneIndexTermContextArray:(IOSObjectArray *)contexts
withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod:(OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *)rewriteMethod;

+ (OrgApacheLuceneIndexTermContext *)adjustFrequenciesWithOrgApacheLuceneIndexTermContext:(OrgApacheLuceneIndexTermContext *)ctx
                                                                                withInt:(jint)artificialDf
                                                                                withLong:(jlong)artificialTtf;

@end

J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchBlendedTermQuery, terms_, IOSObjectArray *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchBlendedTermQuery, boosts_, IOSFloatArray *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchBlendedTermQuery, contexts_, IOSObjectArray *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchBlendedTermQuery, rewriteMethod_, OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *)

__attribute__((unused)) static void OrgApacheLuceneSearchBlendedTermQuery_initWithOrgApacheLuceneIndexTermArray_withFloatArray_withOrgApacheLuceneIndexTermContextArray_withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_(OrgApacheLuceneSearchBlendedTermQuery *self, IOSObjectArray *terms, IOSFloatArray *boosts, IOSObjectArray *contexts, OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *rewriteMethod);

__attribute__((unused)) static OrgApacheLuceneSearchBlendedTermQuery *new_OrgApacheLuceneSearchBlendedTermQuery_initWithOrgApacheLuceneIndexTermArray_withFloatArray_withOrgApacheLuceneIndexTermContextArray_withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_(IOSObjectArray *terms, IOSFloatArray *boosts, IOSObjectArray *contexts, OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *rewriteMethod) NS_RETURNS_RETAINED;

__attribute__((unused)) static OrgApacheLuceneSearchBlendedTermQuery *create_OrgApacheLuceneSearchBlendedTermQuery_initWithOrgApacheLuceneIndexTermArray_withFloatArray_withOrgApacheLuceneIndexTermContextArray_withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_(IOSObjectArray *terms, IOSFloatArray *boosts, IOSObjectArray *contexts, OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *rewriteMethod);

__attribute__((unused)) static OrgApacheLuceneIndexTermContext *OrgApacheLuceneSearchBlendedTermQuery_adjustFrequenciesWithOrgApacheLuceneIndexTermContext_withInt_withLong_(OrgApacheLuceneIndexTermContext *ctx, jint artificialDf, jlong artificialTtf);

@interface OrgApacheLuceneSearchBlendedTermQuery_Builder () {
 @public
  jint numTerms_;
  IOSObjectArray *terms_;
  IOSFloatArray *boosts_;
  IOSObjectArray *contexts_;
  OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *rewriteMethod_;
}

@end

J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchBlendedTermQuery_Builder, terms_, IOSObjectArray *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchBlendedTermQuery_Builder, boosts_, IOSFloatArray *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchBlendedTermQuery_Builder, contexts_, IOSObjectArray *)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchBlendedTermQuery_Builder, rewriteMethod_, OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *)

@interface OrgApacheLuceneSearchBlendedTermQuery_1 : OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod

- (instancetype)init;

- (OrgApacheLuceneSearchQuery *)rewriteWithOrgApacheLuceneSearchQueryArray:(IOSObjectArray *)subQueries;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneSearchBlendedTermQuery_1)

__attribute__((unused)) static void OrgApacheLuceneSearchBlendedTermQuery_1_init(OrgApacheLuceneSearchBlendedTermQuery_1 *self);

__attribute__((unused)) static OrgApacheLuceneSearchBlendedTermQuery_1 *new_OrgApacheLuceneSearchBlendedTermQuery_1_init(void) NS_RETURNS_RETAINED;

__attribute__((unused)) static OrgApacheLuceneSearchBlendedTermQuery_1 *create_OrgApacheLuceneSearchBlendedTermQuery_1_init(void);

@interface OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite () {
 @public
  jfloat tieBreakerMultiplier_;
}

@end

@interface OrgApacheLuceneSearchBlendedTermQuery_2 : OrgApacheLuceneUtilInPlaceMergeSorter {
 @public
  IOSObjectArray *val$terms_;
  IOSObjectArray *val$contexts_;
  IOSFloatArray *val$boosts_;
}

- (instancetype)initWithOrgApacheLuceneIndexTermArray:(IOSObjectArray *)capture$0
             withOrgApacheLuceneIndexTermContextArray:(IOSObjectArray *)capture$1
                                       withFloatArray:(IOSFloatArray *)capture$2;

- (void)swapWithInt:(jint)i
            withInt:(jint)j;

- (jint)compareWithInt:(jint)i
               withInt:(jint)j;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneSearchBlendedTermQuery_2)

__attribute__((unused)) static void OrgApacheLuceneSearchBlendedTermQuery_2_initWithOrgApacheLuceneIndexTermArray_withOrgApacheLuceneIndexTermContextArray_withFloatArray_(OrgApacheLuceneSearchBlendedTermQuery_2 *self, IOSObjectArray *capture$0, IOSObjectArray *capture$1, IOSFloatArray *capture$2);

__attribute__((unused)) static OrgApacheLuceneSearchBlendedTermQuery_2 *new_OrgApacheLuceneSearchBlendedTermQuery_2_initWithOrgApacheLuceneIndexTermArray_withOrgApacheLuceneIndexTermContextArray_withFloatArray_(IOSObjectArray *capture$0, IOSObjectArray *capture$1, IOSFloatArray *capture$2) NS_RETURNS_RETAINED;

__attribute__((unused)) static OrgApacheLuceneSearchBlendedTermQuery_2 *create_OrgApacheLuceneSearchBlendedTermQuery_2_initWithOrgApacheLuceneIndexTermArray_withOrgApacheLuceneIndexTermContextArray_withFloatArray_(IOSObjectArray *capture$0, IOSObjectArray *capture$1, IOSFloatArray *capture$2);

J2OBJC_INITIALIZED_DEFN(OrgApacheLuceneSearchBlendedTermQuery)

OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *OrgApacheLuceneSearchBlendedTermQuery_BOOLEAN_REWRITE;
OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *OrgApacheLuceneSearchBlendedTermQuery_DISJUNCTION_MAX_REWRITE;

@implementation OrgApacheLuceneSearchBlendedTermQuery

+ (OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *)BOOLEAN_REWRITE {
  return OrgApacheLuceneSearchBlendedTermQuery_BOOLEAN_REWRITE;
}

+ (OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *)DISJUNCTION_MAX_REWRITE {
  return OrgApacheLuceneSearchBlendedTermQuery_DISJUNCTION_MAX_REWRITE;
}

- (instancetype)initWithOrgApacheLuceneIndexTermArray:(IOSObjectArray *)terms
                                       withFloatArray:(IOSFloatArray *)boosts
             withOrgApacheLuceneIndexTermContextArray:(IOSObjectArray *)contexts
withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod:(OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *)rewriteMethod {
  OrgApacheLuceneSearchBlendedTermQuery_initWithOrgApacheLuceneIndexTermArray_withFloatArray_withOrgApacheLuceneIndexTermContextArray_withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_(self, terms, boosts, contexts, rewriteMethod);
  return self;
}

- (jboolean)isEqual:(id)obj {
  if ([super isEqual:obj] == false) {
    return false;
  }
  OrgApacheLuceneSearchBlendedTermQuery *that = (OrgApacheLuceneSearchBlendedTermQuery *) cast_chk(obj, [OrgApacheLuceneSearchBlendedTermQuery class]);
  return JavaUtilArrays_equalsWithNSObjectArray_withNSObjectArray_(terms_, ((OrgApacheLuceneSearchBlendedTermQuery *) nil_chk(that))->terms_) && JavaUtilArrays_equalsWithNSObjectArray_withNSObjectArray_(contexts_, that->contexts_) && JavaUtilArrays_equalsWithFloatArray_withFloatArray_(boosts_, that->boosts_) && [((OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *) nil_chk(rewriteMethod_)) isEqual:that->rewriteMethod_];
}

- (NSUInteger)hash {
  jint h = ((jint) [super hash]);
  h = 31 * h + JavaUtilArrays_hashCodeWithNSObjectArray_(terms_);
  h = 31 * h + JavaUtilArrays_hashCodeWithNSObjectArray_(contexts_);
  h = 31 * h + JavaUtilArrays_hashCodeWithFloatArray_(boosts_);
  h = 31 * h + ((jint) [((OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *) nil_chk(rewriteMethod_)) hash]);
  return h;
}

- (NSString *)toStringWithNSString:(NSString *)field {
  JavaLangStringBuilder *builder = create_JavaLangStringBuilder_initWithNSString_(@"Blended(");
  for (jint i = 0; i < ((IOSObjectArray *) nil_chk(terms_))->size_; ++i) {
    if (i != 0) {
      [builder appendWithNSString:@" "];
    }
    OrgApacheLuceneSearchTermQuery *termQuery = create_OrgApacheLuceneSearchTermQuery_initWithOrgApacheLuceneIndexTerm_(IOSObjectArray_Get(terms_, i));
    [termQuery setBoostWithFloat:IOSFloatArray_Get(nil_chk(boosts_), i)];
    [builder appendWithNSString:[termQuery toStringWithNSString:field]];
  }
  [builder appendWithNSString:@")"];
  return [builder description];
}

- (OrgApacheLuceneSearchQuery *)rewriteWithOrgApacheLuceneIndexIndexReader:(OrgApacheLuceneIndexIndexReader *)reader {
  IOSObjectArray *contexts = JavaUtilArrays_copyOfWithNSObjectArray_withInt_(self->contexts_, ((IOSObjectArray *) nil_chk(self->contexts_))->size_);
  for (jint i = 0; i < ((IOSObjectArray *) nil_chk(contexts))->size_; ++i) {
    if (IOSObjectArray_Get(contexts, i) == nil || !JreObjectEqualsEquals(((OrgApacheLuceneIndexTermContext *) nil_chk(IOSObjectArray_Get(contexts, i)))->topReaderContext_, [((OrgApacheLuceneIndexIndexReader *) nil_chk(reader)) getContext])) {
      IOSObjectArray_Set(contexts, i, OrgApacheLuceneIndexTermContext_buildWithOrgApacheLuceneIndexIndexReaderContext_withOrgApacheLuceneIndexTerm_([((OrgApacheLuceneIndexIndexReader *) nil_chk(reader)) getContext], IOSObjectArray_Get(nil_chk(terms_), i)));
    }
  }
  jint df = 0;
  jlong ttf = 0;
  {
    IOSObjectArray *a__ = contexts;
    OrgApacheLuceneIndexTermContext * const *b__ = a__->buffer_;
    OrgApacheLuceneIndexTermContext * const *e__ = b__ + a__->size_;
    while (b__ < e__) {
      OrgApacheLuceneIndexTermContext *ctx = *b__++;
      df = JavaLangMath_maxWithInt_withInt_(df, [((OrgApacheLuceneIndexTermContext *) nil_chk(ctx)) docFreq]);
      if ([ctx totalTermFreq] == -1LL) {
        ttf = -1LL;
      }
      else if (ttf != -1LL) {
        ttf += [ctx totalTermFreq];
      }
    }
  }
  for (jint i = 0; i < contexts->size_; ++i) {
    IOSObjectArray_Set(contexts, i, OrgApacheLuceneSearchBlendedTermQuery_adjustFrequenciesWithOrgApacheLuceneIndexTermContext_withInt_withLong_(IOSObjectArray_Get(contexts, i), df, ttf));
  }
  IOSObjectArray *termQueries = [IOSObjectArray arrayWithLength:((IOSObjectArray *) nil_chk(terms_))->size_ type:OrgApacheLuceneSearchTermQuery_class_()];
  for (jint i = 0; i < terms_->size_; ++i) {
    IOSObjectArray_SetAndConsume(termQueries, i, new_OrgApacheLuceneSearchTermQuery_initWithOrgApacheLuceneIndexTerm_withOrgApacheLuceneIndexTermContext_(IOSObjectArray_Get(terms_, i), IOSObjectArray_Get(contexts, i)));
    [((OrgApacheLuceneSearchTermQuery *) nil_chk(IOSObjectArray_Get(termQueries, i))) setBoostWithFloat:IOSFloatArray_Get(nil_chk(boosts_), i)];
  }
  OrgApacheLuceneSearchQuery *rewritten = JreRetainedLocalValue([((OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *) nil_chk(rewriteMethod_)) rewriteWithOrgApacheLuceneSearchQueryArray:termQueries]);
  [((OrgApacheLuceneSearchQuery *) nil_chk(rewritten)) setBoostWithFloat:[self getBoost]];
  return rewritten;
}

+ (OrgApacheLuceneIndexTermContext *)adjustFrequenciesWithOrgApacheLuceneIndexTermContext:(OrgApacheLuceneIndexTermContext *)ctx
                                                                                withInt:(jint)artificialDf
                                                                                withLong:(jlong)artificialTtf {
  return OrgApacheLuceneSearchBlendedTermQuery_adjustFrequenciesWithOrgApacheLuceneIndexTermContext_withInt_withLong_(ctx, artificialDf, artificialTtf);
}

- (void)dealloc {
  RELEASE_(terms_);
  RELEASE_(boosts_);
  RELEASE_(contexts_);
  RELEASE_(rewriteMethod_);
  [super dealloc];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x2, -1, 0, -1, -1, -1, -1 },
    { NULL, "Z", 0x1, 1, 2, -1, -1, -1, -1 },
    { NULL, "I", 0x1, 3, -1, -1, -1, -1, -1 },
    { NULL, "LNSString;", 0x1, 4, 5, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneSearchQuery;", 0x11, 6, 7, 8, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneIndexTermContext;", 0xa, 9, 10, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(initWithOrgApacheLuceneIndexTermArray:withFloatArray:withOrgApacheLuceneIndexTermContextArray:withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod:);
  methods[1].selector = @selector(isEqual:);
  methods[2].selector = @selector(hash);
  methods[3].selector = @selector(toStringWithNSString:);
  methods[4].selector = @selector(rewriteWithOrgApacheLuceneIndexIndexReader:);
  methods[5].selector = @selector(adjustFrequenciesWithOrgApacheLuceneIndexTermContext:withInt:withLong:);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "BOOLEAN_REWRITE", "LOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod;", .constantValue.asLong = 0, 0x19, -1, 11, -1, -1 },
    { "DISJUNCTION_MAX_REWRITE", "LOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod;", .constantValue.asLong = 0, 0x19, -1, 12, -1, -1 },
    { "terms_", "[LOrgApacheLuceneIndexTerm;", .constantValue.asLong = 0, 0x12, -1, -1, -1, -1 },
    { "boosts_", "[F", .constantValue.asLong = 0, 0x12, -1, -1, -1, -1 },
    { "contexts_", "[LOrgApacheLuceneIndexTermContext;", .constantValue.asLong = 0, 0x12, -1, -1, -1, -1 },
    { "rewriteMethod_", "LOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod;", .constantValue.asLong = 0, 0x12, -1, -1, -1, -1 },
  };
  static const void *ptrTable[] = { "[LOrgApacheLuceneIndexTerm;[F[LOrgApacheLuceneIndexTermContext;LOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod;", "equals", "LNSObject;", "hashCode", "toString", "LNSString;", "rewrite", "LOrgApacheLuceneIndexIndexReader;", "LJavaIoIOException;", "adjustFrequencies", "LOrgApacheLuceneIndexTermContext;IJ", &OrgApacheLuceneSearchBlendedTermQuery_BOOLEAN_REWRITE, &OrgApacheLuceneSearchBlendedTermQuery_DISJUNCTION_MAX_REWRITE, "LOrgApacheLuceneSearchBlendedTermQuery_Builder;LOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod;LOrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite;" };
  static const J2ObjcClassInfo _OrgApacheLuceneSearchBlendedTermQuery = { "BlendedTermQuery", "org.apache.lucene.search", ptrTable, methods, fields, 7, 0x11, 6, 6, -1, 13, -1, -1, -1 };
  return &_OrgApacheLuceneSearchBlendedTermQuery;
}

+ (void)initialize {
  if (self == [OrgApacheLuceneSearchBlendedTermQuery class]) {
    JreStrongAssignAndConsume(&OrgApacheLuceneSearchBlendedTermQuery_BOOLEAN_REWRITE, new_OrgApacheLuceneSearchBlendedTermQuery_1_init());
    JreStrongAssignAndConsume(&OrgApacheLuceneSearchBlendedTermQuery_DISJUNCTION_MAX_REWRITE, new_OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite_initWithFloat_(0.01f));
    J2OBJC_SET_INITIALIZED(OrgApacheLuceneSearchBlendedTermQuery)
  }
}

@end

void OrgApacheLuceneSearchBlendedTermQuery_initWithOrgApacheLuceneIndexTermArray_withFloatArray_withOrgApacheLuceneIndexTermContextArray_withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_(OrgApacheLuceneSearchBlendedTermQuery *self, IOSObjectArray *terms, IOSFloatArray *boosts, IOSObjectArray *contexts, OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *rewriteMethod) {
  OrgApacheLuceneSearchQuery_init(self);
  JreAssert(((IOSObjectArray *) nil_chk(terms))->size_ == ((IOSFloatArray *) nil_chk(boosts))->size_, @"org/apache/lucene/search/BlendedTermQuery.java:194 condition failed: assert terms.length == boosts.length;");
  JreAssert(terms->size_ == ((IOSObjectArray *) nil_chk(contexts))->size_, @"org/apache/lucene/search/BlendedTermQuery.java:195 condition failed: assert terms.length == contexts.length;");
  JreStrongAssign(&self->terms_, terms);
  JreStrongAssign(&self->boosts_, boosts);
  JreStrongAssign(&self->contexts_, contexts);
  JreStrongAssign(&self->rewriteMethod_, rewriteMethod);
  [create_OrgApacheLuceneSearchBlendedTermQuery_2_initWithOrgApacheLuceneIndexTermArray_withOrgApacheLuceneIndexTermContextArray_withFloatArray_(terms, contexts, boosts) sortWithInt:0 withInt:terms->size_];
}

OrgApacheLuceneSearchBlendedTermQuery *new_OrgApacheLuceneSearchBlendedTermQuery_initWithOrgApacheLuceneIndexTermArray_withFloatArray_withOrgApacheLuceneIndexTermContextArray_withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_(IOSObjectArray *terms, IOSFloatArray *boosts, IOSObjectArray *contexts, OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *rewriteMethod) {
  J2OBJC_NEW_IMPL(OrgApacheLuceneSearchBlendedTermQuery, initWithOrgApacheLuceneIndexTermArray_withFloatArray_withOrgApacheLuceneIndexTermContextArray_withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_, terms, boosts, contexts, rewriteMethod)
}

OrgApacheLuceneSearchBlendedTermQuery *create_OrgApacheLuceneSearchBlendedTermQuery_initWithOrgApacheLuceneIndexTermArray_withFloatArray_withOrgApacheLuceneIndexTermContextArray_withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_(IOSObjectArray *terms, IOSFloatArray *boosts, IOSObjectArray *contexts, OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *rewriteMethod) {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneSearchBlendedTermQuery, initWithOrgApacheLuceneIndexTermArray_withFloatArray_withOrgApacheLuceneIndexTermContextArray_withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_, terms, boosts, contexts, rewriteMethod)
}

OrgApacheLuceneIndexTermContext *OrgApacheLuceneSearchBlendedTermQuery_adjustFrequenciesWithOrgApacheLuceneIndexTermContext_withInt_withLong_(OrgApacheLuceneIndexTermContext *ctx, jint artificialDf, jlong artificialTtf) {
  OrgApacheLuceneSearchBlendedTermQuery_initialize();
  id<JavaUtilList> leaves = JreRetainedLocalValue([((OrgApacheLuceneIndexIndexReaderContext *) nil_chk(((OrgApacheLuceneIndexTermContext *) nil_chk(ctx))->topReaderContext_)) leaves]);
  jint len;
  if (leaves == nil) {
    len = 1;
  }
  else {
    len = [leaves size];
  }
  OrgApacheLuceneIndexTermContext *newCtx = create_OrgApacheLuceneIndexTermContext_initWithOrgApacheLuceneIndexIndexReaderContext_(ctx->topReaderContext_);
  for (jint i = 0; i < len; ++i) {
    OrgApacheLuceneIndexTermState *termState = JreRetainedLocalValue([ctx getWithInt:i]);
    if (termState == nil) {
      continue;
    }
    [newCtx register__WithOrgApacheLuceneIndexTermState:termState withInt:i];
  }
  [newCtx accumulateStatisticsWithInt:artificialDf withLong:artificialTtf];
  return newCtx;
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneSearchBlendedTermQuery)

@implementation OrgApacheLuceneSearchBlendedTermQuery_Builder

J2OBJC_IGNORE_DESIGNATED_BEGIN
- (instancetype)init {
  OrgApacheLuceneSearchBlendedTermQuery_Builder_init(self);
  return self;
}
J2OBJC_IGNORE_DESIGNATED_END

- (OrgApacheLuceneSearchBlendedTermQuery_Builder *)setRewriteMethodWithOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod:(OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *)rewiteMethod {
  JreStrongAssign(&self->rewriteMethod_, rewiteMethod);
  return self;
}

- (OrgApacheLuceneSearchBlendedTermQuery_Builder *)addWithOrgApacheLuceneIndexTerm:(OrgApacheLuceneIndexTerm *)term {
  return [self addWithOrgApacheLuceneIndexTerm:term withFloat:1.0f];
}

- (OrgApacheLuceneSearchBlendedTermQuery_Builder *)addWithOrgApacheLuceneIndexTerm:(OrgApacheLuceneIndexTerm *)term
                                                                         withFloat:(jfloat)boost {
  return [self addWithOrgApacheLuceneIndexTerm:term withFloat:boost withOrgApacheLuceneIndexTermContext:nil];
}

- (OrgApacheLuceneSearchBlendedTermQuery_Builder *)addWithOrgApacheLuceneIndexTerm:(OrgApacheLuceneIndexTerm *)term
                                                                         withFloat:(jfloat)boost
                                               withOrgApacheLuceneIndexTermContext:(OrgApacheLuceneIndexTermContext *)context {
  if (numTerms_ >= OrgApacheLuceneSearchBooleanQuery_getMaxClauseCount()) {
    @throw create_OrgApacheLuceneSearchBooleanQuery_TooManyClauses_init();
  }
  JreStrongAssign(&terms_, OrgApacheLuceneUtilArrayUtil_growWithNSObjectArray_withInt_(terms_, numTerms_ + 1));
  JreStrongAssign(&boosts_, OrgApacheLuceneUtilArrayUtil_growWithFloatArray_withInt_(boosts_, numTerms_ + 1));
  JreStrongAssign(&contexts_, OrgApacheLuceneUtilArrayUtil_growWithNSObjectArray_withInt_(contexts_, numTerms_ + 1));
  IOSObjectArray_SetAndConsume(nil_chk(terms_), numTerms_, new_OrgApacheLuceneIndexTerm_initWithNSString_withOrgApacheLuceneUtilBytesRef_([((OrgApacheLuceneIndexTerm *) nil_chk(term)) field], OrgApacheLuceneUtilBytesRef_deepCopyOfWithOrgApacheLuceneUtilBytesRef_([term bytes])));
  *IOSFloatArray_GetRef(nil_chk(boosts_), numTerms_) = boost;
  IOSObjectArray_Set(nil_chk(contexts_), numTerms_, context);
  numTerms_ += 1;
  return self;
}

- (OrgApacheLuceneSearchBlendedTermQuery *)build {
  return create_OrgApacheLuceneSearchBlendedTermQuery_initWithOrgApacheLuceneIndexTermArray_withFloatArray_withOrgApacheLuceneIndexTermContextArray_withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_(JavaUtilArrays_copyOfWithNSObjectArray_withInt_(terms_, numTerms_), JavaUtilArrays_copyOfWithFloatArray_withInt_(boosts_, numTerms_), JavaUtilArrays_copyOfWithNSObjectArray_withInt_(contexts_, numTerms_), rewriteMethod_);
}

- (void)dealloc {
  RELEASE_(terms_);
  RELEASE_(boosts_);
  RELEASE_(contexts_);
  RELEASE_(rewriteMethod_);
  [super dealloc];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x1, -1, -1, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneSearchBlendedTermQuery_Builder;", 0x1, 0, 1, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneSearchBlendedTermQuery_Builder;", 0x1, 2, 3, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneSearchBlendedTermQuery_Builder;", 0x1, 2, 4, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneSearchBlendedTermQuery_Builder;", 0x1, 2, 5, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneSearchBlendedTermQuery;", 0x1, -1, -1, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(init);
  methods[1].selector = @selector(setRewriteMethodWithOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod:);
  methods[2].selector = @selector(addWithOrgApacheLuceneIndexTerm:);
  methods[3].selector = @selector(addWithOrgApacheLuceneIndexTerm:withFloat:);
  methods[4].selector = @selector(addWithOrgApacheLuceneIndexTerm:withFloat:withOrgApacheLuceneIndexTermContext:);
  methods[5].selector = @selector(build);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "numTerms_", "I", .constantValue.asLong = 0, 0x2, -1, -1, -1, -1 },
    { "terms_", "[LOrgApacheLuceneIndexTerm;", .constantValue.asLong = 0, 0x2, -1, -1, -1, -1 },
    { "boosts_", "[F", .constantValue.asLong = 0, 0x2, -1, -1, -1, -1 },
    { "contexts_", "[LOrgApacheLuceneIndexTermContext;", .constantValue.asLong = 0, 0x2, -1, -1, -1, -1 },
    { "rewriteMethod_", "LOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod;", .constantValue.asLong = 0, 0x2, -1, -1, -1, -1 },
  };
  static const void *ptrTable[] = { "setRewriteMethod", "LOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod;", "add", "LOrgApacheLuceneIndexTerm;", "LOrgApacheLuceneIndexTerm;F", "LOrgApacheLuceneIndexTerm;FLOrgApacheLuceneIndexTermContext;", "LOrgApacheLuceneSearchBlendedTermQuery;" };
  static const J2ObjcClassInfo _OrgApacheLuceneSearchBlendedTermQuery_Builder = { "Builder", "org.apache.lucene.search", ptrTable, methods, fields, 7, 0x9, 6, 5, 6, -1, -1, -1, -1 };
  return &_OrgApacheLuceneSearchBlendedTermQuery_Builder;
}

@end

void OrgApacheLuceneSearchBlendedTermQuery_Builder_init(OrgApacheLuceneSearchBlendedTermQuery_Builder *self) {
  NSObject_init(self);
  self->numTerms_ = 0;
  JreStrongAssignAndConsume(&self->terms_, [IOSObjectArray newArrayWithLength:0 type:OrgApacheLuceneIndexTerm_class_()]);
  JreStrongAssignAndConsume(&self->boosts_, [IOSFloatArray newArrayWithLength:0]);
  JreStrongAssignAndConsume(&self->contexts_, [IOSObjectArray newArrayWithLength:0 type:OrgApacheLuceneIndexTermContext_class_()]);
  JreStrongAssign(&self->rewriteMethod_, JreLoadStatic(OrgApacheLuceneSearchBlendedTermQuery, DISJUNCTION_MAX_REWRITE));
}

OrgApacheLuceneSearchBlendedTermQuery_Builder *new_OrgApacheLuceneSearchBlendedTermQuery_Builder_init() {
  J2OBJC_NEW_IMPL(OrgApacheLuceneSearchBlendedTermQuery_Builder, init)
}

OrgApacheLuceneSearchBlendedTermQuery_Builder *create_OrgApacheLuceneSearchBlendedTermQuery_Builder_init() {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneSearchBlendedTermQuery_Builder, init)
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneSearchBlendedTermQuery_Builder)

@implementation OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod

J2OBJC_IGNORE_DESIGNATED_BEGIN
- (instancetype)init {
  OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_init(self);
  return self;
}
J2OBJC_IGNORE_DESIGNATED_END

- (OrgApacheLuceneSearchQuery *)rewriteWithOrgApacheLuceneSearchQueryArray:(IOSObjectArray *)subQueries {
  // can't call an abstract method
  [self doesNotRecognizeSelector:_cmd];
  return 0;
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x4, -1, -1, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneSearchQuery;", 0x401, 0, 1, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(init);
  methods[1].selector = @selector(rewriteWithOrgApacheLuceneSearchQueryArray:);
  #pragma clang diagnostic pop
  static const void *ptrTable[] = { "rewrite", "[LOrgApacheLuceneSearchQuery;", "LOrgApacheLuceneSearchBlendedTermQuery;" };
  static const J2ObjcClassInfo _OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod = { "RewriteMethod", "org.apache.lucene.search", ptrTable, methods, NULL, 7, 0x409, 2, 0, 2, -1, -1, -1, -1 };
  return &_OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod;
}

@end

void OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_init(OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod *self) {
  NSObject_init(self);
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod)

@implementation OrgApacheLuceneSearchBlendedTermQuery_1

J2OBJC_IGNORE_DESIGNATED_BEGIN
- (instancetype)init {
  OrgApacheLuceneSearchBlendedTermQuery_1_init(self);
  return self;
}
J2OBJC_IGNORE_DESIGNATED_END

- (OrgApacheLuceneSearchQuery *)rewriteWithOrgApacheLuceneSearchQueryArray:(IOSObjectArray *)subQueries {
  OrgApacheLuceneSearchBooleanQuery_Builder *merged = create_OrgApacheLuceneSearchBooleanQuery_Builder_init();
  [merged setDisableCoordWithBoolean:true];
  {
    IOSObjectArray *a__ = subQueries;
    OrgApacheLuceneSearchQuery * const *b__ = ((IOSObjectArray *) nil_chk(a__))->buffer_;
    OrgApacheLuceneSearchQuery * const *e__ = b__ + a__->size_;
    while (b__ < e__) {
      OrgApacheLuceneSearchQuery *query = *b__++;
      [merged addWithOrgApacheLuceneSearchQuery:query withOrgApacheLuceneSearchBooleanClause_Occur:JreLoadEnum(OrgApacheLuceneSearchBooleanClause_Occur, SHOULD)];
    }
  }
  return JreRetainedLocalValue([merged build]);
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x0, -1, -1, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneSearchQuery;", 0x1, 0, 1, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(init);
  methods[1].selector = @selector(rewriteWithOrgApacheLuceneSearchQueryArray:);
  #pragma clang diagnostic pop
  static const void *ptrTable[] = { "rewrite", "[LOrgApacheLuceneSearchQuery;", "LOrgApacheLuceneSearchBlendedTermQuery;" };
  static const J2ObjcClassInfo _OrgApacheLuceneSearchBlendedTermQuery_1 = { "", "org.apache.lucene.search", ptrTable, methods, NULL, 7, 0x8018, 2, 0, 2, -1, -1, -1, -1 };
  return &_OrgApacheLuceneSearchBlendedTermQuery_1;
}

@end

void OrgApacheLuceneSearchBlendedTermQuery_1_init(OrgApacheLuceneSearchBlendedTermQuery_1 *self) {
  OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_init(self);
}

OrgApacheLuceneSearchBlendedTermQuery_1 *new_OrgApacheLuceneSearchBlendedTermQuery_1_init() {
  J2OBJC_NEW_IMPL(OrgApacheLuceneSearchBlendedTermQuery_1, init)
}

OrgApacheLuceneSearchBlendedTermQuery_1 *create_OrgApacheLuceneSearchBlendedTermQuery_1_init() {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneSearchBlendedTermQuery_1, init)
}

@implementation OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite

- (instancetype)initWithFloat:(jfloat)tieBreakerMultiplier {
  OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite_initWithFloat_(self, tieBreakerMultiplier);
  return self;
}

- (OrgApacheLuceneSearchQuery *)rewriteWithOrgApacheLuceneSearchQueryArray:(IOSObjectArray *)subQueries {
  return create_OrgApacheLuceneSearchDisjunctionMaxQuery_initWithJavaUtilCollection_withFloat_(JavaUtilArrays_asListWithNSObjectArray_(subQueries), tieBreakerMultiplier_);
}

- (jboolean)isEqual:(id)obj {
  if (obj == nil || !JreObjectEqualsEquals([self java_getClass], [obj java_getClass])) {
    return false;
  }
  OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite *that = (OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite *) cast_chk(obj, [OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite class]);
  return tieBreakerMultiplier_ == that->tieBreakerMultiplier_;
}

- (NSUInteger)hash {
  return 31 * ((jint) [[self java_getClass] hash]) + JavaLangFloat_floatToIntBitsWithFloat_(tieBreakerMultiplier_);
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x1, -1, 0, -1, -1, -1, -1 },
    { NULL, "LOrgApacheLuceneSearchQuery;", 0x1, 1, 2, -1, -1, -1, -1 },
    { NULL, "Z", 0x1, 3, 4, -1, -1, -1, -1 },
    { NULL, "I", 0x1, 5, -1, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(initWithFloat:);
  methods[1].selector = @selector(rewriteWithOrgApacheLuceneSearchQueryArray:);
  methods[2].selector = @selector(isEqual:);
  methods[3].selector = @selector(hash);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "tieBreakerMultiplier_", "F", .constantValue.asLong = 0, 0x12, -1, -1, -1, -1 },
  };
  static const void *ptrTable[] = { "F", "rewrite", "[LOrgApacheLuceneSearchQuery;", "equals", "LNSObject;", "hashCode", "LOrgApacheLuceneSearchBlendedTermQuery;" };
  static const J2ObjcClassInfo _OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite = { "DisjunctionMaxRewrite", "org.apache.lucene.search", ptrTable, methods, fields, 7, 0x9, 4, 1, 6, -1, -1, -1, -1 };
  return &_OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite;
}

@end

void OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite_initWithFloat_(OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite *self, jfloat tieBreakerMultiplier) {
  OrgApacheLuceneSearchBlendedTermQuery_RewriteMethod_init(self);
  self->tieBreakerMultiplier_ = tieBreakerMultiplier;
}

OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite *new_OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite_initWithFloat_(jfloat tieBreakerMultiplier) {
  J2OBJC_NEW_IMPL(OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite, initWithFloat_, tieBreakerMultiplier)
}

OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite *create_OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite_initWithFloat_(jfloat tieBreakerMultiplier) {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite, initWithFloat_, tieBreakerMultiplier)
}

J2OBJC_CLASS_TYPE_LITERAL_SOURCE(OrgApacheLuceneSearchBlendedTermQuery_DisjunctionMaxRewrite)

@implementation OrgApacheLuceneSearchBlendedTermQuery_2

- (instancetype)initWithOrgApacheLuceneIndexTermArray:(IOSObjectArray *)capture$0
             withOrgApacheLuceneIndexTermContextArray:(IOSObjectArray *)capture$1
                                       withFloatArray:(IOSFloatArray *)capture$2 {
  OrgApacheLuceneSearchBlendedTermQuery_2_initWithOrgApacheLuceneIndexTermArray_withOrgApacheLuceneIndexTermContextArray_withFloatArray_(self, capture$0, capture$1, capture$2);
  return self;
}

- (void)swapWithInt:(jint)i
            withInt:(jint)j {
  OrgApacheLuceneIndexTerm *tmpTerm = IOSObjectArray_Get(nil_chk(val$terms_), i);
  IOSObjectArray_Set(val$terms_, i, IOSObjectArray_Get(val$terms_, j));
  IOSObjectArray_Set(val$terms_, j, tmpTerm);
  OrgApacheLuceneIndexTermContext *tmpContext = IOSObjectArray_Get(nil_chk(val$contexts_), i);
  IOSObjectArray_Set(val$contexts_, i, IOSObjectArray_Get(val$contexts_, j));
  IOSObjectArray_Set(val$contexts_, j, tmpContext);
  jfloat tmpBoost = IOSFloatArray_Get(nil_chk(val$boosts_), i);
  *IOSFloatArray_GetRef(val$boosts_, i) = IOSFloatArray_Get(val$boosts_, j);
  *IOSFloatArray_GetRef(val$boosts_, j) = tmpBoost;
}

- (jint)compareWithInt:(jint)i
               withInt:(jint)j {
  return [((OrgApacheLuceneIndexTerm *) nil_chk(IOSObjectArray_Get(nil_chk(val$terms_), i))) compareToWithId:IOSObjectArray_Get(val$terms_, j)];
}

- (void)dealloc {
  RELEASE_(val$terms_);
  RELEASE_(val$contexts_);
  RELEASE_(val$boosts_);
  [super dealloc];
}

+ (const J2ObjcClassInfo *)__metadata {
  static J2ObjcMethodInfo methods[] = {
    { NULL, NULL, 0x0, -1, 0, -1, -1, -1, -1 },
    { NULL, "V", 0x4, 1, 2, -1, -1, -1, -1 },
    { NULL, "I", 0x4, 3, 2, -1, -1, -1, -1 },
  };
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wobjc-multiple-method-names"
  #pragma clang diagnostic ignored "-Wundeclared-selector"
  methods[0].selector = @selector(initWithOrgApacheLuceneIndexTermArray:withOrgApacheLuceneIndexTermContextArray:withFloatArray:);
  methods[1].selector = @selector(swapWithInt:withInt:);
  methods[2].selector = @selector(compareWithInt:withInt:);
  #pragma clang diagnostic pop
  static const J2ObjcFieldInfo fields[] = {
    { "val$terms_", "[LOrgApacheLuceneIndexTerm;", .constantValue.asLong = 0, 0x1012, -1, -1, -1, -1 },
    { "val$contexts_", "[LOrgApacheLuceneIndexTermContext;", .constantValue.asLong = 0, 0x1012, -1, -1, -1, -1 },
    { "val$boosts_", "[F", .constantValue.asLong = 0, 0x1012, -1, -1, -1, -1 },
  };
  static const void *ptrTable[] = { "[LOrgApacheLuceneIndexTerm;[LOrgApacheLuceneIndexTermContext;[F", "swap", "II", "compare", "LOrgApacheLuceneSearchBlendedTermQuery;", "initWithOrgApacheLuceneIndexTermArray:withFloatArray:withOrgApacheLuceneIndexTermContextArray:withOrgApacheLuceneSearchBlendedTermQuery_RewriteMethod:" };
  static const J2ObjcClassInfo _OrgApacheLuceneSearchBlendedTermQuery_2 = { "", "org.apache.lucene.search", ptrTable, methods, fields, 7, 0x8010, 3, 3, 4, -1, 5, -1, -1 };
  return &_OrgApacheLuceneSearchBlendedTermQuery_2;
}

@end

void OrgApacheLuceneSearchBlendedTermQuery_2_initWithOrgApacheLuceneIndexTermArray_withOrgApacheLuceneIndexTermContextArray_withFloatArray_(OrgApacheLuceneSearchBlendedTermQuery_2 *self, IOSObjectArray *capture$0, IOSObjectArray *capture$1, IOSFloatArray *capture$2) {
  JreStrongAssign(&self->val$terms_, capture$0);
  JreStrongAssign(&self->val$contexts_, capture$1);
  JreStrongAssign(&self->val$boosts_, capture$2);
  OrgApacheLuceneUtilInPlaceMergeSorter_init(self);
}

OrgApacheLuceneSearchBlendedTermQuery_2 *new_OrgApacheLuceneSearchBlendedTermQuery_2_initWithOrgApacheLuceneIndexTermArray_withOrgApacheLuceneIndexTermContextArray_withFloatArray_(IOSObjectArray *capture$0, IOSObjectArray *capture$1, IOSFloatArray *capture$2) {
  J2OBJC_NEW_IMPL(OrgApacheLuceneSearchBlendedTermQuery_2, initWithOrgApacheLuceneIndexTermArray_withOrgApacheLuceneIndexTermContextArray_withFloatArray_, capture$0, capture$1, capture$2)
}

OrgApacheLuceneSearchBlendedTermQuery_2 *create_OrgApacheLuceneSearchBlendedTermQuery_2_initWithOrgApacheLuceneIndexTermArray_withOrgApacheLuceneIndexTermContextArray_withFloatArray_(IOSObjectArray *capture$0, IOSObjectArray *capture$1, IOSFloatArray *capture$2) {
  J2OBJC_CREATE_IMPL(OrgApacheLuceneSearchBlendedTermQuery_2, initWithOrgApacheLuceneIndexTermArray_withOrgApacheLuceneIndexTermContextArray_withFloatArray_, capture$0, capture$1, capture$2)
}


text:
package org.apache.storm.spout;

import java.nio.ByteBuffer;
import java.util.List;

import org.apache.storm.tuple.Fields;
import org.apache.storm.utils.Utils;

import static org.apache.storm.utils.Utils.tuple;
import static java.util.Arrays.asList;

public class RawMultiScheme implements MultiScheme {
  @Override
  public Iterable<List<Object>> deserialize(ByteBuffer ser) {
    return asList(tuple(Utils.toByteArray(ser)));
  }

  @Override
  public Fields getOutputFields() {
    return new Fields("bytes");
  }
}


text:
import { View } from '@ckeditor/ckeditor5-ui';
import { Locale } from '@ckeditor/ckeditor5-utils';

export default class ImageUploadFormRowView extends View {
    constructor(locale: Locale, options?: { children?: View[] | undefined; class?: string; labelView?: View });
    class: string | null;
}


text:
/**
 * A simple routine for showing geometric objects in the examples.
 */

//var util = require("util");
module.exports = function (title, polygon) {
  //console.log(title+" = \n"+util.inspect(polygon,null,3)+" "+(polygon.isEmpty? (polygon.isEmpty() ?" EMPTY": "NONEMPTY"): "")+"\n\n");
  console.log(title+" = "+polygon.toString()+" "+(polygon.isEmpty? (polygon.isEmpty() ?" EMPTY": "NONEMPTY"): "")+"\n\n");
};


text:
/**
 * Created by Robin on 3/16/2016.
 */

/**
 *
 * @param {number} radius               The radius of the projectile.
 *
 * @param {Object} speed                The speed of the projectile.
 * @param {number} speed.dx
 * @param {number} speed.dy
 *
 * @param {Object} startPosition        Starting position.
 * @param {number} startPosition.x
 * @param {number} startPosition.y
 *
 * @constructor
 */
var Projectile = function (radius, speed, startPosition) {
    this.radius = radius;
    this.speed = speed;
    this.position = startPosition;
    this.gameOver = false;
};

Projectile.prototype.update = function (canvas, players, room, socket) {
    var oldX = this.position.x,
        oldY = this.position.y;
    this.move(canvas, players);

    if ((this.position.x !== oldX || this.position.y !== oldY) || this.gameOver) {
        this.gameOver = false;
        socket.emit("ballupdate", {"roomNumber": room, "projectile": this});
    }

};

/**
 * This method simply returns radius*2, you could use this to get the width or height
 * of the projectile.
 *
 * @returns {number} Width or Height
 */
Projectile.prototype.getWidthHeight = function () {
    return this.radius * 2;
};

/**
 * Draws the projectile on the given canvas context.
 *
 * @param {Object} context              The context derived from the canvas.
 */
Projectile.prototype.draw = function (context) {
    //TODO drawing logic here
    context.beginPath();
    context.arc(this.position.x, this.position.y, this.radius, 2 * Math.PI, false);
    context.fillStyle = "#000000";
    context.fill();
};

/**
 * Reviver function to create a new Projectile from the given Json.
 *
 * @param {Object} json
 * @returns {Projectile}
 */
Projectile.revive = function (json) {
    return new Projectile(json.radius, json.speed, json.position);
};

/**
 * @param {Element} canvas
 * @param {Object[]} players
 * @author Sander
 */
Projectile.prototype.move = function (canvas, players) {
    this.position.x += this.speed.dx;
    this.position.y += this.speed.dy;

    if (this.position.y <= 0) {
        this.position.y = 0;
        this.position.y -= this.speed.dy;
        this.speed.dy *= -1;
    } else if (this.position.y >= canvas.height) {
        this.position.y = canvas.height;
        this.position.y -= this.getWidthHeight();
        this.speed.dy *= -1;
    }

    if ((this.position.x + this.getWidthHeight() >= (canvas.width - players[1].size.width + 5)) && (this.position.y >= players[1].position.y) && (this.position.y <= players[1].position.y + players[1].size.height)) {
        this.position.x = (canvas.width - players[1].size.width * 2 - this.speed.dx);
        // this.speed.dy += (players[1].speed / 2);
        this.speed.dx *= -1;
        this.position.x += this.speed.dx;
    } else if ((this.position.x - this.getWidthHeight() <= (players[0].size.width - 5)) && (this.position.y >= players[0].position.y) && (this.position.y <= (players[0].position.y + players[0].size.height))) {
        this.position.x = (players[0].size.width * 2) - this.speed.dx;
        // this.speed.dy += (players[0].speed / 2);
        this.speed.dx *= -1;
        this.position.x += this.speed.dx;
    }

    // this.draw(canvas.getContext("2d"));
    if (this.position.x > canvas.width || this.position.x < 0) {
        if (this.position.x > canvas.width)
            players[0].score++;
        if (this.position.x < 0)
            players[1].score++;

        this.finishRound(canvas, players);
    }
};

Projectile.prototype.finishRound = function (canvas, players) {
    for (var i in players) {
        players[i].ready = false;
        this.position.x = canvas.width / 2;
        this.position.y = canvas.height / 2;
    }
    this.gameOver = true;
};


text:
layout: navbar_sidebar
title: Navbar and Sidebar Layout
permalink: examples/navbar-sidebar/
---

This is the fixed navbar and sidebar layout

Your content goes here! :thumbsup:


text:
<?php

namespace Magento\Quote\Observer\Frontend\Quote\Address;

use Magento\TestFramework\Helper\Bootstrap;

class CollectTotalsObserverTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver
     */
    protected $model;

    /**
     * Object Manager
     *
     * @var \Magento\Framework\ObjectManagerInterface
     */
    private $objectManager;

    protected function setUp()
    {
        $this->objectManager = Bootstrap::getObjectManager();
        $this->model = $this->objectManager->create(
            'Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver'
        );
    }

    /**
     * @magentoConfigFixture current_store customer/create_account/auto_group_assign 1
     * @magentoConfigFixture current_store customer/create_account/default_group 1
     * @magentoDataFixture Magento/Customer/_files/customer.php
     * @magentoDataFixture Magento/Sales/_files/quote.php
     *
     * @covers \Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver::execute
     */
    public function testChangeQuoteCustomerGroupIdForCustomerWithDisabledAutomaticGroupChange()
    {
        /** @var \Magento\Framework\ObjectManagerInterface $objectManager */
        $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();

        /** @var $customer \Magento\Customer\Model\Customer */
        $customer = $objectManager->create('Magento\Customer\Model\Customer');
        $customer->load(1);
        $customer->setDisableAutoGroupChange(1);
        $customer->setGroupId(2);
        $customer->save();

        /** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository */
        $customerRepository = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface');
        $customerData = $customerRepository->getById($customer->getId());

        /** @var $quote \Magento\Quote\Model\Quote */
        $quote = $objectManager->create('Magento\Quote\Model\Quote');
        $quote->load('test01', 'reserved_order_id');
        $quote->setCustomer($customerData);

        $quoteAddress = $quote->getBillingAddress();
        $shippingAssignment = $this->objectManager->create('Magento\Quote\Model\ShippingAssignment');
        $shipping = $this->objectManager->create('Magento\Quote\Model\Shipping');
        $shipping->setAddress($quoteAddress);
        $shippingAssignment->setShipping($shipping);
        /** @var  \Magento\Quote\Model\Quote\Address\Total $total */
        $total = $this->objectManager->create('Magento\Quote\Model\Quote\Address\Total');

        $eventObserver = $objectManager->create(
            'Magento\Framework\Event\Observer',
            ['data' => [
                'quote' => $quote,
                'shipping_assignment' => $shippingAssignment,
                'total' => $total
        ]
            ]
        );
        $this->model->execute($eventObserver);

        $this->assertEquals(2, $quote->getCustomer()->getGroupId());
    }

    /**
     * @magentoConfigFixture current_store customer/create_account/auto_group_assign 1
     * @magentoConfigFixture current_store customer/create_account/default_group 1
     * @magentoDataFixture Magento/Customer/_files/customer.php
     * @magentoDataFixture Magento/Sales/_files/quote.php
     *
     * @covers \Magento\Quote\Observer\Frontend\Quote\Address\CollectTotalsObserver::execute
     */
    public function testChangeQuoteCustomerGroupIdForCustomerWithEnabledAutomaticGroupChange()
    {
        /** @var \Magento\Framework\ObjectManagerInterface $objectManager */
        $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();

        /** @var $customer \Magento\Customer\Model\Customer */
        $customer = $objectManager->create('Magento\Customer\Model\Customer');
        $customer->load(1);
        $customer->setDisableAutoGroupChange(0);
        $customer->setGroupId(2);
        $customer->save();

        /** @var \Magento\Customer\Model\CustomerRegistry $customerRegistry */
        $customerRegistry = $objectManager->get('Magento\Customer\Model\CustomerRegistry');
        $customerRegistry->remove($customer->getId());

        /** @var \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository */
        $customerRepository = $objectManager->create('Magento\Customer\Api\CustomerRepositoryInterface');
        $customerData = $customerRepository->getById($customer->getId());

        /** @var $quote \Magento\Quote\Model\Quote */
        $quote = $objectManager->create('Magento\Quote\Model\Quote');
        $quote->load('test01', 'reserved_order_id');
        $quote->setCustomer($customerData);

        $quoteAddress = $quote->getBillingAddress();

        $shippingAssignment = $this->objectManager->create('Magento\Quote\Model\ShippingAssignment');
        $shipping = $this->objectManager->create('Magento\Quote\Model\Shipping');
        $shipping->setAddress($quoteAddress);
        $shippingAssignment->setShipping($shipping);
        /** @var  \Magento\Quote\Model\Quote\Address\Total $total */
        $total = $this->objectManager->create('Magento\Quote\Model\Quote\Address\Total');

        $eventObserver = $objectManager->create(
            'Magento\Framework\Event\Observer',
            ['data' => [
                'quote' => $quote,
                'shipping_assignment' => $shippingAssignment,
                'total' => $total
            ]
            ]
        );
        $this->model->execute($eventObserver);

        $this->assertEquals(1, $quote->getCustomer()->getGroupId());
    }
}


text:
#pragma once

#include <pcl/pcl_base.h>
#include <pcl/point_types_conversion.h>
#include <pcl/search/pcl_search.h>

namespace pcl
{
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  /** \brief Decompose a region of space into clusters based on the Euclidean distance between points
    * \param[in] cloud the point cloud message
    * \param[in] tree the spatial locator (e.g., kd-tree) used for nearest neighbors searching
    * \note the tree has to be created as a spatial locator on \a cloud
    * \param[in] tolerance the spatial cluster tolerance as a measure in L2 Euclidean space
    * \param[in] indices_in the cluster containing the seed point indices (as a vector of PointIndices)
    * \param[out] indices_out
    * \param[in] delta_hue
    * \todo look how to make this templated!
    * \ingroup segmentation
    */
  void
  seededHueSegmentation (const PointCloud<PointXYZRGB>            &cloud,
                         const search::Search<PointXYZRGB>::Ptr   &tree,
                         float                                    tolerance,
                         PointIndices                             &indices_in,
                         PointIndices                             &indices_out,
                         float                                    delta_hue = 0.0);

  /** \brief Decompose a region of space into clusters based on the Euclidean distance between points
    * \param[in] cloud the point cloud message
    * \param[in] tree the spatial locator (e.g., kd-tree) used for nearest neighbors searching
    * \note the tree has to be created as a spatial locator on \a cloud
    * \param[in] tolerance the spatial cluster tolerance as a measure in L2 Euclidean space
    * \param[in] indices_in the cluster containing the seed point indices (as a vector of PointIndices)
    * \param[out] indices_out
    * \param[in] delta_hue
    * \todo look how to make this templated!
    * \ingroup segmentation
    */
  void
  seededHueSegmentation (const PointCloud<PointXYZRGB>            &cloud,
                         const search::Search<PointXYZRGBL>::Ptr  &tree,
                         float                                    tolerance,
                         PointIndices                             &indices_in,
                         PointIndices                             &indices_out,
                         float                                    delta_hue = 0.0);

  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  /** \brief SeededHueSegmentation
    * \author Koen Buys
    * \ingroup segmentation
    */
  class SeededHueSegmentation: public PCLBase<PointXYZRGB>
  {
    using BasePCLBase = PCLBase<PointXYZRGB>;

    public:
      using PointCloud = pcl::PointCloud<PointXYZRGB>;
      using PointCloudPtr = PointCloud::Ptr;
      using PointCloudConstPtr = PointCloud::ConstPtr;

      using KdTree = pcl::search::Search<PointXYZRGB>;
      using KdTreePtr = pcl::search::Search<PointXYZRGB>::Ptr;

      using PointIndicesPtr = PointIndices::Ptr;
      using PointIndicesConstPtr = PointIndices::ConstPtr;

      //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
      /** \brief Empty constructor. */
      SeededHueSegmentation () : cluster_tolerance_ (0), delta_hue_ (0.0)
      {};

      /** \brief Provide a pointer to the search object.
        * \param[in] tree a pointer to the spatial search object.
        */
      inline void
      setSearchMethod (const KdTreePtr &tree) { tree_ = tree; }

      /** \brief Get a pointer to the search method used. */
      inline KdTreePtr
      getSearchMethod () const { return (tree_); }

      /** \brief Set the spatial cluster tolerance as a measure in the L2 Euclidean space
        * \param[in] tolerance the spatial cluster tolerance as a measure in the L2 Euclidean space
        */
      inline void
      setClusterTolerance (double tolerance) { cluster_tolerance_ = tolerance; }

      /** \brief Get the spatial cluster tolerance as a measure in the L2 Euclidean space. */
      inline double
      getClusterTolerance () const { return (cluster_tolerance_); }

      /** \brief Set the tollerance on the hue
        * \param[in] delta_hue the new delta hue
        */
      inline void
      setDeltaHue (float delta_hue) { delta_hue_ = delta_hue; }

      /** \brief Get the tolerance on the hue */
      inline float
      getDeltaHue () const { return (delta_hue_); }

      /** \brief Cluster extraction in a PointCloud given by <setInputCloud (), setIndices ()>
        * \param[in] indices_in
        * \param[out] indices_out
        */
      void
      segment (PointIndices &indices_in, PointIndices &indices_out);

    protected:
      // Members derived from the base class
      using BasePCLBase::input_;
      using BasePCLBase::indices_;
      using BasePCLBase::initCompute;
      using BasePCLBase::deinitCompute;

      /** \brief A pointer to the spatial search object. */
      KdTreePtr tree_;

      /** \brief The spatial cluster tolerance as a measure in the L2 Euclidean space. */
      double cluster_tolerance_;

      /** \brief The allowed difference on the hue*/
      float delta_hue_;

      /** \brief Class getName method. */
      virtual std::string getClassName () const { return ("seededHueSegmentation"); }
  };
}

#ifdef PCL_NO_PRECOMPILE
#include <pcl/segmentation/impl/seeded_hue_segmentation.hpp>
#endif