text:
import _extends from "@babel/runtime/helpers/esm/extends";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _typeof from "@babel/runtime/helpers/esm/typeof";

/* eslint-disable no-constant-condition */
import * as React from 'react';
import { setRef, useEventCallback, useControlled, unstable_useId as useId } from '../utils'; // https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript
// Give up on IE11 support for this feature

function stripDiacritics(string) {
  return typeof string.normalize !== 'undefined' ? string.normalize('NFD').replace(/[\u0300-\u036f]/g, '') : string;
}

export function createFilterOptions() {
  var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var _config$ignoreAccents = config.ignoreAccents,
      ignoreAccents = _config$ignoreAccents === void 0 ? true : _config$ignoreAccents,
      _config$ignoreCase = config.ignoreCase,
      ignoreCase = _config$ignoreCase === void 0 ? true : _config$ignoreCase,
      limit = config.limit,
      _config$matchFrom = config.matchFrom,
      matchFrom = _config$matchFrom === void 0 ? 'any' : _config$matchFrom,
      stringify = config.stringify,
      _config$trim = config.trim,
      trim = _config$trim === void 0 ? false : _config$trim;
  return function (options, _ref) {
    var inputValue = _ref.inputValue,
        getOptionLabel = _ref.getOptionLabel;
    var input = trim ? inputValue.trim() : inputValue;

    if (ignoreCase) {
      input = input.toLowerCase();
    }

    if (ignoreAccents) {
      input = stripDiacritics(input);
    }

    var filteredOptions = options.filter(function (option) {
      var candidate = (stringify || getOptionLabel)(option);

      if (ignoreCase) {
        candidate = candidate.toLowerCase();
      }

      if (ignoreAccents) {
        candidate = stripDiacritics(candidate);
      }

      return matchFrom === 'start' ? candidate.indexOf(input) === 0 : candidate.indexOf(input) > -1;
    });
    return typeof limit === 'number' ? filteredOptions.slice(0, limit) : filteredOptions;
  };
} // To replace with .findIndex() once we stop IE11 support.

function findIndex(array, comp) {
  for (var i = 0; i < array.length; i += 1) {
    if (comp(array[i])) {
      return i;
    }
  }

  return -1;
}

var defaultFilterOptions = createFilterOptions(); // Number of options to jump in list box when pageup and pagedown keys are used.

var pageSize = 5;
export default function useAutocomplete(props) {
  var _props$autoComplete = props.autoComplete,
      autoComplete = _props$autoComplete === void 0 ? false : _props$autoComplete,
      _props$autoHighlight = props.autoHighlight,
      autoHighlight = _props$autoHighlight === void 0 ? false : _props$autoHighlight,
      _props$autoSelect = props.autoSelect,
      autoSelect = _props$autoSelect === void 0 ? false : _props$autoSelect,
      _props$blurOnSelect = props.blurOnSelect,
      blurOnSelect = _props$blurOnSelect === void 0 ? false : _props$blurOnSelect,
      _props$clearOnBlur = props.clearOnBlur,
      clearOnBlur = _props$clearOnBlur === void 0 ? !props.freeSolo : _props$clearOnBlur,
      _props$clearOnEscape = props.clearOnEscape,
      clearOnEscape = _props$clearOnEscape === void 0 ? false : _props$clearOnEscape,
      _props$componentName = props.componentName,
      componentName = _props$componentName === void 0 ? 'useAutocomplete' : _props$componentName,
      _props$defaultValue = props.defaultValue,
      defaultValue = _props$defaultValue === void 0 ? props.multiple ? [] : null : _props$defaultValue,
      _props$disableClearab = props.disableClearable,
      disableClearable = _props$disableClearab === void 0 ? false : _props$disableClearab,
      _props$disableCloseOn = props.disableCloseOnSelect,
      disableCloseOnSelect = _props$disableCloseOn === void 0 ? false : _props$disableCloseOn,
      _props$disabledItemsF = props.disabledItemsFocusable,
      disabledItemsFocusable = _props$disabledItemsF === void 0 ? false : _props$disabledItemsF,
      _props$disableListWra = props.disableListWrap,
      disableListWrap = _props$disableListWra === void 0 ? false : _props$disableListWra,
      _props$filterOptions = props.filterOptions,
      filterOptions = _props$filterOptions === void 0 ? defaultFilterOptions : _props$filterOptions,
      _props$filterSelected = props.filterSelectedOptions,
      filterSelectedOptions = _props$filterSelected === void 0 ? false : _props$filterSelected,
      _props$freeSolo = props.freeSolo,
      freeSolo = _props$freeSolo === void 0 ? false : _props$freeSolo,
      getOptionDisabled = props.getOptionDisabled,
      _props$getOptionLabel = props.getOptionLabel,
      getOptionLabelProp = _props$getOptionLabel === void 0 ? function (option) {
    var _option$label;

    return (_option$label = option.label) !== null && _option$label !== void 0 ? _option$label : option;
  } : _props$getOptionLabel,
      _props$isOptionEqualT = props.isOptionEqualToValue,
      isOptionEqualToValue = _props$isOptionEqualT === void 0 ? function (option, value) {
    return option === value;
  } : _props$isOptionEqualT,
      groupBy = props.groupBy,
      _props$handleHomeEndK = props.handleHomeEndKeys,
      handleHomeEndKeys = _props$handleHomeEndK === void 0 ? !props.freeSolo : _props$handleHomeEndK,
      idProp = props.id,
      _props$includeInputIn = props.includeInputInList,
      includeInputInList = _props$includeInputIn === void 0 ? false : _props$includeInputIn,
      inputValueProp = props.inputValue,
      _props$multiple = props.multiple,
      multiple = _props$multiple === void 0 ? false : _props$multiple,
      onChange = props.onChange,
      onClose = props.onClose,
      onHighlightChange = props.onHighlightChange,
      onInputChange = props.onInputChange,
      onOpen = props.onOpen,
      openProp = props.open,
      _props$openOnFocus = props.openOnFocus,
      openOnFocus = _props$openOnFocus === void 0 ? false : _props$openOnFocus,
      options = props.options,
      _props$selectOnFocus = props.selectOnFocus,
      selectOnFocus = _props$selectOnFocus === void 0 ? !props.freeSolo : _props$selectOnFocus,
      valueProp = props.value;
  var id = useId(idProp);
  var getOptionLabel = getOptionLabelProp;

  getOptionLabel = function getOptionLabel(option) {
    var optionLabel = getOptionLabelProp(option);

    if (typeof optionLabel !== 'string') {
      if (process.env.NODE_ENV !== 'production') {
        var erroneousReturn = optionLabel === undefined ? 'undefined' : "".concat(_typeof(optionLabel), " (").concat(optionLabel, ")");
        console.error("Material-UI: The `getOptionLabel` method of ".concat(componentName, " returned ").concat(erroneousReturn, " instead of a string for ").concat(JSON.stringify(option), "."));
      }

      return String(optionLabel);
    }

    return optionLabel;
  };

  var ignoreFocus = React.useRef(false);
  var firstFocus = React.useRef(true);
  var inputRef = React.useRef(null);
  var listboxRef = React.useRef(null);

  var _React$useState = React.useState(null),
      anchorEl = _React$useState[0],
      setAnchorEl = _React$useState[1];

  var _React$useState2 = React.useState(-1),
      focusedTag = _React$useState2[0],
      setFocusedTag = _React$useState2[1];

  var defaultHighlighted = autoHighlight ? 0 : -1;
  var highlightedIndexRef = React.useRef(defaultHighlighted);

  var _useControlled = useControlled({
    controlled: valueProp,
    default: defaultValue,
    name: componentName
  }),
      _useControlled2 = _slicedToArray(_useControlled, 2),
      value = _useControlled2[0],
      setValueState = _useControlled2[1];

  var _useControlled3 = useControlled({
    controlled: inputValueProp,
    default: '',
    name: componentName,
    state: 'inputValue'
  }),
      _useControlled4 = _slicedToArray(_useControlled3, 2),
      inputValue = _useControlled4[0],
      setInputValueState = _useControlled4[1];

  var _React$useState3 = React.useState(false),
      focused = _React$useState3[0],
      setFocused = _React$useState3[1];

  var resetInputValue = useEventCallback(function (event, newValue) {
    var newInputValue;

    if (multiple) {
      newInputValue = '';
    } else if (newValue == null) {
      newInputValue = '';
    } else {
      var optionLabel = getOptionLabel(newValue);
      newInputValue = typeof optionLabel === 'string' ? optionLabel : '';
    }

    if (inputValue === newInputValue) {
      return;
    }

    setInputValueState(newInputValue);

    if (onInputChange) {
      onInputChange(event, newInputValue, 'reset');
    }
  });
  React.useEffect(function () {
    resetInputValue(null, value);
  }, [value, resetInputValue]);

  var _useControlled5 = useControlled({
    controlled: openProp,
    default: false,
    name: componentName,
    state: 'open'
  }),
      _useControlled6 = _slicedToArray(_useControlled5, 2),
      open = _useControlled6[0],
      setOpenState = _useControlled6[1];

  var _React$useState4 = React.useState(true),
      inputPristine = _React$useState4[0],
      setInputPristine = _React$useState4[1];

  var inputValueIsSelectedValue = !multiple && value != null && inputValue === getOptionLabel(value);
  var popupOpen = open;
  var filteredOptions = popupOpen ? filterOptions(options.filter(function (option) {
    if (filterSelectedOptions && (multiple ? value : [value]).some(function (value2) {
      return value2 !== null && isOptionEqualToValue(option, value2);
    })) {
      return false;
    }

    return true;
  }), // we use the empty string to manipulate `filterOptions` to not filter any options
  // i.e. the filter predicate always returns true
  {
    inputValue: inputValueIsSelectedValue && inputPristine ? '' : inputValue,
    getOptionLabel: getOptionLabel
  }) : [];
  var listboxAvailable = open && filteredOptions.length > 0;

  if (process.env.NODE_ENV !== 'production') {
    if (value !== null && !freeSolo && options.length > 0) {
      var missingValue = (multiple ? value : [value]).filter(function (value2) {
        return !options.some(function (option) {
          return isOptionEqualToValue(option, value2);
        });
      });

      if (missingValue.length > 0) {
        console.warn(["Material-UI: The value provided to ".concat(componentName, " is invalid."), "None of the options match with `".concat(missingValue.length > 1 ? JSON.stringify(missingValue) : JSON.stringify(missingValue[0]), "`."), 'You can use the `isOptionEqualToValue` prop to customize the equality test.'].join('\n'));
      }
    }
  }

  var focusTag = useEventCallback(function (tagToFocus) {
    if (tagToFocus === -1) {
      inputRef.current.focus();
    } else {
      anchorEl.querySelector("[data-tag-index=\"".concat(tagToFocus, "\"]")).focus();
    }
  }); // Ensure the focusedTag is never inconsistent

  React.useEffect(function () {
    if (multiple && focusedTag > value.length - 1) {
      setFocusedTag(-1);
      focusTag(-1);
    }
  }, [value, multiple, focusedTag, focusTag]);

  function validOptionIndex(index, direction) {
    if (!listboxRef.current || index === -1) {
      return -1;
    }

    var nextFocus = index;

    while (true) {
      // Out of range
      if (direction === 'next' && nextFocus === filteredOptions.length || direction === 'previous' && nextFocus === -1) {
        return -1;
      }

      var option = listboxRef.current.querySelector("[data-option-index=\"".concat(nextFocus, "\"]")); // Same logic as MenuList.js

      var nextFocusDisabled = disabledItemsFocusable ? false : !option || option.disabled || option.getAttribute('aria-disabled') === 'true';

      if (option && !option.hasAttribute('tabindex') || nextFocusDisabled) {
        // Move to the next element.
        nextFocus += direction === 'next' ? 1 : -1;
      } else {
        return nextFocus;
      }
    }
  }

  var setHighlightedIndex = useEventCallback(function (_ref2) {
    var event = _ref2.event,
        index = _ref2.index,
        _ref2$reason = _ref2.reason,
        reason = _ref2$reason === void 0 ? 'auto' : _ref2$reason;
    highlightedIndexRef.current = index; // does the index exist?

    if (index === -1) {
      inputRef.current.removeAttribute('aria-activedescendant');
    } else {
      inputRef.current.setAttribute('aria-activedescendant', "".concat(id, "-option-").concat(index));
    }

    if (onHighlightChange) {
      onHighlightChange(event, index === -1 ? null : filteredOptions[index], reason);
    }

    if (!listboxRef.current) {
      return;
    }

    var prev = listboxRef.current.querySelector('[role="option"].Mui-focused');

    if (prev) {
      prev.classList.remove('Mui-focused');
      prev.classList.remove('Mui-focusVisible');
    }

    var listboxNode = listboxRef.current.parentElement.querySelector('[role="listbox"]'); // "No results"

    if (!listboxNode) {
      return;
    }

    if (index === -1) {
      listboxNode.scrollTop = 0;
      return;
    }

    var option = listboxRef.current.querySelector("[data-option-index=\"".concat(index, "\"]"));

    if (!option) {
      return;
    }

    option.classList.add('Mui-focused');

    if (reason === 'keyboard') {
      option.classList.add('Mui-focusVisible');
    } // Scroll active descendant into view.
    // Logic copied from https://www.w3.org/TR/wai-aria-practices/examples/listbox/js/listbox.js
    //
    // Consider this API instead once it has a better browser support:
    // .scrollIntoView({ scrollMode: 'if-needed', block: 'nearest' });

    if (listboxNode.scrollHeight > listboxNode.clientHeight && reason !== 'mouse') {
      var element = option;
      var scrollBottom = listboxNode.clientHeight + listboxNode.scrollTop;
      var elementBottom = element.offsetTop + element.offsetHeight;

      if (elementBottom > scrollBottom) {
        listboxNode.scrollTop = elementBottom - listboxNode.clientHeight;
      } else if (element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0) < listboxNode.scrollTop) {
        listboxNode.scrollTop = element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0);
      }
    }
  });
  var changeHighlightedIndex = useEventCallback(function (_ref3) {
    var event = _ref3.event,
        diff = _ref3.diff,
        _ref3$direction = _ref3.direction,
        direction = _ref3$direction === void 0 ? 'next' : _ref3$direction,
        _ref3$reason = _ref3.reason,
        reason = _ref3$reason === void 0 ? 'auto' : _ref3$reason;

    if (!popupOpen) {
      return;
    }

    var getNextIndex = function getNextIndex() {
      var maxIndex = filteredOptions.length - 1;

      if (diff === 'reset') {
        return defaultHighlighted;
      }

      if (diff === 'start') {
        return 0;
      }

      if (diff === 'end') {
        return maxIndex;
      }

      var newIndex = highlightedIndexRef.current + diff;

      if (newIndex < 0) {
        if (newIndex === -1 && includeInputInList) {
          return -1;
        }

        if (disableListWrap && highlightedIndexRef.current !== -1 || Math.abs(diff) > 1) {
          return 0;
        }

        return maxIndex;
      }

      if (newIndex > maxIndex) {
        if (newIndex === maxIndex + 1 && includeInputInList) {
          return -1;
        }

        if (disableListWrap || Math.abs(diff) > 1) {
          return maxIndex;
        }

        return 0;
      }

      return newIndex;
    };

    var nextIndex = validOptionIndex(getNextIndex(), direction);
    setHighlightedIndex({
      index: nextIndex,
      reason: reason,
      event: event
    }); // Sync the content of the input with the highlighted option.

    if (autoComplete && diff !== 'reset') {
      if (nextIndex === -1) {
        inputRef.current.value = inputValue;
      } else {
        var option = getOptionLabel(filteredOptions[nextIndex]);
        inputRef.current.value = option; // The portion of the selected suggestion that has not been typed by the user,
        // a completion string, appears inline after the input cursor in the textbox.

        var index = option.toLowerCase().indexOf(inputValue.toLowerCase());

        if (index === 0 && inputValue.length > 0) {
          inputRef.current.setSelectionRange(inputValue.length, option.length);
        }
      }
    }
  });
  var syncHighlightedIndex = React.useCallback(function () {
    if (!popupOpen) {
      return;
    }

    var valueItem = multiple ? value[0] : value; // The popup is empty, reset

    if (filteredOptions.length === 0 || valueItem == null) {
      changeHighlightedIndex({
        diff: 'reset'
      });
      return;
    }

    if (!listboxRef.current) {
      return;
    } // Synchronize the value with the highlighted index

    if (valueItem != null) {
      var currentOption = filteredOptions[highlightedIndexRef.current]; // Keep the current highlighted index if possible

      if (multiple && currentOption && findIndex(value, function (val) {
        return isOptionEqualToValue(currentOption, val);
      }) !== -1) {
        return;
      }

      var itemIndex = findIndex(filteredOptions, function (optionItem) {
        return isOptionEqualToValue(optionItem, valueItem);
      });

      if (itemIndex === -1) {
        changeHighlightedIndex({
          diff: 'reset'
        });
      } else {
        setHighlightedIndex({
          index: itemIndex
        });
      }

      return;
    } // Prevent the highlighted index to leak outside the boundaries.

    if (highlightedIndexRef.current >= filteredOptions.length - 1) {
      setHighlightedIndex({
        index: filteredOptions.length - 1
      });
      return;
    } // Restore the focus to the previous index.

    setHighlightedIndex({
      index: highlightedIndexRef.current
    }); // Ignore filteredOptions (and options, isOptionEqualToValue, getOptionLabel) not to break the scroll position
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [// Only sync the highlighted index when the option switch between empty and not
  filteredOptions.length, // Don't sync the highlighted index with the value when multiple
  // eslint-disable-next-line react-hooks/exhaustive-deps
  multiple ? false : value, filterSelectedOptions, changeHighlightedIndex, setHighlightedIndex, popupOpen, inputValue, multiple]);
  var handleListboxRef = useEventCallback(function (node) {
    setRef(listboxRef, node);

    if (!node) {
      return;
    }

    syncHighlightedIndex();
  });

  if (process.env.NODE_ENV !== 'production') {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    React.useEffect(function () {
      if (!inputRef.current || inputRef.current.nodeName !== 'INPUT') {
        console.error(["Material-UI: Unable to find the input element. It was resolved to ".concat(inputRef.current, " while an HTMLInputElement was expected."), "Instead, ".concat(componentName, " expects an input element."), '', componentName === 'useAutocomplete' ? 'Make sure you have binded getInputProps correctly and that the normal ref/effect resolutions order is guaranteed.' : 'Make sure you have customized the input component correctly.'].join('\n'));
      }
    }, [componentName]);
  }

  React.useEffect(function () {
    syncHighlightedIndex();
  }, [syncHighlightedIndex]);

  var handleOpen = function handleOpen(event) {
    if (open) {
      return;
    }

    setOpenState(true);
    setInputPristine(true);

    if (onOpen) {
      onOpen(event);
    }
  };

  var handleClose = function handleClose(event, reason) {
    if (!open) {
      return;
    }

    setOpenState(false);

    if (onClose) {
      onClose(event, reason);
    }
  };

  var handleValue = function handleValue(event, newValue, reason, details) {
    if (value === newValue) {
      return;
    }

    if (onChange) {
      onChange(event, newValue, reason, details);
    }

    setValueState(newValue);
  };

  var isTouch = React.useRef(false);

  var selectNewValue = function selectNewValue(event, option) {
    var reasonProp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'selectOption';
    var origin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'options';
    var reason = reasonProp;
    var newValue = option;

    if (multiple) {
      newValue = Array.isArray(value) ? value.slice() : [];

      if (process.env.NODE_ENV !== 'production') {
        var matches = newValue.filter(function (val) {
          return isOptionEqualToValue(option, val);
        });

        if (matches.length > 1) {
          console.error(["Material-UI: The `isOptionEqualToValue` method of ".concat(componentName, " do not handle the arguments correctly."), "The component expects a single value to match a given option but found ".concat(matches.length, " matches.")].join('\n'));
        }
      }

      var itemIndex = findIndex(newValue, function (valueItem) {
        return isOptionEqualToValue(option, valueItem);
      });

      if (itemIndex === -1) {
        newValue.push(option);
      } else if (origin !== 'freeSolo') {
        newValue.splice(itemIndex, 1);
        reason = 'removeOption';
      }
    }

    resetInputValue(event, newValue);
    handleValue(event, newValue, reason, {
      option: option
    });

    if (!disableCloseOnSelect && !event.ctrlKey && !event.metaKey) {
      handleClose(event, reason);
    }

    if (blurOnSelect === true || blurOnSelect === 'touch' && isTouch.current || blurOnSelect === 'mouse' && !isTouch.current) {
      inputRef.current.blur();
    }
  };

  function validTagIndex(index, direction) {
    if (index === -1) {
      return -1;
    }

    var nextFocus = index;

    while (true) {
      // Out of range
      if (direction === 'next' && nextFocus === value.length || direction === 'previous' && nextFocus === -1) {
        return -1;
      }

      var option = anchorEl.querySelector("[data-tag-index=\"".concat(nextFocus, "\"]")); // Same logic as MenuList.js

      if (!option || !option.hasAttribute('tabindex') || option.disabled || option.getAttribute('aria-disabled') === 'true') {
        nextFocus += direction === 'next' ? 1 : -1;
      } else {
        return nextFocus;
      }
    }
  }

  var handleFocusTag = function handleFocusTag(event, direction) {
    if (!multiple) {
      return;
    }

    handleClose(event, 'toggleInput');
    var nextTag = focusedTag;

    if (focusedTag === -1) {
      if (inputValue === '' && direction === 'previous') {
        nextTag = value.length - 1;
      }
    } else {
      nextTag += direction === 'next' ? 1 : -1;

      if (nextTag < 0) {
        nextTag = 0;
      }

      if (nextTag === value.length) {
        nextTag = -1;
      }
    }

    nextTag = validTagIndex(nextTag, direction);
    setFocusedTag(nextTag);
    focusTag(nextTag);
  };

  var handleClear = function handleClear(event) {
    ignoreFocus.current = true;
    setInputValueState('');

    if (onInputChange) {
      onInputChange(event, '', 'clear');
    }

    handleValue(event, multiple ? [] : null, 'clear');
  };

  var handleKeyDown = function handleKeyDown(other) {
    return function (event) {
      if (other.onKeyDown) {
        other.onKeyDown(event);
      }

      if (event.defaultMuiPrevented) {
        return;
      }

      if (focusedTag !== -1 && ['ArrowLeft', 'ArrowRight'].indexOf(event.key) === -1) {
        setFocusedTag(-1);
        focusTag(-1);
      } // Wait until IME is settled.

      if (event.which !== 229) {
        switch (event.key) {
          case 'Home':
            if (popupOpen && handleHomeEndKeys) {
              // Prevent scroll of the page
              event.preventDefault();
              changeHighlightedIndex({
                diff: 'start',
                direction: 'next',
                reason: 'keyboard',
                event: event
              });
            }

            break;

          case 'End':
            if (popupOpen && handleHomeEndKeys) {
              // Prevent scroll of the page
              event.preventDefault();
              changeHighlightedIndex({
                diff: 'end',
                direction: 'previous',
                reason: 'keyboard',
                event: event
              });
            }

            break;

          case 'PageUp':
            // Prevent scroll of the page
            event.preventDefault();
            changeHighlightedIndex({
              diff: -pageSize,
              direction: 'previous',
              reason: 'keyboard',
              event: event
            });
            handleOpen(event);
            break;

          case 'PageDown':
            // Prevent scroll of the page
            event.preventDefault();
            changeHighlightedIndex({
              diff: pageSize,
              direction: 'next',
              reason: 'keyboard',
              event: event
            });
            handleOpen(event);
            break;

          case 'ArrowDown':
            // Prevent cursor move
            event.preventDefault();
            changeHighlightedIndex({
              diff: 1,
              direction: 'next',
              reason: 'keyboard',
              event: event
            });
            handleOpen(event);
            break;

          case 'ArrowUp':
            // Prevent cursor move
            event.preventDefault();
            changeHighlightedIndex({
              diff: -1,
              direction: 'previous',
              reason: 'keyboard',
              event: event
            });
            handleOpen(event);
            break;

          case 'ArrowLeft':
            handleFocusTag(event, 'previous');
            break;

          case 'ArrowRight':
            handleFocusTag(event, 'next');
            break;

          case 'Enter':
            if (highlightedIndexRef.current !== -1 && popupOpen) {
              var option = filteredOptions[highlightedIndexRef.current];
              var disabled = getOptionDisabled ? getOptionDisabled(option) : false; // Avoid early form validation, let the end-users continue filling the form.

              event.preventDefault();

              if (disabled) {
                return;
              }

              selectNewValue(event, option, 'selectOption'); // Move the selection to the end.

              if (autoComplete) {
                inputRef.current.setSelectionRange(inputRef.current.value.length, inputRef.current.value.length);
              }
            } else if (freeSolo && inputValue !== '' && inputValueIsSelectedValue === false) {
              if (multiple) {
                // Allow people to add new values before they submit the form.
                event.preventDefault();
              }

              selectNewValue(event, inputValue, 'createOption', 'freeSolo');
            }

            break;

          case 'Escape':
            if (popupOpen) {
              // Avoid Opera to exit fullscreen mode.
              event.preventDefault(); // Avoid the Modal to handle the event.

              event.stopPropagation();
              handleClose(event, 'escape');
            } else if (clearOnEscape && (inputValue !== '' || multiple && value.length > 0)) {
              // Avoid Opera to exit fullscreen mode.
              event.preventDefault(); // Avoid the Modal to handle the event.

              event.stopPropagation();
              handleClear(event);
            }

            break;

          case 'Backspace':
            if (multiple && inputValue === '' && value.length > 0) {
              var index = focusedTag === -1 ? value.length - 1 : focusedTag;
              var newValue = value.slice();
              newValue.splice(index, 1);
              handleValue(event, newValue, 'removeOption', {
                option: value[index]
              });
            }

            break;

          default:
        }
      }
    };
  };

  var handleFocus = function handleFocus(event) {
    setFocused(true);

    if (openOnFocus && !ignoreFocus.current) {
      handleOpen(event);
    }
  };

  var handleBlur = function handleBlur(event) {
    // Ignore the event when using the scrollbar with IE11
    if (listboxRef.current !== null && listboxRef.current.parentElement.contains(document.activeElement)) {
      inputRef.current.focus();
      return;
    }

    setFocused(false);
    firstFocus.current = true;
    ignoreFocus.current = false;

    if (autoSelect && highlightedIndexRef.current !== -1 && popupOpen) {
      selectNewValue(event, filteredOptions[highlightedIndexRef.current], 'blur');
    } else if (autoSelect && freeSolo && inputValue !== '') {
      selectNewValue(event, inputValue, 'blur', 'freeSolo');
    } else if (clearOnBlur) {
      resetInputValue(event, value);
    }

    handleClose(event, 'blur');
  };

  var handleInputChange = function handleInputChange(event) {
    var newValue = event.target.value;

    if (inputValue !== newValue) {
      setInputValueState(newValue);
      setInputPristine(false);

      if (onInputChange) {
        onInputChange(event, newValue, 'input');
      }
    }

    if (newValue === '') {
      if (!disableClearable && !multiple) {
        handleValue(event, null, 'clear');
      }
    } else {
      handleOpen(event);
    }
  };

  var handleOptionMouseOver = function handleOptionMouseOver(event) {
    setHighlightedIndex({
      event: event,
      index: Number(event.currentTarget.getAttribute('data-option-index')),
      reason: 'mouse'
    });
  };

  var handleOptionTouchStart = function handleOptionTouchStart() {
    isTouch.current = true;
  };

  var handleOptionClick = function handleOptionClick(event) {
    var index = Number(event.currentTarget.getAttribute('data-option-index'));
    selectNewValue(event, filteredOptions[index], 'selectOption');
    isTouch.current = false;
  };

  var handleTagDelete = function handleTagDelete(index) {
    return function (event) {
      var newValue = value.slice();
      newValue.splice(index, 1);
      handleValue(event, newValue, 'removeOption', {
        option: value[index]
      });
    };
  };

  var handlePopupIndicator = function handlePopupIndicator(event) {
    if (open) {
      handleClose(event, 'toggleInput');
    } else {
      handleOpen(event);
    }
  }; // Prevent input blur when interacting with the combobox

  var handleMouseDown = function handleMouseDown(event) {
    if (event.target.getAttribute('id') !== id) {
      event.preventDefault();
    }
  }; // Focus the input when interacting with the combobox

  var handleClick = function handleClick() {
    inputRef.current.focus();

    if (selectOnFocus && firstFocus.current && inputRef.current.selectionEnd - inputRef.current.selectionStart === 0) {
      inputRef.current.select();
    }

    firstFocus.current = false;
  };

  var handleInputMouseDown = function handleInputMouseDown(event) {
    if (inputValue === '' || !open) {
      handlePopupIndicator(event);
    }
  };

  var dirty = freeSolo && inputValue.length > 0;
  dirty = dirty || (multiple ? value.length > 0 : value !== null);
  var groupedOptions = filteredOptions;

  if (groupBy) {
    // used to keep track of key and indexes in the result array
    var indexBy = new Map();
    var warn = false;
    groupedOptions = filteredOptions.reduce(function (acc, option, index) {
      var group = groupBy(option);

      if (acc.length > 0 && acc[acc.length - 1].group === group) {
        acc[acc.length - 1].options.push(option);
      } else {
        if (process.env.NODE_ENV !== 'production') {
          if (indexBy.get(group) && !warn) {
            console.warn("Material-UI: The options provided combined with the `groupBy` method of ".concat(componentName, " returns duplicated headers."), 'You can solve the issue by sorting the options with the output of `groupBy`.');
            warn = true;
          }

          indexBy.set(group, true);
        }

        acc.push({
          key: index,
          index: index,
          group: group,
          options: [option]
        });
      }

      return acc;
    }, []);
  }

  return {
    getRootProps: function getRootProps() {
      var other = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      return _extends({
        'aria-owns': listboxAvailable ? "".concat(id, "-listbox") : null,
        role: 'combobox',
        'aria-expanded': listboxAvailable
      }, other, {
        onKeyDown: handleKeyDown(other),
        onMouseDown: handleMouseDown,
        onClick: handleClick
      });
    },
    getInputLabelProps: function getInputLabelProps() {
      return {
        id: "".concat(id, "-label"),
        htmlFor: id
      };
    },
    getInputProps: function getInputProps() {
      return {
        id: id,
        value: inputValue,
        onBlur: handleBlur,
        onFocus: handleFocus,
        onChange: handleInputChange,
        onMouseDown: handleInputMouseDown,
        // if open then this is handled imperativeley so don't let react override
        // only have an opinion about this when closed
        'aria-activedescendant': popupOpen ? '' : null,
        'aria-autocomplete': autoComplete ? 'both' : 'list',
        'aria-controls': listboxAvailable ? "".concat(id, "-listbox") : null,
        // Disable browser's suggestion that might overlap with the popup.
        // Handle autocomplete but not autofill.
        autoComplete: 'off',
        ref: inputRef,
        autoCapitalize: 'none',
        spellCheck: 'false'
      };
    },
    getClearProps: function getClearProps() {
      return {
        tabIndex: -1,
        onClick: handleClear
      };
    },
    getPopupIndicatorProps: function getPopupIndicatorProps() {
      return {
        tabIndex: -1,
        onClick: handlePopupIndicator
      };
    },
    getTagProps: function getTagProps(_ref4) {
      var index = _ref4.index;
      return {
        key: index,
        'data-tag-index': index,
        tabIndex: -1,
        onDelete: handleTagDelete(index)
      };
    },
    getListboxProps: function getListboxProps() {
      return {
        role: 'listbox',
        id: "".concat(id, "-listbox"),
        'aria-labelledby': "".concat(id, "-label"),
        ref: handleListboxRef,
        onMouseDown: function onMouseDown(event) {
          // Prevent blur
          event.preventDefault();
        }
      };
    },
    getOptionProps: function getOptionProps(_ref5) {
      var index = _ref5.index,
          option = _ref5.option;
      var selected = (multiple ? value : [value]).some(function (value2) {
        return value2 != null && isOptionEqualToValue(option, value2);
      });
      var disabled = getOptionDisabled ? getOptionDisabled(option) : false;
      return {
        key: getOptionLabel(option),
        tabIndex: -1,
        role: 'option',
        id: "".concat(id, "-option-").concat(index),
        onMouseOver: handleOptionMouseOver,
        onClick: handleOptionClick,
        onTouchStart: handleOptionTouchStart,
        'data-option-index': index,
        'aria-disabled': disabled,
        'aria-selected': selected
      };
    },
    id: id,
    inputValue: inputValue,
    value: value,
    dirty: dirty,
    popupOpen: popupOpen,
    focused: focused || focusedTag !== -1,
    anchorEl: anchorEl,
    setAnchorEl: setAnchorEl,
    focusedTag: focusedTag,
    groupedOptions: groupedOptions
  };
}


text:
package controllers

import (
	"net/http"

	"github.com/vmware/harbor/src/common/dao"
	"github.com/vmware/harbor/src/common/models"
	"github.com/vmware/harbor/src/common/utils/log"
)

// NavigationHeaderController handles requests to /navigation_header
type NavigationHeaderController struct {
	BaseController
}

// Get renders user's navigation header
func (nhc *NavigationHeaderController) Get() {
	sessionUserID := nhc.GetSession("userId")
	var hasLoggedIn bool
	var isAdmin int
	if sessionUserID != nil {
		hasLoggedIn = true
		userID := sessionUserID.(int)
		u, err := dao.GetUser(models.User{UserID: userID})
		if err != nil {
			log.Errorf("Error occurred in GetUser, error: %v", err)
			nhc.CustomAbort(http.StatusInternalServerError, "Internal error.")
		}
		if u == nil {
			log.Warningf("User was deleted already, user id: %d, canceling request.", userID)
			nhc.CustomAbort(http.StatusUnauthorized, "")
		}
		isAdmin = u.HasAdminRole
	}
	nhc.Data["HasLoggedIn"] = hasLoggedIn
	nhc.Data["IsAdmin"] = isAdmin
	nhc.TplName = "navigation-header.htm"
	nhc.Render()
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @category   ZFDebug
 * @package    ZFDebug_Controller
 * @subpackage Plugins
 * @copyright  Copyright (c) 2008-2009 ZF Debug Bar Team (http://code.google.com/p/zfdebug)
 * @license    http://code.google.com/p/zfdebug/wiki/License     New BSD License
 */
class ZFDebug_Controller_Plugin_Debug_Plugin_Variables extends ZFDebug_Controller_Plugin_Debug_Plugin implements ZFDebug_Controller_Plugin_Debug_Plugin_Interface
{
    /**
     * Contains plugin identifier name
     *
     * @var string
     */
    protected $_identifier = 'variables';

    /**
     * @var Zend_Controller_Request_Abstract
     */
    protected $_request;

    /**
     * Create ZFDebug_Controller_Plugin_Debug_Plugin_Variables
     *
     * @return void
     */
    public function __construct()
    {

    }

    /**
     * Gets identifier for this plugin
     *
     * @return string
     */
    public function getIdentifier()
    {
        return $this->_identifier;
    }

    /**
     * Returns the base64 encoded icon
     *
     * @return string
     **/
    public function getIconData()
    {
        return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAFWSURBVBgZBcE/SFQBAAfg792dppJeEhjZn80MChpqdQ2iscmlscGi1nBPaGkviKKhONSpvSGHcCrBiDDjEhOC0I68sjvf+/V9RQCsLHRu7k0yvtN8MTMPICJieaLVS5IkafVeTkZEFLGy0JndO6vWNGVafPJVh2p8q/lqZl60DpIkaWcpa1nLYtpJkqR1EPVLz+pX4rj47FDbD2NKJ1U+6jTeTRdL/YuNrkLdhhuAZVP6ukqbh7V0TzmtadSEDZXKhhMG7ekZl24jGDLgtwEd6+jbdWAAEY0gKsPO+KPy01+jGgqlUjTK4ZroK/UVKoeOgJ5CpRyq5e2qjhF1laAS8c+Ymk1ZrVXXt2+9+fJBYUwDpZ4RR7Wtf9u9m2tF8Hwi9zJ3/tg5pW2FHVv7eZJHd75TBPD0QuYze7n4Zdv+ch7cfg8UAcDjq7mfwTycew1AEQAAAMB/0x+5JQ3zQMYAAAAASUVORK5CYII=';
    }

    /**
     * Gets menu tab for the Debugbar
     *
     * @return string
     */
    public function getTab()
    {
        return ' Variables';
    }

    /**
     * Gets content panel for the Debugbar
     *
     * @return string
     */
    public function getPanel()
    {
        $this->_request = Zend_Controller_Front::getInstance()->getRequest();
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
        if ($viewRenderer->view && method_exists($viewRenderer->view, 'getVars')) {
            $viewVars = $this->_cleanData($viewRenderer->view->getVars());
        } else {
            $viewVars = "No 'getVars()' method in view class";
        }
        $vars = '';
        if ($this->_request->isPost())
        {
            $vars .= '
$_POST
'
            . '
' . $this->_cleanData($this->_request->getPost()) . '
';
        }

        $vars .= '
$_COOKIE
'
        . '
' . $this->_cleanData($this->_request->getCookie()) . '
'
        . '
Request
'
        . '
' . $this->_cleanData($this->_request->getParams()) . '
'
        . '
View vars
'
        . '
' . $viewVars . '
';
        return $vars;
    }

}


text:
<html>
<head>
    <title>Iframe Client</title>

    <script src="../config.js"></script>
    <script type="text/javascript">loadHub_dirDepth="2";</script>
    <script src="../util/loadHub.js"></script>

    <script src="../util/test_hub.js"></script>

    <script type="text/javascript">
        var hubClient = null;

        function init()
        {
            new TestHubClient( "iframe", function( test ) {

                hubClient = new OpenAjax.hub.IframeHubClient({
                      HubClient: {
                          onSecurityAlert: function() {},
                          log: test.log
                      }
                });
                hubClient.connect( function() {
                    var sid = hubClient.subscribe( "test.iframe", function() {} );
                    test.onMsg = function( data ) {
                        if ( data == "unsubscribe" ) {
                            hubClient.unsubscribe( sid );
                        }
                    };
                });

            });
        }
    </script>
</head>

<body onload="init();">
</body>
</html>


text:
package com.teamname.goaton.client;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.gwt.GwtApplication;
import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration;
import com.teamname.goaton.MainGame;

public class HtmlLauncher extends GwtApplication {

        @Override
        public GwtApplicationConfiguration getConfig () {
                return new GwtApplicationConfiguration(800, 800);
        }

        @Override
        public ApplicationListener createApplicationListener () {
                return new MainGame();
        }
}


text:
#include "main-font-text.hh"
#include "shape-consumer.hh"

struct output_buffer_t
{
  output_buffer_t (option_parser_t *parser)
		  : options (parser, hb_buffer_serialize_list_formats ()),
		    format (parser),
		    gs (nullptr),
		    line_no (0),
		    font (nullptr),
		    output_format (HB_BUFFER_SERIALIZE_FORMAT_INVALID),
		    format_flags (HB_BUFFER_SERIALIZE_FLAG_DEFAULT) {}

  void init (hb_buffer_t *buffer, const font_options_t *font_opts)
  {
    options.get_file_handle ();
    gs = g_string_new (nullptr);
    line_no = 0;
    font = hb_font_reference (font_opts->get_font ());

    if (!options.output_format)
      output_format = HB_BUFFER_SERIALIZE_FORMAT_TEXT;
    else
      output_format = hb_buffer_serialize_format_from_string (options.output_format, -1);
    /* An empty "output_format" parameter basically skips output generating.
     * Useful for benchmarking. */
    if ((!options.output_format || *options.output_format) &&
	!hb_buffer_serialize_format_to_string (output_format))
    {
      if (options.explicit_output_format)
	fail (false, "Unknown output format `%s'; supported formats are: %s",
	      options.output_format,
	      g_strjoinv ("/", const_cast<char**> (options.supported_formats)));
      else
	/* Just default to TEXT if not explicitly requested and the
	 * file extension is not recognized. */
	output_format = HB_BUFFER_SERIALIZE_FORMAT_TEXT;
    }

    unsigned int flags = HB_BUFFER_SERIALIZE_FLAG_DEFAULT;
    if (!format.show_glyph_names)
      flags |= HB_BUFFER_SERIALIZE_FLAG_NO_GLYPH_NAMES;
    if (!format.show_clusters)
      flags |= HB_BUFFER_SERIALIZE_FLAG_NO_CLUSTERS;
    if (!format.show_positions)
      flags |= HB_BUFFER_SERIALIZE_FLAG_NO_POSITIONS;
    if (!format.show_advances)
      flags |= HB_BUFFER_SERIALIZE_FLAG_NO_ADVANCES;
    if (format.show_extents)
      flags |= HB_BUFFER_SERIALIZE_FLAG_GLYPH_EXTENTS;
    if (format.show_flags)
      flags |= HB_BUFFER_SERIALIZE_FLAG_GLYPH_FLAGS;
    format_flags = (hb_buffer_serialize_flags_t) flags;

    if (format.trace)
      hb_buffer_set_message_func (buffer, message_func, this, nullptr);
  }
  void new_line () { line_no++; }
  void consume_text (hb_buffer_t  *buffer,
		     const char   *text,
		     unsigned int  text_len,
		     hb_bool_t     utf8_clusters)
  {
    g_string_set_size (gs, 0);
    format.serialize_buffer_of_text (buffer, line_no, text, text_len, font, gs);
    fprintf (options.fp, "%s", gs->str);
  }
  void error (const char *message)
  {
    g_string_set_size (gs, 0);
    format.serialize_message (line_no, "error", message, gs);
    fprintf (options.fp, "%s", gs->str);
  }
  void consume_glyphs (hb_buffer_t  *buffer,
		       const char   *text,
		       unsigned int  text_len,
		       hb_bool_t     utf8_clusters)
  {
    g_string_set_size (gs, 0);
    format.serialize_buffer_of_glyphs (buffer, line_no, text, text_len, font,
				       output_format, format_flags, gs);
    fprintf (options.fp, "%s", gs->str);
  }
  void finish (hb_buffer_t *buffer, const font_options_t *font_opts)
  {
    hb_buffer_set_message_func (buffer, nullptr, nullptr, nullptr);
    hb_font_destroy (font);
    g_string_free (gs, true);
    gs = nullptr;
    font = nullptr;
  }

  static hb_bool_t
  message_func (hb_buffer_t *buffer,
		hb_font_t *font,
		const char *message,
		void *user_data)
  {
    output_buffer_t *that = (output_buffer_t *) user_data;
    that->trace (buffer, font, message);
    return true;
  }

  void
  trace (hb_buffer_t *buffer,
	 hb_font_t *font,
	 const char *message)
  {
    g_string_set_size (gs, 0);
    format.serialize_line_no (line_no, gs);
    g_string_append_printf (gs, "trace: %s	buffer: ", message);
    format.serialize_glyphs (buffer, font, output_format, format_flags, gs);
    g_string_append_c (gs, '\n');
    fprintf (options.fp, "%s", gs->str);
  }

  protected:
  output_options_t options;
  format_options_t format;

  GString *gs;
  unsigned int line_no;
  hb_font_t *font;
  hb_buffer_serialize_format_t output_format;
  hb_buffer_serialize_flags_t format_flags;
};

int
main (int argc, char **argv)
{
  if (argc == 2 && !strcmp (argv[1], "--batch"))
  {
    unsigned int ret = 0;
    char buf[4092];
    while (fgets (buf, sizeof (buf), stdin))
    {
      size_t l = strlen (buf);
      if (l && buf[l - 1] == '\n') buf[l - 1] = '\0';
      main_font_text_t<shape_consumer_t<output_buffer_t>, FONT_SIZE_UPEM, 0> driver;
      char *args[32];
      argc = 0;
      char *p = buf, *e;
      args[argc++] = p;
      unsigned start_offset = 0;
      while ((e = strchr (p + start_offset, ':')) && argc < (int) ARRAY_LENGTH (args))
      {
	*e++ = '\0';
	while (*e == ':')
	  e++;
	args[argc++] = p = e;
	/* Skip 2 first bytes on first argument if is Windows path, "C:\..." */
	start_offset = argc == 2 && p[0] != '\0' && p[0] != ':' && p[1] == ':' && (p[2] == '\\' || p[2] == '/') ? 2 : 0;
      }
      ret |= driver.main (argc, args);
      fflush (stdout);

      if (ret)
	break;
    }
    return ret;
  }
  main_font_text_t<shape_consumer_t<output_buffer_t>, FONT_SIZE_UPEM, 0> driver;
  return driver.main (argc, argv);
}


text:
module Compass
  module Stats
    class StatsVisitor
      attr_accessor :rule_count, :prop_count, :mixin_def_count, :mixin_count
      def initialize
        self.rule_count = 0
        self.prop_count = 0
        self.mixin_def_count = 0
        self.mixin_count = 0
      end
      def visit(node)
        self.prop_count += 1 if node.is_a?(Sass::Tree::PropNode) && !node.children.any?
        if node.is_a?(Sass::Tree::RuleNode)
          self.rule_count += node.rule.reject{|r| r.is_a?(Sass::Script::Node)}.map{|r| r.split(/,/)}.flatten.compact.size
        end
        self.mixin_def_count += 1 if node.is_a?(Sass::Tree::MixinDefNode)
        self.mixin_count += 1 if node.is_a?(Sass::Tree::MixinNode)
      end
      def up(node)
      end
      def down(node)
      end
      def import?(node)
        return false
        full_filename = node.send(:import)
        full_filename != Compass.deprojectize(full_filename)
      end
    end
    class CssFile
      attr_accessor :path, :css
      attr_accessor :selector_count, :prop_count
      attr_accessor :file_size
      def initialize(path)
        require 'css_parser'
        self.path = path
        self.css = CssParser::Parser.new
        self.css.add_block!(contents)
        self.selector_count = 0
        self.prop_count = 0
      end
      def contents
        @contents ||= File.read(path)
      end
      def lines
        contents.inject(0){|m,c| m + 1 }
      end
      def analyze!
        self.file_size = File.size(path)
        css.each_selector do |selector, declarations, specificity|
          sels = selector.split(/,/).size
          props = declarations.split(/;/).size
          self.selector_count += sels
          self.prop_count += props
        end
      end
    end
    class SassFile
      attr_accessor :path
      attr_reader :visitor
      attr_accessor :file_size

      def initialize(path)
        self.path = path
      end
      def contents
        @contents ||= File.read(path)
      end
      def tree
        opts = Compass.configuration.to_sass_engine_options
        opts[:syntax] = path[-4..-1].to_sym
        @tree = Sass::Engine.new(contents, opts).to_tree
      end
      def visit_tree!
        @visitor = StatsVisitor.new
        tree.visit_depth_first(@visitor)
        @visitor
      end
      def analyze!
        self.file_size = File.size(path)
        visit_tree!
      end
      def lines
        contents.inject(0){|m,c| m + 1 }
      end
      def rule_count
        visitor.rule_count
      end
      def prop_count
        visitor.prop_count
      end
      def mixin_def_count
        visitor.mixin_def_count
      end
      def mixin_count
        visitor.mixin_count
      end
    end
  end
end


text:
import JelObject from '../JelObject';
import Runtime from '../Runtime';
import SerializablePrimitive from '../SerializablePrimitive';
import BaseTypeRegistry from '../BaseTypeRegistry';
import Context from '../Context';
import Float from './Float';
import JelString from './JelString';
import List from './List';
import NativeJelObject from './NativeJelObject';
import Class from './Class';
import JelBoolean from './JelBoolean';
import TypeChecker from './TypeChecker';
import Callable from '../Callable';
import Util from '../../util/Util';

const LIST_OR_DICTIONARY = ['List', 'Dictionary'];

/**
 * Dictionary is a map-like type for JEL.
 */
export default class Dictionary extends NativeJelObject implements SerializablePrimitive {
	elements: Map<string, JelObject|null>;

  static clazz: Class|undefined;

	static readonly empty_jel_property = true;
	static readonly empty = new Dictionary();

  defaultValue_jel_property: boolean;

	constructor(elements?: any, keepMap = false, public defaultValue: JelObject|null = null) {
		super('Dictionary');
		if (keepMap && elements)
			this.elements = elements;
		else {
			this.elements = new Map();
			this.putAll(elements);
		}
	}

  get clazz(): Class {
    return Dictionary.clazz!;
  }

  static fromArray_jel_mapping = true;
  static fromArray(ctx: Context, keys: List, value: any) {
    const d = new Map();
    for (let key of keys.elements)
      d.set(TypeChecker.realString(key, 'keys'), value);
    return new Dictionary(d, true);
  }

	op(ctx: Context, operator: string, right: JelObject, isReversal: boolean = false): JelObject|Promise<JelObject> {
		if (right == null)
			return this;
		if (right instanceof Dictionary) {
			switch(operator) {
				case '==':
				case '===':
					if (this.elements.size != right.elements.size)
						return JelBoolean.FALSE;
					let result: JelBoolean | Promise<JelBoolean> = JelBoolean.TRUE;
					for (let key of this.elements.keys())
						if (!right.elements.has(key))
							return JelBoolean.FALSE;
						else
							result = JelBoolean.falsestWithPromises(ctx, result, Runtime.op(ctx, operator, this.elements.get(key) as JelObject, right.elements.get(key) as JelObject) as any);
					return result;
        case '+':
          return this.setAll(ctx, right);
        case '-':
          return this.deleteAll(ctx, right);
			}
		}
		return super.op(ctx, operator, right, isReversal);
	}

	singleOp(ctx: Context, operator: string): JelObject|Promise<JelObject> {
		if (operator == '!')
			return JelBoolean.valueOf(!this.elements.size);
		else
			return super.singleOp(ctx, operator);
	}

	get_jel_mapping: boolean;
	get(ctx: Context, key0: JelString | string): any {
		const key = TypeChecker.realString(key0, 'key');
		const v = this.elements.get(key);
		return v == undefined ? this.defaultValue : v;
	}

  withDefault_jel_mapping: boolean;
  withDefault(ctx: Context, defaultValue: JelObject|null): Dictionary {
    if (this.defaultValue === defaultValue)
      return this;
    return new Dictionary(this.elements, true, defaultValue);
  }

  member(ctx: Context, name: string): Promise<JelObject|null>|JelObject|null|undefined {
    const sm = super.member(ctx, name);
    if (sm !== undefined)
      return sm;
		return this.elements.get(name);
	}

	has_jel_mapping: boolean;
	has(ctx: Context, key0: JelString | string): JelBoolean {
		const key = TypeChecker.realString(key0, 'key');
		return JelBoolean.valueOf(this.elements.has(key));
	}

  set_jel_mapping: boolean;
  set(ctx: Context, key0: any, value: JelObject|null): Dictionary {
		const key = TypeChecker.realString(key0, 'key');
		const t = new Dictionary(this, false, this.defaultValue);
		t.elements.set(key, value);
		return t;
	}

  setAll_jel_mapping: boolean;
  setAll(ctx: Context, other0: any): Dictionary {
		const other = TypeChecker.optionalInstance(Dictionary, other0, 'other');
    return this.setAllJs(other);
  }

  setAllJs(other?: Dictionary): Dictionary {
    if (!other || other.isEmpty)
      return this;
    else if (this.isEmpty)
      return other;
    else
      return new Dictionary(this, false, this.defaultValue).putAll(other);
  }

  delete_jel_mapping: boolean;
  delete(ctx: Context, key0: any): Dictionary {
	  const key = TypeChecker.realString(key0, 'key');
    if (!key)
      return this;
    const d = new Dictionary(this, false, this.defaultValue);
    d.elements.delete(key);
    return d;
  }

  deleteAll_jel_mapping: boolean;
  deleteAll(ctx: Context, keys0: any): Dictionary {
	  const keys = TypeChecker.types(['Dictionary', 'List'], keys0, 'keys');
    if (this.isEmpty || keys.isEmpty)
      return this;
    const d = new Dictionary(this, false, this.defaultValue);
    if (keys instanceof Dictionary)
      keys.eachJs((key: string)=>d.elements.delete(key));
    else
      keys.elements.forEach((e: JelObject|null)=>d.elements.delete(TypeChecker.realString(e, 'list element')));
    return d;
  }

  // inline put, for JS only
	putAll(otherDict: any): Dictionary {
		if (!otherDict)
			return this;

		if (otherDict instanceof Map) {
			for (let key of otherDict.keys())
				this.elements.set(key, otherDict.get(key));
		}
		else if (otherDict instanceof Dictionary) {
 			this.putAll(otherDict.elements);
		}
		else if (Array.isArray(otherDict)) {
      if (Array.isArray(otherDict[0]))
        for (let i = 0; i < otherDict.length; i++)
          this.elements.set(otherDict[i][0] || '', otherDict[i][1]);
      else
        for (let i = 0; i < otherDict.length-1; i+=2)
          this.elements.set(otherDict[i] instanceof JelString ? otherDict[i].value : '', otherDict[i+1]);
		}
		else if (otherDict instanceof List) {
			this.putAll(otherDict.elements);
		}
		else if (typeof otherDict == 'object') {
			for (let key in otherDict)
				this.elements.set(key, otherDict[key]);
		}
		return this;
	}

  anyKey_jel_property: boolean;
	get anyKey(): string | null {
		if (this.elements.size)
			return this.elements.keys().next().value;
		else
			return null;
	}

  size_jel_property: boolean;
	get size(): number {
		return this.elements.size;
	}

  isEmpty_jel_property: boolean;
  get isEmpty(): boolean {
		return this.elements.size == 0;
	}

  keys_jel_property: boolean;
	get keys(): List {
		return new List(Array.from(this.elements.keys()).map(e=>JelString.valueOf(e)));
	}

	map_jel_mapping: boolean;
	map(ctx: Context, f0: any): Dictionary | Promise<Dictionary> {
		const f: Callable = TypeChecker.instance(Callable, f0, 'f');
    if (this.isEmpty)
      return this;

		const self = this;
		const newDict = new Dictionary(undefined, false, this.defaultValue);
		let i = 0;
		const it = this.elements.keys();
		function exec(): Promise<Dictionary> | Dictionary {
			while (true) {
				const next = it.next();
				if (next.done)
					return newDict;
				const r = f.invoke(undefined, JelString.valueOf(next.value), self.elements.get(next.value) || null, Float.valueOf(i));
				i++;
				if (r instanceof Promise)
					return r.then(v=> {
						newDict.elements.set(next.value, v);
						return exec();
					});
				else
					newDict.elements.set(next.value, r);
			}
		}
		return exec();
	}

	mapWithPromisesJs(f: (k: string, v: JelObject|null)=>JelObject|null|Promise<JelObject|null>): Promise<Dictionary> | Dictionary {
		const self = this;
		const newDict = new Dictionary(undefined, false, this.defaultValue);
		const it = this.elements.keys();
		function exec(): Promise<Dictionary> | Dictionary {
			while (true) {
				const next = it.next();
				if (next.done)
					return newDict;
				const r = f(next.value, self.elements.get(next.value) || null);
				if (r instanceof Promise)
					return r.then(v=> {
						newDict.elements.set(next.value, v);
						return exec();
					});
				else
					newDict.elements.set(next.value, r);
			}
		}
		return exec();
	}

  mapToList_jel_mapping: boolean;
	mapToList(ctx: Context, f0: any): List | Promise<List> {
		const f: Callable = TypeChecker.instance(Callable, f0, 'f');

    if (this.isEmpty)
      return List.empty;

		const self = this;
		const l: any[] = [];
		let i = 0;
		const it = this.elements.keys();
		function exec(): Promise<any[]> | any[] {
			while (true) {
				const next = it.next();
				if (next.done)
					return l;
				const r = f.invoke(undefined, JelString.valueOf(next.value), self.elements.get(next.value) || null, Float.valueOf(i));
				i++;
				if (r instanceof Promise)
					return r.then(v=> {
						l.push(v);
						return exec();
					});
				else
					l.push(r);
			}
		}
		return Util.resolveValue(exec(), l=>new List(l));
	}

	mapJs(f: (k: string, v: JelObject|null, i: number)=>JelObject|null): Dictionary {
		const self = this;
		const newDict = new Dictionary(undefined, false, this.defaultValue);
		let i = 0;
		const it = this.elements.keys();
		while (true) {
			const next = it.next();
			if (next.done)
				return newDict;
      const k = next.value;
	    newDict.elements.set(k, f(k, this.elements.get(next.value) as JelObject|null, i++));
		}
	}

 	mapToArrayJs(f: (k: string, v: JelObject|null, i: number)=>JelObject|null): any[] {
		const self = this;
		const l = [];
		let i = 0;
		const it = this.elements.keys();
		while (true) {
			const next = it.next();
			if (next.done)
				return l;
      const k = next.value;
	    l.push(f(k, this.elements.get(next.value) as JelObject|null, i++));
		}
	}

 	eachJs(f: (k: string, v: JelObject|null, i: number)=>any): Dictionary {
		const self = this;
		let i = 0;
		const it = this.elements.keys();
		while (true) {
			const next = it.next();
			if (next.done)
				return this;
			 f(next.value, this.elements.get(next.value) as JelObject|null, i++);
		}
	}

  duplicateKeysJs(other: Dictionary): string[] {
		const self = this;
		let i = 0;
    const d = [];
		for (let key of this.elements.keys())
      if (other.elements.has(key))
        d.push(key);
    return d;
	}

	filter_jel_mapping: boolean;
	filter(ctx: Context, f0: any): Dictionary | Promise<Dictionary> {
		const f: Callable = TypeChecker.instance(Callable, f0, 'f');
		const self = this;
		const newDict = new Dictionary(undefined, false, this.defaultValue);
		let i = 0;
		const it = this.elements.keys();
		function exec(): Promise<Dictionary> | Dictionary {
			while (true) {
				const next = it.next();
				if (next.done)
					return newDict;
				const thisValue = self.elements.get(next.value) as JelObject;
				const r = f.invoke(undefined, JelString.valueOf(next.value), thisValue, Float.valueOf(i));
				i++;
				if (r instanceof Promise)
					return r.then(v=> {
						if (JelBoolean.toRealBoolean(v))
							newDict.elements.set(next.value, thisValue);
						return exec();
					});
				else if (JelBoolean.toRealBoolean(r))
					newDict.elements.set(next.value, thisValue);
			}
		}
		return exec();
	}

 	filterJs(f: (key: string, value: JelObject|null)=>boolean): Dictionary {
		const newDict = new Dictionary(undefined, false, this.defaultValue);
		for (let key of this.elements.keys()) {
      const value = (this.elements.get(key)||null) as JelObject|null;
      if (f(key, value))
        newDict.elements.set(key, value);
    }
    return newDict;
	}

	reduce_jel_mapping: boolean;
	reduce(ctx: Context, f0: any, init: any = 0): any {
		const f: Callable = TypeChecker.instance(Callable, f0, 'f');

		const self = this;
		let result: any = init;
		let i = 0;
		const it = this.elements.keys();
		function exec(): Promise<Dictionary> | Dictionary {
			while (true) {
				const next = it.next();
				if (next.done)
					return result;
				const r = f.invoke(undefined, result, JelString.valueOf(next.value), self.elements.get(next.value) || null, Float.valueOf(i));
				i++;
				if (r instanceof Promise)
					return r.then(v=> {
						result = v;
						return exec();
					});
				else
					result = r;
			}
			return result;
		}
		return exec();
	}

	hasAny_jel_mapping: boolean;
	hasAny(ctx: Context, f0: any): JelBoolean | Promise<JelBoolean> {
		const f: Callable = TypeChecker.instance(Callable, f0, 'f');
		const self = this;
		let i = 0;
		const it = this.elements.keys();
		function exec(): Promise<JelBoolean> | JelBoolean {
			while (true) {
				const next = it.next();
				if (next.done)
					return JelBoolean.FALSE;
				const r = f.invoke(undefined, JelString.valueOf(next.value), self.elements.get(next.value) || null, Float.valueOf(i));
				i++;
				if (r instanceof Promise)
					return r.then(v=> JelBoolean.toRealBoolean(v) ? JelBoolean.TRUE : exec());
				else if (JelBoolean.toRealBoolean(r))
					return JelBoolean.TRUE;
			}
		}
		return exec();
	}

	hasAnyJs(f: (k: string, v: JelObject|null)=>boolean): boolean {
    for (let key of this.elements.keys())
      if (f(key, this.elements.get(key) || null))
        return true;
    return false;
	}

  findJs(f: (k: string, v: JelObject|null)=>boolean): any {
    for (let key of this.elements.keys())
      if (f(key, this.elements.get(key) || null))
        return key;
    return undefined;
	}

	hasOnly_jel_mapping: boolean;
	hasOnly(ctx: Context, f0: any): JelBoolean | Promise<JelBoolean> {
		const f: Callable = TypeChecker.instance(Callable, f0, 'f');

		const self = this;
		let i = 0;
		const it = this.elements.keys();
		function exec(): Promise<JelBoolean> | JelBoolean {
			while (true) {
				const next = it.next();
				if (next.done)
					return JelBoolean.TRUE;
				const r = f.invoke(undefined, JelString.valueOf(next.value), self.elements.get(next.value) || null, Float.valueOf(i));
				i++;
				if (r instanceof Promise)
					return r.then(v=> JelBoolean.toRealBoolean(v) ? exec() : JelBoolean.FALSE);
				else if (!JelBoolean.toRealBoolean(r))
					return JelBoolean.FALSE;
			}
		}
		return exec();
	}

 	hasOnlyJs(f: (k: string, v: JelObject|null)=>boolean): boolean {
    for (let key of this.elements.keys())
      if (!f(key, this.elements.get(key) || null))
        return false;
    return true;
	}

  hasOnlyWithPromises(f: (k: string, v: JelObject|null)=>JelBoolean|Promise<JelBoolean>): JelBoolean | Promise<JelBoolean> {
		const self = this;
		const it = this.elements.keys();
		function exec(): Promise<JelBoolean> | JelBoolean {
			while (true) {
				const next = it.next();
				if (next.done)
					return JelBoolean.TRUE;
				const r = f(next.value, self.elements.get(next.value) || null);
				if (r instanceof Promise)
					return r.then(v=> JelBoolean.toRealBoolean(v) ? exec() : JelBoolean.FALSE);
				else if (!JelBoolean.toRealBoolean(r))
					return JelBoolean.FALSE;
			}
		}
		return exec();
	}

	toObjectDebug(): any {
		const o: any = {};
		this.elements.forEach((value, key) => o[key] = value);
		return o;
	}

	static fromObject(o: any): Dictionary {
		return new Dictionary(new Map(Object.keys(o).map(k => [k, o[k]]) as any), true);
	}

	serializeToString(pretty: boolean, indent: number, spaces: string, serializer: (object: any, pretty: boolean, indent: number, spaces: string)=>string): string | undefined {
		if (!this.size)
			return "{}";
		let r = '{';
		let i = 0;
		const last = this.elements.size-1;
		const addElement = (value: any, key: string) => {
			if (pretty)
				r += '\n'+spaces.substr(0, 2);
			if (typeof key == 'string' && /^[a-zA-Z_]\w*$/.test(key))
				r += key;
			else
				r += serializer(key, pretty, indent,spaces);
			r += (pretty ? ': ' : ':') + serializer(value, pretty, indent, spaces);
			if (i++ < last)
				r += pretty ? ', ' : ',';
		};
		if (pretty) {
			r += '\n';
			Array.from(this.elements.keys()).sort().forEach(k=>addElement(this.elements.get(k), k));
		}
		else
			this.elements.forEach(addElement);
		return r + '}';
	}

  static merge(dicts?: Dictionary[]): Dictionary {
    if (!dicts || !dicts.length)
      return Dictionary.empty;
    if (dicts.length == 1)
      return dicts[0];
    if (dicts.length == 2 && dicts[0].isEmpty)
      return dicts[1];
    let d = new Dictionary();
    for (let i = 0; i < dicts.length; i++)
      d = d.putAll(dicts[i]);
    return d;
  }

	static valueOf(data?: Map<string, any>, keepMap = false): Dictionary {
		return new Dictionary(data, keepMap);
	}

	static create_jel_mapping = {list: 1}; // 2nd ctor argument intentionally omittted!
	static create(ctx: Context, ...args: any[]): any {
		return new Dictionary(args[0]);  // 2nd ctor argument intentionally omittted! They are not intended for JEL.
	}
}

Dictionary.prototype.size_jel_property = true;
Dictionary.prototype.anyKey_jel_property = true;
Dictionary.prototype.keys_jel_property = true;
Dictionary.prototype.isEmpty_jel_property = true;
Dictionary.prototype.defaultValue_jel_property = true;
Dictionary.prototype.get_jel_mapping = true;
Dictionary.prototype.withDefault_jel_mapping = true;
Dictionary.prototype.has_jel_mapping = true;
Dictionary.prototype.set_jel_mapping = true;
Dictionary.prototype.setAll_jel_mapping = true;
Dictionary.prototype.delete_jel_mapping = true;
Dictionary.prototype.deleteAll_jel_mapping = true;
Dictionary.prototype.map_jel_mapping = true;
Dictionary.prototype.mapToList_jel_mapping = true;
Dictionary.prototype.filter_jel_mapping = true;
Dictionary.prototype.reduce_jel_mapping = true;
Dictionary.prototype.hasAny_jel_mapping = true;
Dictionary.prototype.hasOnly_jel_mapping = true;

BaseTypeRegistry.register('Dictionary', Dictionary);


text:
package org.apache.logging.log4j.core.util;

import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.AbstractLifeCycle;
import org.apache.logging.log4j.core.LifeCycle2;
import org.apache.logging.log4j.status.StatusLogger;

/**
 * ShutdownRegistrationStrategy that simply uses {@link Runtime#addShutdownHook(Thread)}. If no strategy is specified,
 * this one is used for shutdown hook registration.
 *
 * @since 2.1
 */
public class DefaultShutdownCallbackRegistry implements ShutdownCallbackRegistry, LifeCycle2, Runnable {
    /** Status logger. */
    protected static final Logger LOGGER = StatusLogger.getLogger();

    private final AtomicReference<State> state = new AtomicReference<>(State.INITIALIZED);
    private final ThreadFactory threadFactory;

    // use references to prevent memory leaks
    private final Collection<Reference<Cancellable>> hooks = new CopyOnWriteArrayList<>();
    private Reference<Thread> shutdownHookRef;

    /**
     * Constructs a DefaultShutdownRegistrationStrategy.
     */
    public DefaultShutdownCallbackRegistry() {
        this(Executors.defaultThreadFactory());
    }

    /**
     * Constructs a DefaultShutdownRegistrationStrategy using the given {@link ThreadFactory}.
     *
     * @param threadFactory the ThreadFactory to use to create a {@link Runtime} shutdown hook thread
     */
    protected DefaultShutdownCallbackRegistry(final ThreadFactory threadFactory) {
        this.threadFactory = threadFactory;
    }

    /**
     * Executes the registered shutdown callbacks.
     */
    @Override
    public void run() {
        if (state.compareAndSet(State.STARTED, State.STOPPING)) {
            for (final Reference<Cancellable> hookRef : hooks) {
                Cancellable hook = hookRef.get();
                if (hook != null) {
                    try {
                        hook.run();
                    } catch (final Throwable t1) {
                        try {
                            LOGGER.error(SHUTDOWN_HOOK_MARKER, "Caught exception executing shutdown hook {}", hook, t1);
                        } catch (final Throwable t2) {
                            System.err.println("Caught exception " + t2.getClass() + " logging exception " + t1.getClass());
                            t1.printStackTrace();
                        }
                    }
                }
            }
            state.set(State.STOPPED);
        }
    }

    private static class RegisteredCancellable implements Cancellable {
        private Runnable callback;
        private Collection<Reference<Cancellable>> registered;

        RegisteredCancellable(final Runnable callback, final Collection<Reference<Cancellable>> registered) {
            this.callback = callback;
            this.registered = registered;
        }

        @Override
        public void cancel() {
            callback = null;
            Collection<Reference<Cancellable>> references = registered;
            if (references != null) {
                registered = null;
                references.removeIf(ref -> {
                    Cancellable value = ref.get();
                    return value == null || value == RegisteredCancellable.this;
                });
            }
        }

        @Override
        public void run() {
            final Runnable runnableHook = callback;
            if (runnableHook != null) {
                runnableHook.run();
                callback = null;
            }
        }

        @Override
        public String toString() {
            return String.valueOf(callback);
        }
    }

    @Override
    public Cancellable addShutdownCallback(final Runnable callback) {
        if (isStarted()) {
            final Cancellable receipt = new RegisteredCancellable(callback, hooks);
            hooks.add(new SoftReference<>(receipt));
            return receipt;
        }
        throw new IllegalStateException("Cannot add new shutdown hook as this is not started. Current state: " +
            state.get().name());
    }

    @Override
    public void initialize() {
    }

    /**
     * Registers the shutdown thread only if this is initialized.
     */
    @Override
    public void start() {
        if (state.compareAndSet(State.INITIALIZED, State.STARTING)) {
            try {
                addShutdownHook(threadFactory.newThread(this));
                state.set(State.STARTED);
            } catch (final IllegalStateException ex) {
                state.set(State.STOPPED);
                throw ex;
            } catch (final Exception e) {
                LOGGER.catching(e);
                state.set(State.STOPPED);
            }
        }
    }

    private void addShutdownHook(final Thread thread) {
        shutdownHookRef = new WeakReference<>(thread);
        Runtime.getRuntime().addShutdownHook(thread);
    }

    @Override
    public void stop() {
        stop(AbstractLifeCycle.DEFAULT_STOP_TIMEOUT, AbstractLifeCycle.DEFAULT_STOP_TIMEUNIT);
    }

    /**
     * Cancels the shutdown thread only if this is started.
     */
    @Override
    public boolean stop(final long timeout, final TimeUnit timeUnit) {
        if (state.compareAndSet(State.STARTED, State.STOPPING)) {
            try {
                removeShutdownHook();
            } finally {
                state.set(State.STOPPED);
            }
        }
        return true;
    }

    private void removeShutdownHook() {
        final Thread shutdownThread = shutdownHookRef.get();
        if (shutdownThread != null) {
            Runtime.getRuntime().removeShutdownHook(shutdownThread);
            shutdownHookRef.enqueue();
        }
    }

    @Override
    public State getState() {
        return state.get();
    }

    /**
     * Indicates if this can accept shutdown hooks.
     *
     * @return true if this can accept shutdown hooks
     */
    @Override
    public boolean isStarted() {
        return state.get() == State.STARTED;
    }

    @Override
    public boolean isStopped() {
        return state.get() == State.STOPPED;
    }

}


text:
package com.hazelcast.internal.monitor.impl;

import com.hazelcast.collection.LocalQueueStats;
import com.hazelcast.internal.json.JsonObject;
import com.hazelcast.internal.metrics.Probe;
import com.hazelcast.internal.util.Clock;
import com.hazelcast.json.internal.JsonSerializable;

import java.util.concurrent.atomic.AtomicLongFieldUpdater;

import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_AVERAGE_AGE;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_BACKUP_ITEM_COUNT;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_CREATION_TIME;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_EVENT_OPERATION_COUNT;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_MAX_AGE;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_MIN_AGE;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_NUMBER_OF_EMPTY_POLLS;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_NUMBER_OF_EVENTS;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_NUMBER_OF_OFFERS;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_NUMBER_OF_OTHER_OPERATIONS;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_NUMBER_OF_POLLS;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_NUMBER_OF_REJECTED_OFFERS;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_OWNED_ITEM_COUNT;
import static com.hazelcast.internal.metrics.MetricDescriptorConstants.QUEUE_METRIC_TOTAL;
import static com.hazelcast.internal.metrics.ProbeUnit.MS;
import static com.hazelcast.internal.util.JsonUtil.getInt;
import static com.hazelcast.internal.util.JsonUtil.getLong;
import static java.util.concurrent.atomic.AtomicLongFieldUpdater.newUpdater;

public class LocalQueueStatsImpl implements LocalQueueStats, JsonSerializable {

    private static final AtomicLongFieldUpdater<LocalQueueStatsImpl> NUMBER_OF_OFFERS =
            newUpdater(LocalQueueStatsImpl.class, "numberOfOffers");
    private static final AtomicLongFieldUpdater<LocalQueueStatsImpl> NUMBER_OF_REJECTED_OFFERS =
            newUpdater(LocalQueueStatsImpl.class, "numberOfRejectedOffers");
    private static final AtomicLongFieldUpdater<LocalQueueStatsImpl> NUMBER_OF_POLLS =
            newUpdater(LocalQueueStatsImpl.class, "numberOfPolls");
    private static final AtomicLongFieldUpdater<LocalQueueStatsImpl> NUMBER_OF_EMPTY_POLLS =
            newUpdater(LocalQueueStatsImpl.class, "numberOfEmptyPolls");
    private static final AtomicLongFieldUpdater<LocalQueueStatsImpl> NUMBER_OF_OTHER_OPERATIONS =
            newUpdater(LocalQueueStatsImpl.class, "numberOfOtherOperations");
    private static final AtomicLongFieldUpdater<LocalQueueStatsImpl> NUMBER_OF_EVENTS =
            newUpdater(LocalQueueStatsImpl.class, "numberOfEvents");

    @Probe(name = QUEUE_METRIC_OWNED_ITEM_COUNT)
    private int ownedItemCount;
    @Probe(name = QUEUE_METRIC_BACKUP_ITEM_COUNT)
    private int backupItemCount;
    @Probe(name = QUEUE_METRIC_MIN_AGE, unit = MS)
    private long minAge;
    @Probe(name = QUEUE_METRIC_MAX_AGE, unit = MS)
    private long maxAge;
    @Probe(name = QUEUE_METRIC_AVERAGE_AGE, unit = MS)
    private long averageAge;
    @Probe(name = QUEUE_METRIC_CREATION_TIME, unit = MS)
    private long creationTime;

    // These fields are only accessed through the updater
    @Probe(name = QUEUE_METRIC_NUMBER_OF_OFFERS)
    private volatile long numberOfOffers;
    @Probe(name = QUEUE_METRIC_NUMBER_OF_REJECTED_OFFERS)
    private volatile long numberOfRejectedOffers;
    @Probe(name = QUEUE_METRIC_NUMBER_OF_POLLS)
    private volatile long numberOfPolls;
    @Probe(name = QUEUE_METRIC_NUMBER_OF_EMPTY_POLLS)
    private volatile long numberOfEmptyPolls;
    @Probe(name = QUEUE_METRIC_NUMBER_OF_OTHER_OPERATIONS)
    private volatile long numberOfOtherOperations;
    @Probe(name = QUEUE_METRIC_NUMBER_OF_EVENTS)
    private volatile long numberOfEvents;

    public LocalQueueStatsImpl() {
        creationTime = Clock.currentTimeMillis();
    }

    @Override
    public long getMinAge() {
        return minAge;
    }

    public void setMinAge(long minAge) {
        this.minAge = minAge;
    }

    @Override
    public long getMaxAge() {
        return maxAge;
    }

    public void setMaxAge(long maxAge) {
        this.maxAge = maxAge;
    }

    @Override
    public long getAverageAge() {
        return averageAge;
    }

    public void setAverageAge(long averageAge) {
        this.averageAge = averageAge;
    }

    @Override
    public long getOwnedItemCount() {
        return ownedItemCount;
    }

    public void setOwnedItemCount(int ownedItemCount) {
        this.ownedItemCount = ownedItemCount;
    }

    @Override
    public long getBackupItemCount() {
        return backupItemCount;
    }

    public void setBackupItemCount(int backupItemCount) {
        this.backupItemCount = backupItemCount;
    }

    @Override
    public long getCreationTime() {
        return creationTime;
    }

    @Probe(name = QUEUE_METRIC_TOTAL)
    public long total() {
        return numberOfOffers + numberOfPolls + numberOfOtherOperations;
    }

    @Override
    public long getOfferOperationCount() {
        return numberOfOffers;
    }

    @Override
    public long getRejectedOfferOperationCount() {
        return numberOfRejectedOffers;
    }

    @Override
    public long getPollOperationCount() {
        return numberOfPolls;
    }

    @Override
    public long getEmptyPollOperationCount() {
        return numberOfEmptyPolls;
    }

    @Override
    public long getOtherOperationsCount() {
        return numberOfOtherOperations;
    }

    public void incrementOtherOperations() {
        NUMBER_OF_OTHER_OPERATIONS.incrementAndGet(this);
    }

    public void incrementOffers() {
        NUMBER_OF_OFFERS.incrementAndGet(this);
    }

    public void incrementRejectedOffers() {
        NUMBER_OF_REJECTED_OFFERS.incrementAndGet(this);
    }

    public void incrementPolls() {
        NUMBER_OF_POLLS.incrementAndGet(this);
    }

    public void incrementEmptyPolls() {
        NUMBER_OF_EMPTY_POLLS.incrementAndGet(this);
    }

    public void incrementReceivedEvents() {
        NUMBER_OF_EVENTS.incrementAndGet(this);
    }

    @Probe(name = QUEUE_METRIC_EVENT_OPERATION_COUNT)
    @Override
    public long getEventOperationCount() {
        return numberOfEvents;
    }

    @Override
    public JsonObject toJson() {
        JsonObject root = new JsonObject();
        root.add("ownedItemCount", ownedItemCount);
        root.add("backupItemCount", backupItemCount);
        root.add("minAge", minAge);
        root.add("maxAge", maxAge);
        root.add("averageAge", averageAge);
        root.add("creationTime", creationTime);
        root.add("numberOfOffers", numberOfOffers);
        root.add("numberOfPolls", numberOfPolls);
        root.add("numberOfRejectedOffers", numberOfRejectedOffers);
        root.add("numberOfEmptyPolls", numberOfEmptyPolls);
        root.add("numberOfOtherOperations", numberOfOtherOperations);
        root.add("numberOfEvents", numberOfEvents);
        return root;
    }

    @Override
    public void fromJson(JsonObject json) {
        ownedItemCount = getInt(json, "ownedItemCount", -1);
        backupItemCount = getInt(json, "backupItemCount", -1);
        minAge = getLong(json, "minAge", -1L);
        maxAge = getLong(json, "maxAge", -1L);
        averageAge = getLong(json, "averageAge", -1L);
        creationTime = getLong(json, "creationTime", -1L);
        NUMBER_OF_OFFERS.set(this, getLong(json, "numberOfOffers", -1L));
        NUMBER_OF_POLLS.set(this, getLong(json, "numberOfPolls", -1L));
        NUMBER_OF_REJECTED_OFFERS.set(this, getLong(json, "numberOfRejectedOffers", -1L));
        NUMBER_OF_EMPTY_POLLS.set(this, getLong(json, "numberOfEmptyPolls", -1L));
        NUMBER_OF_OTHER_OPERATIONS.set(this, getLong(json, "numberOfOtherOperations", -1L));
        NUMBER_OF_EVENTS.set(this, getLong(json, "numberOfEvents", -1L));
    }

    @Override
    public String toString() {
        return "LocalQueueStatsImpl{"
                + "ownedItemCount=" + ownedItemCount
                + ", backupItemCount=" + backupItemCount
                + ", minAge=" + minAge
                + ", maxAge=" + maxAge
                + ", averageAge=" + averageAge
                + ", creationTime=" + creationTime
                + ", numberOfOffers=" + numberOfOffers
                + ", numberOfRejectedOffers=" + numberOfRejectedOffers
                + ", numberOfPolls=" + numberOfPolls
                + ", numberOfEmptyPolls=" + numberOfEmptyPolls
                + ", numberOfOtherOperations=" + numberOfOtherOperations
                + ", numberOfEvents=" + numberOfEvents
                + '}';
    }
}


text:
This is a web-based application that reads RSS feeds. this project included [Jasmine](http://jasmine.github.io/)  andcomplete test suite.

## Why this Project?

Testing is an important part of the development process and many organizations practice a standard of development known as "test-driven development". This is when developers write tests first, before they ever start developing their application. All the tests initially fail and then they start writing application code to make these tests pass.

## What to run this application?
1. Check out the repository or Download or fork the application.
2. Select index.html to start the app.

Additionally to inspect the site on your phone, you can run a local server
  ```bash
  $> cd /path/to/your-project-folder
  $> python -m SimpleHTTPServer 8080
  ```
and Open a browser and visit localhost:8080

OR

Download and install [ngrok](https://ngrok.com/) to make your local server accessible remotely.
  ``` bash
  $> cd /path/to/your-project-folder
  $> ngrok http 8080
  ```
# How did I complete this project?
1. Download the [required project assets](http://github.com/udacity/frontend-nanodegree-feedreader).
2. Review the functionality of the application within my browser.
3. Explore the application's HTML (*./index.html*), CSS (*./css/style.css*) and JavaScript (*./js/app.js*) to gain an understanding of how it works.
4. Explore the Jasmine spec file in *./jasmine/spec/feedreader.js*
5. Edit the allFeeds variable in *./js/app.js* to make the provided test fail and see how Jasmine visualizes this failure in my application.
6. Return the allFeeds variable to a passing state.
7. Write a test that loops through each feed in the allFeeds object and ensures it has a URL defined and that the URL is not empty.
8. Write a test that loops through each feed in the allFeeds object and ensures it has a name defined and that the name is not empty.
9. Write a new test suite named "The menu".
10. Write a test that ensures the menu element is hidden by default. I have to analyze the HTML and the CSS to determine how we're performing the hiding/showing of the menu element.
11. Write a test that ensures the menu changes visibility when the menu icon is clicked. This test should have two expectations: does the menu display when clicked and does it hide when clicked again.
12. Write a test that ensures when the loadFeed function is called and completes its work, there is at least a single .entry element within the .feed container. Remember, loadFeed() is asynchronous so this test wil require the use of Jasmine's beforeEach and asynchronous done() function.
13. Write a test that ensures when a new feed is loaded by the loadFeed function that the content actually changes. Remember, loadFeed() is asynchronous.
14. When complete - all of the tests should pass.


text:
package akka.io

import java.nio.channels.DatagramChannel
import scala.collection.immutable
import scala.util.control.NonFatal
import akka.dispatch.{ RequiresMessageQueue, UnboundedMessageQueueSemantics }
import akka.io.Inet.SocketOption
import akka.io.Udp._
import akka.actor._

/**
 * INTERNAL API
 */
private[io] class UdpSender(
  val udp: UdpExt,
  channelRegistry: ChannelRegistry,
  commander: ActorRef,
  options: immutable.Traversable[SocketOption])
  extends Actor with ActorLogging with WithUdpSend with RequiresMessageQueue[UnboundedMessageQueueSemantics] {

  val channel = {
    val datagramChannel = DatagramChannel.open
    datagramChannel.configureBlocking(false)
    val socket = datagramChannel.socket
    options foreach { _.beforeDatagramBind(socket) }

    datagramChannel
  }
  channelRegistry.register(channel, initialOps = 0)

  def receive: Receive = {
    case registration: ChannelRegistration ⇒
      options.foreach {
        case v2: Inet.SocketOptionV2 ⇒ v2.afterConnect(channel.socket)
        case _ ⇒
      }
      commander ! SimpleSenderReady
      context.become(sendHandlers(registration))
  }

  override def postStop(): Unit = if (channel.isOpen) {
    log.debug("Closing DatagramChannel after being stopped")
    try channel.close()
    catch {
      case NonFatal(e) ⇒ log.debug("Error closing DatagramChannel: {}", e)
    }
  }
}


text:
<?php
/****************************************************************/
/* ATutor														*/
/****************************************************************/
/* Copyright (c) 2002-2010                                      */
/* Inclusive Design Institute                                   */
/* http://atutor.ca												*/
/*                                                              */
/* This program is free software. You can redistribute it and/or*/
/* modify it under the terms of the GNU General Public License  */
/* as published by the Free Software Foundation.				*/
/****************************************************************/
// $Id: password_user.php 10142 2010-08-17 19:17:26Z hwong $

$_user_location = 'admin';

define('AT_INCLUDE_PATH', '../../../include/');
require(AT_INCLUDE_PATH.'vitals.inc.php');
admin_authenticate(AT_ADMIN_PRIV_USERS);

if (isset($_POST['cancel'])) {
	$msg->addFeedback('CANCELLED');
	header('Location: '.AT_BASE_HREF.'mods/_core/users/users.php');
	exit;
} else if (isset($_POST['submit'])) {
	/* password check: password is verified front end by javascript. here is to handle the errors from javascript */
	if ($_POST['password_error'] <> "")
	{
		$pwd_errors = explode(",", $_POST['password_error']);

		foreach ($pwd_errors as $pwd_error)
		{
			if ($pwd_error == "missing_password")
				$missing_fields[] = _AT('password');
			else
				$msg->addError($pwd_error);
		}
	}

	if (!$msg->containsErrors()) {
		$_POST['id'] = intval($_POST['id']);

		$sql = "UPDATE ".TABLE_PREFIX."members SET password= '$_POST[form_password_hidden]', creation_date=creation_date, last_login=last_login WHERE member_id=$_POST[id]";
		$result = mysql_query($sql, $db);

		$sql	= "SELECT login, email FROM ".TABLE_PREFIX."members WHERE member_id=$_POST[id]";
		$result = mysql_query($sql,$db);
		if ($row = mysql_fetch_assoc($result)) {
			$r_login = $row['login'];
			$r_email = $row['email'];

			$tmp_message  = _AT('password_change_msg')."\n\n";
			$tmp_message .= _AT('web_site').' : '.AT_BASE_HREF."\n";
			$tmp_message .= _AT('login_name').' : '.$r_login."\n";

			require(AT_INCLUDE_PATH . 'classes/phpmailer/atutormailer.class.php');

			$mail = new ATutorMailer;

			$mail->From     = $_config['contact_email'];
			$mail->AddAddress($r_email);
			$mail->Subject = $_config['site_name'] . ': ' . _AT('password_changed');
			$mail->Body    = $tmp_message;

			if(!$mail->Send()) {
			   $msg->printErrors('SENDING_ERROR');
			   exit;
			}

		}

		$msg->addFeedback('PROFILE_UPDATED_ADMIN');
		header('Location: '.AT_BASE_HREF.'mods/_core/users/users.php');
		exit;
	}
	$_GET['id'] = $_POST['id'];
}

$onload = 'document.form.password.focus();';

require(AT_INCLUDE_PATH.'header.inc.php');

$id = intval($_GET['id']);

$sql	= "SELECT login FROM ".TABLE_PREFIX."members WHERE member_id=$id";
$result = mysql_query($sql, $db);

if (!$row = mysql_fetch_assoc($result)) {
	$msg->printErrors('USER_NOT_FOUND');
	require(AT_INCLUDE_PATH.'footer.inc.php');
	exit;
}

?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" name="form">
	<input type="hidden" name="id" value="<?php echo $id; ?>" />
	<input type="hidden" name="form_password_hidden" value="" />
	<input type="hidden" name="password_error" value="" />

<?php echo htmlspecialchars($row['login']); ?>

			<span class="required" title="<?php echo _AT('required_field'); ?>">*<?php echo _AT('password'); ?>

			<input type="password" name="password" id="password" value="" size="30" />

			<span class="required" title="<?php echo _AT('required_field'); ?>">*<?php echo _AT('confirm_password'); ?>

			<input type="password" name="password2" id="password2" value="" size="30" />

			<input type="submit" name="submit" value="<?php echo _AT('submit'); ?>" onClick="encrypt_password()" />
			<input type="submit" name="cancel" value="<?php echo _AT('cancel'); ?>" />

</form>

<?php require(AT_INCLUDE_PATH.'footer.inc.php'); ?>


text:
using System;

namespace stellar_dotnet_sdk.xdr
{
// === xdr source ============================================================
//  struct AuthCert
//  {
//      Curve25519Public pubkey;
//      uint64 expiration;
//      Signature sig;
//  };
//  ===========================================================================
    public class AuthCert
    {
        public AuthCert()
        {
        }

        public Curve25519Public Pubkey { get; set; }
        public Uint64 Expiration { get; set; }
        public Signature Sig { get; set; }

        public static void Encode(XdrDataOutputStream stream, AuthCert encodedAuthCert)
        {
            Curve25519Public.Encode(stream, encodedAuthCert.Pubkey);
            Uint64.Encode(stream, encodedAuthCert.Expiration);
            Signature.Encode(stream, encodedAuthCert.Sig);
        }

        public static AuthCert Decode(XdrDataInputStream stream)
        {
            AuthCert decodedAuthCert = new AuthCert();
            decodedAuthCert.Pubkey = Curve25519Public.Decode(stream);
            decodedAuthCert.Expiration = Uint64.Decode(stream);
            decodedAuthCert.Sig = Signature.Decode(stream);
            return decodedAuthCert;
        }
    }
}


text:
from flask import Flask, render_template, redirect, request, session, url_for, flash
from flask.ext.moment import Moment

from uuid import uuid4

from libs import sorter, format_dueDate

from creds import *

from parse_rest.connection import register
from parse_rest.datatypes import Object
from parse_rest.user import User

register(PARSE_appId, PARSE_apiKey)

class Projects(Object):
	pass
class Tasks(Object):
	pass
class _User(Object):
	pass
app = Flask(__name__)
moment = Moment(app)

@app.before_request
def setup_env():
	app.jinja_env.globals["len"] = len
	app.jinja_env.globals["sorter"] = sorter

@app.route("/")
@app.route("/list")
def list_projects():
	if not session.get("logged_in"):
		return redirect(url_for("login"))
	projects = Projects.Query.filter(userId=session.get("uid"))
	return render_template("listProjects.html", projects=projects)
@app.route("/newproj", methods=["GET", "POST"])
def new_project():
	if not session.get("logged_in"):
		return redirect(url_for("login"))
	if request.method == "POST":
		Projects(
			name=request.form["projectName"],
			detail=request.form["projectDetail"],
			url=uuid4().hex,
			theme=request.form["projectTheme"],
			user=_User.Query.get(objectId=session.get("uid")),
			userId=session.get("uid")
			).save()
		return redirect(url_for("list_projects"))
	return render_template("newProject.html")
@app.route("/editproj/<projectUrl>", methods=["GET", "POST"])
def edit_project(projectUrl=None):
	if not session.get("logged_in"):
		return redirect(url_for("login"))
	if projectUrl == None:
		return redirect(url_for("list_projects"))
	try:
		project = Projects.Query.get(url=projectUrl)
	except:
		return redirect(url_for("list_projects"))
	if project.userId != session.get("uid"):
		return redirect(url_for("list_projects"))
	if request.method == "POST":
		project(
		name=request.form["projectTitle"],
		detail=request.form["projectDetail"],
		theme=request.form["projectTheme"]
		).save()
		return redirect(url_for("list_projects"))
	return render_template("editProject.html", project=project)
@app.route("/delproj/<projectUrl>")
def delete_project(projectUrl=None):
	if not session.get("logged_in"):
		return redirect(url_for("login"))
	if projectUrl == None:
		return redirect(url_for("list_projects"))
	try:
		project = Projects.Query.get(url=projectUrl)
	except:
		flash("No such project")
		return redirect(url_for("list_projects"))
	if project.userId != session.get("uid"):
		flash("You do not own this project")
		return redirect(url_for("list_projects"))
	project.delete()
	flash("deleted")
	return redirect(url_for("list_projects"))

@app.route("/tasks/<projectUrl>")
def project_tasks(projectUrl=None):
	if not session.get("logged_in"):
		return redirect(url_for("login"))
	if projectUrl == None:
		return redirect(url_for("list_projects"))
	try:
		project = Projects.Query.get(url=projectUrl)
	except:
		return redirect(url_for("list_projects"))
	if project.userId != session.get("uid"):
		return redirect(url_for("list_projects"))
	tasks = Tasks.Query.filter(userId=session.get("uid"), projectUrl=projectUrl).order_by("-dueDate")
	return render_template("listTasks.html", tasks=tasks, project=project)
@app.route("/newtask/<projectUrl>", methods=["GET","POST"])
def new_task(projectUrl=None):
	if not session.get("logged_in"):
		return redirect(url_for("login"))
	if projectUrl == None:
		redirect(url_for("project_tasks",projectUrl=projectUrl))
	try:
		project = Projects.Query.get(url=projectUrl, userId=session.get("uid"))
	except:
		return redirect(url_for("list_projects"))
	if request.method == "POST":
		Tasks(
			title=request.form["taskTitle"],
			detail=request.form["taskDetail"],
			dueDate=format_dueDate(request.form["taskDueDate"]),
			user=_User.Query.get(objectId=session.get("uid")),
			userId=session.get("uid"),
			project=project,
			projectId=project.objectId,
			projectUrl=project.url
		).save()
		return redirect(url_for("project_tasks", projectUrl=projectUrl))
	return render_template("newTask.html", project=project)
@app.route("/all")
def all_tasks():
	if not session.get("logged_in"):
		return redirect(url_for("login"))
	z = Tasks.Query.filter(userId=session.get("uid"))#.order_by("-dueDate")
	if z == None:
		z = []
	return render_template("allTasks.html", tasks=z)
@app.route("/edittask/<taskId>", methods=["GET", "POST"])
def edit_task(taskId=None):
	if not session.get("logged_in"):
		return redirect(url_for("login"))
	if taskId == None:
		return redirect(url_for("project_list"))
	try:
		task = Tasks.Query.get(objectId=taskId, userId=session.get("uid"))
	except:
		return redirect(url_for("project_list"))
	if request.method == "POST":
		task(
			title=request.form["taskTitle"],
			detail=request.form["taskTitle"],
			dueDate=format_dueDate(request.form["taskDueDate"]),
		).save()
		return redirect(url_for("project_tasks", projectUrl=task.projectUrl))
	return render_template("editTask.html", task=task)
@app.route("/deltask/<taskId>")
def delete_task(taskId=None):
	if not session.get("logged_in"):
		return redirect(url_for("login"))
	if taskId == None:
		return redirect(url_for("project_list"))
	try:
		task = Tasks.Query.get(objectId=taskId, userId=session.get("uid"))
	except:
		return redirect(url_for("project_list"))
	task.delete()
	return redirect(url_for("project_tasks", projectUrl=task.projectUrl))

@app.route("/login", methods=["POST","GET"])
def login():
	if session.get("logged_in"):
		return redirect(url_for("list_projects"))
	if request.method == "POST":
		try:
			u = User.login(request.form["username"], request.form["password"])
			session["logged_in"] = True
			session["uid"] = u.objectId
		except:
			flash("bad login")

	return render_template("login.html")
@app.route("/logout")
def logout():
	if not session.get("logged_in"):
		return redirect(url_for("login"))
	else:
		session.pop("logged_in", None)
		return redirect(url_for("login"))

if __name__ == "__main__":
	app.secret_key = "907470"
	app.run(debug=True)