text:
// Copyright 2011 WebDriver committers
// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview The file contains the base class for input devices such as
 * the keyboard, mouse, and touchscreen.
 */

goog.provide('bot.Device');

goog.require('bot');
goog.require('bot.dom');
goog.require('bot.locators');
goog.require('bot.userAgent');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.userAgent');
goog.require('goog.userAgent.product');

/**
 * A Device class that provides common functionality for input devices.
 * @param {bot.Device.ModifiersState=} opt_modifiersState state of modifier
 * keys. The state is shared, not copied from this parameter.
 *
 * @constructor
 */
bot.Device = function(opt_modifiersState) {
  /**
   * Element being interacted with.
   * @type {!Element}
   * @private
   */
  this.element_ = bot.getDocument().documentElement;

  /**
   * If the element is an option, this is its parent select element.
   * @type {Element}
   * @private
   */
  this.select_ = null;

  // If there is an active element, make that the current element instead.
  var activeElement = bot.dom.getActiveElement(this.element_);
  if (activeElement) {
    this.setElement(activeElement);
  }

  /**
   * State of modifier keys for this device.
   * @type {bot.Device.ModifiersState}
   * @protected
   */
  this.modifiersState = opt_modifiersState || new bot.Device.ModifiersState();
};

/**
 * Returns the element with which the device is interacting.
 *
 * @return {!Element} Element being interacted with.
 * @protected
 */
bot.Device.prototype.getElement = function() {
  return this.element_;
};

/**
 * Sets the element with which the device is interacting.
 *
 * @param {!Element} element Element being interacted with.
 * @protected
 */
bot.Device.prototype.setElement = function(element) {
  this.element_ = element;
  if (bot.dom.isElement(element, goog.dom.TagName.OPTION)) {
    this.select_ = /** @type {Element} */ (goog.dom.getAncestor(element,
        function(node) {
          return bot.dom.isElement(node, goog.dom.TagName.SELECT);
        }));
  } else {
    this.select_ = null;
  }
};

/**
 * Fires an HTML event given the state of the device.
 *
 * @param {bot.events.EventType} type HTML Event type.
 * @return {boolean} Whether the event fired successfully; false if cancelled.
 * @protected
 */
bot.Device.prototype.fireHtmlEvent = function(type) {
  return bot.events.fire(this.element_, type);
};

/**
 * Fires a keyboard event given the state of the device and the given arguments.
 * TODO(user): Populate the modifier keys in this method.
 *
 * @param {bot.events.EventType} type Keyboard event type.
 * @param {bot.events.KeyboardArgs} args Keyboard event arguments.
 * @return {boolean} Whether the event fired successfully; false if cancelled.
 * @protected
 */
bot.Device.prototype.fireKeyboardEvent = function(type, args) {
  return bot.events.fire(this.element_, type, args);
};

/**
 * Fires a mouse event given the state of the device and the given arguments.
 * TODO(user): Populate the modifier keys in this method.
 *
 * @param {bot.events.EventType} type Mouse event type.
 * @param {!goog.math.Coordinate} coord The coordinate where event will fire.
 * @param {number} button The mouse button value for the event.
 * @param {Element=} opt_related The related element of this event.
 * @param {number=} opt_wheelDelta The wheel delta value for the event.
 * @return {boolean} Whether the event fired successfully; false if cancelled.
 * @protected
 */
bot.Device.prototype.fireMouseEvent = function(type, coord, button,
                                               opt_related, opt_wheelDelta) {
  // TODO(user): Event if the element is not interactable, the mouse event
  // should still fire on another element (offset parent?).
  if (!bot.dom.isInteractable(this.element_)) {
    return false;
  }

  if (opt_related &&
      !(bot.events.EventType.MOUSEOVER == type ||
        bot.events.EventType.MOUSEOUT == type)) {
    throw new bot.Error(bot.ErrorCode.INVALID_ELEMENT_STATE,
                        'Event type does not allow related target: ' + type);
  }

  var args = {
    clientX: coord.x,
    clientY: coord.y,
    button: button,
    altKey: this.modifiersState.isAltPressed(),
    ctrlKey: this.modifiersState.isControlPressed(),
    shiftKey: this.modifiersState.isShiftPressed(),
    metaKey: this.modifiersState.isMetaPressed(),
    wheelDelta: opt_wheelDelta || 0,
    relatedTarget: opt_related || null
  };

  var target = this.select_ ?
      this.getTargetOfOptionMouseEvent_(type) : this.element_;
  return target ? bot.events.fire(target, type, args) : true;
};

/**
 * Fires a touch event given the state of the deive and the given arguments.
 *
 * @param {bot.events.EventType} type Event type.
 * @param {number} id The touch identifier.
 * @param {!goog.math.Coordinate} coord The coordinate where event will fire.
 * @param {number=} opt_id2 The touch identifier of the second finger.
 * @param {!goog.math.Coordinate=} opt_coord2 The coordinate of the second
 *    finger, if any.
 * @return {boolean} Whether the event fired successfully or was cancelled.
 * @protected
 */
bot.Device.prototype.fireTouchEvent = function(type, id, coord, opt_id2,
                                               opt_coord2) {
  var args = {
    touches: [],
    targetTouches: [],
    changedTouches: [],
    altKey: this.modifiersState.isAltPressed(),
    ctrlKey: this.modifiersState.isControlPressed(),
    shiftKey: this.modifiersState.isShiftPressed(),
    metaKey: this.modifiersState.isMetaPressed(),
    relatedTarget: null,
    scale: 0,
    rotation: 0
  };

  function addTouch(identifier, coords) {
    // Android devices leave identifier to zero.
    var id = goog.userAgent.product.ANDROID ? 0 : identifier;
    var touch = {
      identifier: identifier,
      screenX: coords.x,
      screenY: coords.y,
      clientX: coords.x,
      clientY: coords.y,
      pageX: coords.x,
      pageY: coords.y
    };

    args.changedTouches.push(touch);
    if (type == bot.events.EventType.TOUCHSTART ||
        type == bot.events.EventType.TOUCHMOVE) {
      args.touches.push(touch);
      args.targetTouches.push(touch);
    }
  }

  addTouch(id, coord);
  if (goog.isDef(opt_id2)) {
    addTouch(opt_id2, opt_coord2);
  }

  return bot.events.fire(this.element_, type, args);
};

/**
 * A mouse event fired "on" an <option> element, doesn't always fire on the
 * <option> element itself. Sometimes it fires on the parent <select> element
 * and sometimes not at all, depending on the browser and event type. This
 * returns the true target element of the event, or null if none is fired.
 *
 * @param {bot.events.EventType} type Type of event.
 * @return {Element} Element the event should be fired on, null if none.
 * @private
 */
bot.Device.prototype.getTargetOfOptionMouseEvent_ = function(type) {
  // IE either fires the event on the parent select or not at all.
  if (goog.userAgent.IE) {
    switch (type) {
      case bot.events.EventType.MOUSEOVER:
        return null;
      case bot.events.EventType.CONTEXTMENU:
      case bot.events.EventType.MOUSEMOVE:
        return this.select_.multiple ? this.select_ : null;
      default:
        return this.select_;
    }
  }

  // Opera only skips mouseovers and contextmenus on single selects.
  if (goog.userAgent.OPERA) {
    switch (type) {
      case bot.events.EventType.CONTEXTMENU:
      case bot.events.EventType.MOUSEOVER:
        return this.select_.multiple ? this.element_ : null;
      default:
        return this.element_;
    }
  }

  // WebKit always fires on the option element of multi-selects.
  // On single-selects, it either fires on the parent or not at all.
  if (goog.userAgent.WEBKIT) {
    switch (type) {
      case bot.events.EventType.CLICK:
      case bot.events.EventType.MOUSEUP:
        return this.select_.multiple ? this.element_ : this.select_;
      default:
        return this.select_.multiple ? this.element_ : null;
    }
  }

  // Firefox fires every event or the option element.
  return this.element_;
};

/**
 * A helper function to fire click events.  This method is shared between
 * the mouse and touchscreen devices.
 *
 * @param {!goog.math.Coordinate} coord The coordinate where event will fire.
 * @param {number} button The mouse button value for the event.
 * @protected
 */
bot.Device.prototype.clickElement = function(coord, button) {
  if (!bot.dom.isInteractable(this.element_)) {
    return;
  }

  // bot.events.fire(element, 'click') can trigger all onclick events, but may
  // not follow links (FORM.action or A.href).
  //     TAG      IE   GECKO  WebKit Opera
  // A(href)      No    No     Yes    Yes
  // FORM(action) No    Yes    Yes    Yes
  var targetLink = null;
  var targetButton = null;
  if (!bot.Device.ALWAYS_FOLLOWS_LINKS_ON_CLICK_) {
    for (var e = this.element_; e; e = e.parentNode) {
      if (bot.dom.isElement(e, goog.dom.TagName.A)) {
        targetLink = /**@type {!Element}*/ (e);
        break;
      } else if (bot.Device.isFormSubmitElement(e)) {
        targetButton = e;
        break;
      }
    }
  }

  var selectable = bot.dom.isSelectable(this.element_);
  var wasSelected = selectable && bot.dom.isSelected(this.element_);

  // When an element is toggled as the result of a click, the toggling and the
  // change event happens before the click event. However, on radio buttons and
  // checkboxes, the click handler can prevent the toggle from happening, so
  // for those we need to fire a click before toggling to see if the click was
  // cancelled. For option elements, we toggle unconditionally before the click.
  if (this.select_) {
    this.toggleOption_(wasSelected);
  }

  // NOTE(user): Clicking on a form submit button is a little broken:
  // (1) When clicking a form submit button in IE, firing a click event or
  // calling Form.submit() will not by itself submit the form, so we call
  // Element.click() explicitly, but as a result, the coordinates of the click
  // event are not provided. Also, when clicking on an <input type=image>, the
  // coordinates click that are submitted with the form are always (0, 0).
  // (2) When clicking a form submit button in GECKO, while the coordinates of
  // the click event are correct, those submitted with the form are always (0,0)
  // .
  // TODO(user): See if either of these can be resolved, perhaps by adding
  // hidden form elements with the coordinates before the form is submitted.
  if (goog.userAgent.IE && targetButton) {
    targetButton.click();
    return;
  }

  var performDefault = this.fireMouseEvent(
      bot.events.EventType.CLICK, coord, button);
  if (!performDefault) {
    return;
  }

  if (targetLink && bot.Device.shouldFollowHref_(targetLink)) {
    bot.Device.followHref_(targetLink);
  } else if (selectable && !this.select_) {
    this.toggleRadioButtonOrCheckbox_(wasSelected);
  }
};

/**
 * Focuses on the given element and returns true if it supports being focused
 * and does not already have focus; otherwise, returns false. If another element
 * has focus, that element will be blurred before focusing on the given element.
 *
 * @return {boolean} Whether the element was given focus.
 * @protected
 */
bot.Device.prototype.focusOnElement = function() {
  // Focusing on an <option> always focuses on the parent <select>.
  var elementToFocus = this.select_ || this.element_;

  var activeElement = bot.dom.getActiveElement(elementToFocus);
  if (elementToFocus == activeElement) {
    return false;
  }

  // If there is a currently active element, try to blur it.
  if (activeElement && (goog.isFunction(activeElement.blur) ||
      // IE reports native functions as being objects.
      goog.userAgent.IE && goog.isObject(activeElement.blur))) {
    // In IE, the focus() and blur() functions fire their respective events
    // asynchronously, and as the result, the focus/blur events fired by the
    // the atoms actions will often be in the wrong order on IE. Firing a blur
    // out of order sometimes causes IE to throw an "Unspecified error", so we
    // wrap it in a try-catch and catch and ignore the error in this case.
    try {
      activeElement.blur();
    } catch (e) {
      if (!(goog.userAgent.IE && e.message == 'Unspecified error.')) {
        throw e;
      }
    }

    // Sometimes IE6 and IE7 will not fire an onblur event after blur()
    // is called, unless window.focus() is called immediately afterward.
    // Note that IE8 will hit this branch unless the page is forced into
    // IE8-strict mode. This shouldn't hurt anything, we just use the
    // useragent sniff so we can compile this out for proper browsers.
    if (goog.userAgent.IE && !bot.userAgent.isEngineVersion(8)) {
      goog.dom.getWindow(goog.dom.getOwnerDocument(elementToFocus)).focus();
    }
  }

  // Try to focus on the element.
  if (goog.isFunction(elementToFocus.focus) ||
      goog.userAgent.IE && goog.isObject(elementToFocus.focus)) {
    // Opera fires focus events on hidden elements (e.g. that are hidden after
    // mousedown in a click sequence), but as of Opera 11 the focus() command
    // does not, so we fire a focus event on the hidden element explicitly.
    if (goog.userAgent.OPERA && bot.userAgent.isEngineVersion(11) &&
        !bot.dom.isShown(elementToFocus)) {
      bot.events.fire(elementToFocus, bot.events.EventType.FOCUS);
    } else {
      elementToFocus.focus();
    }
    return true;
  }

  return false;
};

/**
 * Whether links must be manually followed when clicking (because firing click
 * events doesn't follow them).
 *
 * @type {boolean}
 * @private
 * @const
 */
bot.Device.ALWAYS_FOLLOWS_LINKS_ON_CLICK_ =
    goog.userAgent.WEBKIT || goog.userAgent.OPERA ||
      (bot.userAgent.FIREFOX_EXTENSION && bot.userAgent.isProductVersion(3.6));

/**
 * @param {Node} element The element to check.
 * @return {boolean} Whether the element is a submit element in form.
 * @protected
 */
bot.Device.isFormSubmitElement = function(element) {
  if (bot.dom.isElement(element, goog.dom.TagName.INPUT)) {
    var type = element.type.toLowerCase();
    if (type == 'submit' || type == 'image') {
      return true;
    }
  }

  if (bot.dom.isElement(element, goog.dom.TagName.BUTTON)) {
    var type = element.type.toLowerCase();
    if (type == 'submit') {
      return true;
    }
  }
  return false;
};

/**
 * Indicates whether we should manually follow the href of the element we're
 * clicking.
 *
 * Versions of firefox from 4+ will handle links properly when this is used in
 * an extension. Versions of Firefox prior to this may or may not do the right
 * thing depending on whether a target window is opened and whether the click
 * has caused a change in just the hash part of the URL.
 *
 * @param {!Element} element The element to consider.
 * @return {boolean} Whether following an href should be skipped.
 * @private
 */
bot.Device.shouldFollowHref_ = function(element) {
  if (bot.Device.ALWAYS_FOLLOWS_LINKS_ON_CLICK_ || !element.href) {
    return false;
  }

  if (!bot.userAgent.FIREFOX_EXTENSION) {
    return true;
  }

  if (element.target || element.href.toLowerCase().indexOf('javascript') == 0) {
    return false;
  }

  var owner = goog.dom.getWindow(goog.dom.getOwnerDocument(element));
  var sourceUrl = owner.location.href;
  var destinationUrl = bot.Device.resolveUrl_(owner.location, element.href);
  var isOnlyHashChange =
      sourceUrl.split('#')[0] === destinationUrl.split('#')[0];

  return !isOnlyHashChange;
};

/**
 * Explicitly follows the href of an anchor.
 *
 * @param {!Element} anchorElement An anchor element.
 * @private
 */
bot.Device.followHref_ = function(anchorElement) {
  var targetHref = anchorElement.href;
  var owner = goog.dom.getWindow(goog.dom.getOwnerDocument(anchorElement));

  // IE7 and earlier incorrect resolve a relative href against the top window
  // location instead of the window to which the href is assigned. As a result,
  // we have to resolve the relative URL ourselves. We do not use Closure's
  // goog.Uri to resolve, because it incorrectly fails to support empty but
  // undefined query and fragment components and re-encodes the given url.
  if (goog.userAgent.IE && !bot.userAgent.isEngineVersion(8)) {
    targetHref = bot.Device.resolveUrl_(owner.location, targetHref);
  }

  if (anchorElement.target) {
    owner.open(targetHref, anchorElement.target);
  } else {
    owner.location.href = targetHref;
  }
};

/**
 * Toggles the selected state of an option element. This is a noop if the option
 * is selected and belongs to a single-select, because it can't be toggled off.
 *
 * @param {boolean} wasSelected Whether the element was originally selected.
 * @private
 */
bot.Device.prototype.toggleOption_ = function(wasSelected) {
  var select = /** @type {!Element} */ (this.select_);
  // Cannot toggle off options in single-selects.
  if (wasSelected && !select.multiple) {
    return;
  }
  this.element_.selected = !wasSelected;
  // Only WebKit fires the change event itself and only for multi-selects,
  // except for Android versions >= 4.0.
  if (!(goog.userAgent.WEBKIT && select.multiple) ||
      (goog.userAgent.product.ANDROID && bot.userAgent.isProductVersion(4))) {
    bot.events.fire(select, bot.events.EventType.CHANGE);
  }
};

/**
 * Toggles the selected state of a radio button or checkbox. This is a noop if
 * it is a radio button that is selected, because it can't be toggled off.
 *
 * @param {boolean} wasSelected Whether the element was originally selected.
 * @private
 */
bot.Device.prototype.toggleRadioButtonOrCheckbox_ = function(wasSelected) {
  // Gecko and WebKit toggle the element as a result of a click.
  if (goog.userAgent.GECKO || goog.userAgent.WEBKIT) {
    return;
  }
  // Cannot toggle off radio buttons.
  if (wasSelected && this.element_.type.toLowerCase() == 'radio') {
    return;
  }
  this.element_.checked = !wasSelected;
  // Only Opera versions < 11 do not fire the change event themselves.
  if (goog.userAgent.OPERA && !bot.userAgent.isEngineVersion(11)) {
    bot.events.fire(this.element_, bot.events.EventType.CHANGE);
  }
};

/**
 * Find FORM element that is an ancestor of the passed in element.
 * @param {Node} node The node to find a FORM for.
 * @return {Element} The ancestor FORM element if it exists.
 * @protected
 */
bot.Device.findAncestorForm = function(node) {
  return (/** @type {Element} */ goog.dom.getAncestor(
      node, bot.Device.isForm_, /*includeNode=*/true));
};

/**
 * @param {Node} node The node to test.
 * @return {boolean} Whether the node is a FORM element.
 * @private
 */
bot.Device.isForm_ = function(node) {
  return bot.dom.isElement(node, goog.dom.TagName.FORM);
};

/**
 * Submits the specified form. Unlike the public function, it expects to be
 * given a <form> element and fails if it is not.
 * @param {!Element} form The form to submit.
 * @protected
 */
bot.Device.prototype.submitForm = function(form) {
  if (!bot.Device.isForm_(form)) {
    throw new bot.Error(bot.ErrorCode.INVALID_ELEMENT_STATE,
                        'Element was not in a form, so could not submit.');
  }
  if (bot.events.fire(form, bot.events.EventType.SUBMIT)) {
    // When a form has an element with an id or name exactly equal to "submit"
    // (not uncommon) it masks the form.submit function. We  can avoid this by
    // calling the prototype's submit function, except in IE < 8, where DOM id
    // elements don't let you reference their prototypes. For IE < 8, can change
    // the id and names of the elements and revert them back, but they must be
    // reverted before the submit call, because the onsubmit handler might rely
    // on their being correct, and the HTTP request might otherwise be left with
    // incorrect value names. Fortunately, saving the submit function and
    // calling it after reverting the ids and names works! Oh, and goog.typeOf
    // (and thus goog.isFunction) doesn't work for form.submit in IE < 8.
    if (!bot.dom.isElement(form.submit)) {
      form.submit();
    } else if (!goog.userAgent.IE || bot.userAgent.isEngineVersion(8)) {
      (/** @type {Function} */ form.constructor.prototype.submit).call(form);
    } else {
      var idMasks = bot.locators.findElements({'id': 'submit'}, form);
      var nameMasks = bot.locators.findElements({'name': 'submit'}, form);
      goog.array.forEach(idMasks, function(m) {
        m.removeAttribute('id');
      });
      goog.array.forEach(nameMasks, function(m) {
        m.removeAttribute('name');
      });
      var submitFunction = form.submit;
      goog.array.forEach(idMasks, function(m) {
        m.setAttribute('id', 'submit');
      });
      goog.array.forEach(nameMasks, function(m) {
        m.setAttribute('name', 'submit');
      });
      submitFunction();
    }
  }
};

/**
 * Regular expression for splitting up a URL into components.
 * @type {!RegExp}
 * @private
 * @const
 */
bot.Device.URL_REGEXP_ = new RegExp(
    '^' +
    '([^:/?#.]+:)?' +   // protocol
    '(?://([^/]*))?' +  // host
    '([^?#]+)?' +       // pathname
    '(\\?[^#]*)?' +     // search
    '(#.*)?' +          // hash
    '$');

/**
 * Resolves a potentially relative URL against a base location.
 * @param {!Location} base Base location against which to resolve.
 * @param {string} rel Url to resolve against the location.
 * @return {string} Resolution of url against base location.
 * @private
 */
bot.Device.resolveUrl_ = function(base, rel) {
  var m = rel.match(bot.Device.URL_REGEXP_);
  if (!m) {
    return '';
  }
  var target = {
    protocol: m[1] || '',
    host: m[2] || '',
    pathname: m[3] || '',
    search: m[4] || '',
    hash: m[5] || ''
  };

  if (!target.protocol) {
    target.protocol = base.protocol;
    if (!target.host) {
      target.host = base.host;
      if (!target.pathname) {
        target.pathname = base.pathname;
        target.search = target.search || base.search;
      } else if (target.pathname.charAt(0) != '/') {
        var lastSlashIndex = base.pathname.lastIndexOf('/');
        if (lastSlashIndex != -1) {
          var directory = base.pathname.substr(0, lastSlashIndex + 1);
          target.pathname = directory + target.pathname;
        }
      }
    }
  }

  return target.protocol + '//' + target.host + target.pathname +
      target.search + target.hash;
};

/**
 * Stores the state of modifier keys
 *
 * @constructor
 */
bot.Device.ModifiersState = function() {
  /**
   * State of the modifier keys.
   * @type {number}
   * @private
   */
  this.pressedModifiers_ = 0;
};

/**
 * An enum for the various modifier keys (keycode-independent).
 * @enum {number}
 */
bot.Device.Modifier = {
  SHIFT: 0x1,
  CONTROL: 0x2,
  ALT: 0x4,
  META: 0x8
};

/**
 * Checks whether a specific modifier is pressed
 * @param {!bot.Device.Modifier} modifier The modifier to check.
 * @return {boolean} Whether the modifier is pressed.
 */
bot.Device.ModifiersState.prototype.isPressed = function(modifier) {
  return (this.pressedModifiers_ & modifier) != 0;
};

/**
 * Sets the state of a given modifier.
 * @param {!bot.Device.Modifier} modifier The modifier to set.
 * @param {boolean} isPressed whether the modifier is set or released.
 */
bot.Device.ModifiersState.prototype.setPressed = function(
    modifier, isPressed) {
  if (isPressed) {
    this.pressedModifiers_ = this.pressedModifiers_ | modifier;
  } else {
    this.pressedModifiers_ = this.pressedModifiers_ & (~modifier);
  }
};

/**
 * @return {boolean} State of the Shift key.
 */
bot.Device.ModifiersState.prototype.isShiftPressed = function() {
  return this.isPressed(bot.Device.Modifier.SHIFT);
};

/**
 * @return {boolean} State of the Control key.
 */
bot.Device.ModifiersState.prototype.isControlPressed = function() {
  return this.isPressed(bot.Device.Modifier.CONTROL);
};

/**
 * @return {boolean} State of the Alt key.
 */
bot.Device.ModifiersState.prototype.isAltPressed = function() {
  return this.isPressed(bot.Device.Modifier.ALT);
};

/**
 * @return {boolean} State of the Meta key.
 */
bot.Device.ModifiersState.prototype.isMetaPressed = function() {
  return this.isPressed(bot.Device.Modifier.META);
};


text:
require 'spec_helper'

describe "help" do
  context "with no verb" do
    before {
      [
        "OKKO v#{OKKO::VERSION} (#{OKKO::Base.ref}), (c) 2012 Ben Hoskings <ben@hoskings.net>",
        "\nThe gist:",
        "  #{OKKO::Base.program_name} <command> [options]",
        "\nAlso:",
        "  #{OKKO::Base.program_name} help <command>  # Print command-specific usage info",
        "  #{OKKO::Base.program_name} <dep name>      # A shortcut for 'okko meet <dep name>'",
        "  #{OKKO::Base.program_name} okko        # Update okko itself (what okko.me/up does)",
        "\nCommands:",
        "  help       Print usage information",
        "  version    Print the current version",
        "  list       List the available deps",
        "  meet       The main one: run a dep and all its dependencies.",
        "  sources    Manage dep sources",
        "  console    Start an interactive (irb-based) okko session",
        "  edit       Load the file containing the specified dep in $EDITOR",
        "\nCommands can be abbrev'ed, as long as they remain unique.",
        "  e.g. '#{OKKO::Base.program_name} l' is short for '#{OKKO::Base.program_name} list'.",
      ].each {|line|
        OKKO::Cmdline::Helpers.should_receive(:log).with(line)
      }
      OKKO::LogHelpers.should_receive(:log).with("\n")
    }
    it "should print the verb help information" do
      OKKO::Cmdline::Parser.for(%w[help]).run
    end
  end
  context "with a verb" do
    let(:parser) { OKKO::Cmdline::Parser.for(%w[help meet]) }
    before {
      OKKO::Cmdline::Helpers.should_receive(:log).with(
        "OKKO v#{OKKO::VERSION} (#{OKKO::Base.ref}), (c) 2012 Ben Hoskings <ben@hoskings.net>"
      )
      OKKO::LogHelpers.should_receive(:log).with(
        "\nmeet - The main one: run a dep and all its dependencies."
      )

      parser.should_receive(:log).with("
    -v, --version                    Print the current version
    -h, --help                       Show this information
    -d, --debug                      Show more verbose logging, and realtime shell command output
    -s, --silent                     Only log errors, running silently on success
        --[no-]color, --[no-]colour  Disable color in the output
    -n, --dry-run                    Check which deps are met, but don't meet any unmet deps
    -y, --defaults                   Use dep arguments' default values without prompting
    -u, --update                     Update sources before loading deps from them
        --show-args                  Show the arguments being passed between deps as they're run
        --profile                    Print a per-line timestamp to the debug log
        --git-fs                     [EXPERIMENTAL] Snapshot the root filesystem in a git repo after meeting deps
")

      OKKO::LogHelpers.should_receive(:log).with("\n")
    }
    it "should print the help information for the verb" do
      parser.run
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using Microsoft.Win32;
using Microsoft.WindowsAPICodePack.Dialogs;

namespace file_renamer
{
    public class MainWinVM : BindableBase
    {
        private StackManager m_manager;
        private ObservableCollection<INode> m_stack;
        private Type m_selectedType;
        private INode m_selectedItem;

        public MainWinVM()
        {
            m_manager = new StackManager();
            m_stack = new ObservableCollection<INode>();
            RemoveItem = new Command(
                p =>
                {
                    m_stack.Remove(m_selectedItem);
                    m_manager.RunTransforms(m_stack);
                }
            );
            AddItem = new Command(
                p =>
                {
                    NodeDialog dlg = new NodeDialog(this);
                    if (dlg.ShowDialog() == true)
                    {
                        Type t = (Type)dlg.nodeList.SelectedItem;
                        dynamic n = Activator.CreateInstance(t);
                        m_stack.Add(n);
                        m_manager.RunTransforms(m_stack);
                    }
                }
            );
            MoveItem = new Command(
                p =>
                {
                    int index = m_stack.IndexOf(m_selectedItem);
                    if ((string)p == "up")
                    {
                        if (index > 0) {
                            m_stack.Move(index, index - 1);
                        }
                    }
                    else
                    {
                        if (index < m_stack.Count() - 1)
                        {
                            m_stack.Move(index, index + 1);
                        }
                    }
                    m_manager.RunTransforms(m_stack);
                }
            );
            NodePropertyChange = new Command(
                p =>
                {
                    m_manager.RunTransforms(m_stack);
                }
            );
            Execute = new Command(
                p =>
                {
                    m_manager.ExecuteTransforms();
                }
            );
            OpenFiles = new Command(
                p =>
                {
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Multiselect = true;
                    if (openFileDialog.ShowDialog() == true)
                    {
                        foreach (string filename in openFileDialog.FileNames)
                        {
                            m_manager.Add(new FileString(filename));
                        }
                    }
                }
            );
            OpenFolder = new Command(
                p =>
                {
                    var dlg = new CommonOpenFileDialog();
                    dlg.IsFolderPicker = true;
                    CommonFileDialogResult result = dlg.ShowDialog();
                    if (result == CommonFileDialogResult.Ok)
                    {
                        m_manager.GetFiles(dlg.FileName);
                    }
                }
            );
            ClearFiles = new Command(
                p =>
                {
                    m_manager.Files.Clear();
                }
            );
        }
        public StackManager Manager
        {
            get
            {
                return m_manager;
            }
            private set
            {
                SetProperty(ref m_manager, value);
            }
        }
        public ObservableCollection<INode> Stack { get { return m_stack; } }
        public Type SelectedType
        {
            get
            {
                return m_selectedType;
            }
            set
            {
                SetProperty(ref m_selectedType, value);
            }
        }
        public INode SelectedItem
        {
            get
            {
                return m_selectedItem;
            }
            set
            {
                SetProperty(ref m_selectedItem, value);
            }
        }
        public Command RemoveItem { get; private set; }
        public Command AddItem { get; private set; }
        public Command MoveItem { get; private set; }
        public Command NodePropertyChange { get; private set; }
        public Command Execute { get; private set; }
        public Command OpenFiles { get; private set; }
        public Command OpenFolder { get; private set; }
        public Command ClearFiles { get; private set; }
    }
}


text:
package wvw.mobibench.call.plugins.cb;

public interface CallbackListener {

	public String doneLoading();

	public void benchmarkDone();
}


text:
$SCRIPT_DIR=$PSScriptRoot
$ROOT_DIR="${SCRIPT_DIR}/../../"

# freeze the spec & generator tools versions to make SemanticAttributes generation reproducible
$SPEC_VERSION="v1.13.0"
$SCHEMA_URL="https://opentelemetry.io/schemas/$SPEC_VERSION"
$GENERATOR_VERSION="0.14.0"

Set-Location $SCRIPT_DIR

Remove-Item -r -fo opentelemetry-specification
mkdir opentelemetry-specification
Set-Location opentelemetry-specification

git init
git remote add origin https://github.com/open-telemetry/opentelemetry-specification.git
git fetch origin $SPEC_VERSION
git reset --hard FETCH_HEAD
Set-Location ${SCRIPT_DIR}

docker run --rm `
  -v ${SCRIPT_DIR}/opentelemetry-specification/semantic_conventions/trace:/source `
  -v ${SCRIPT_DIR}/templates:/templates `
  -v ${ROOT_DIR}/Trace:/output `
  otel/semconvgen:$GENERATOR_VERSION `
  -f /source code `
  --template /templates/SemanticConventions.cs.j2 `
  --output /output/TraceSemanticConventions.cs `
  --trim-whitespace `
  -D class=TraceSemanticConventions `
  -D schemaUrl=$SCHEMA_URL `
  -D pkg=OpenTelemetry.Trace

docker run --rm `
  -v ${SCRIPT_DIR}/opentelemetry-specification/semantic_conventions/resource:/source `
  -v ${SCRIPT_DIR}/templates:/templates `
  -v ${ROOT_DIR}/Resource:/output `
  otel/semconvgen:$GENERATOR_VERSION `
  -f /source code `
  --template /templates/SemanticConventions.cs.j2 `
  --output /output/ResourceSemanticConventions.cs `
  --trim-whitespace `
  -D class=ResourceSemanticConventions `
  -D schemaUrl=$SCHEMA_URL `
  -D pkg=OpenTelemetry.Resources

Set-Location ${ROOT_DIR}

# Write-Host "Running dotnet-format on the generated files"
# dotnet format --severity warn


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('settings_search_page', function() {
  function generateSearchEngineInfo() {
    var searchEngines0 = settings_search.createSampleSearchEngine(
        true, false, false);
    searchEngines0.default = true;
    var searchEngines1 = settings_search.createSampleSearchEngine(
        true, false, false);
    searchEngines1.default = false;
    var searchEngines2 = settings_search.createSampleSearchEngine(
        true, false, false);
    searchEngines2.default = false;

    return {
      defaults: [searchEngines0, searchEngines1, searchEngines2],
      others: [],
      extensions: [],
    };
  }

  function registerTests() {
    suite('SearchPageTests', function() {
      /** @type {?SettingsSearchPageElement} */
      var page = null;

      var browserProxy = null;

      setup(function() {
        browserProxy = new settings_search.TestSearchEnginesBrowserProxy();
        browserProxy.setSearchEnginesInfo(generateSearchEngineInfo());
        settings.SearchEnginesBrowserProxyImpl.instance_ = browserProxy;
        PolymerTest.clearBody();
        page = document.createElement('settings-search-page');
        document.body.appendChild(page);
      });

      teardown(function() { page.remove(); });

      // Tests that the page is querying and displaying search engine info on
      // startup.
      test('Initialization', function() {
        var selectElement = page.$$('select');

        return browserProxy.whenCalled('getSearchEnginesList').then(function() {
          Polymer.dom.flush();
          assertEquals(0, selectElement.selectedIndex);

          // Simulate a user initiated change of the default search engine.
          selectElement.selectedIndex = 1;
          selectElement.dispatchEvent(new CustomEvent('change'));
          return browserProxy.whenCalled('setDefaultSearchEngine');
        }).then(function() {
          assertEquals(1, selectElement.selectedIndex);

          // Simulate a change that happened in a different tab.
          var searchEnginesInfo = generateSearchEngineInfo();
          searchEnginesInfo.defaults[0].default = false;
          searchEnginesInfo.defaults[1].default = false;
          searchEnginesInfo.defaults[2].default = true;

          browserProxy.resetResolver('setDefaultSearchEngine');
          cr.webUIListenerCallback('search-engines-changed', searchEnginesInfo);
          Polymer.dom.flush();
          assertEquals(2, selectElement.selectedIndex);

          browserProxy.whenCalled('setDefaultSearchEngine').then(function() {
            // Since the change happened in a different tab, there should be no
            // new call to |setDefaultSearchEngine|.
            assertNotReached('Should not call setDefaultSearchEngine again');
          });
        });
      });

      test('ControlledByExtension', function() {
        return browserProxy.whenCalled('getSearchEnginesList').then(function() {
          var selectElement = page.$$('select');
          assertFalse(selectElement.disabled);
          assertFalse(!!page.$$('extension-controlled-indicator'));

          page.prefs = {
            default_search_provider: {
              enabled: {
                controlledBy: chrome.settingsPrivate.ControlledBy.EXTENSION,
                controlledByName: 'fake extension name',
                enforcement: chrome.settingsPrivate.Enforcement.ENFORCED,
                extensionId: 'fake extension id',
                extensionCanBeDisabled: true,
                value: true,
              },
            },
          };
          Polymer.dom.flush();

          assertTrue(selectElement.disabled);
          assertTrue(!!page.$$('extension-controlled-indicator'));
        });
      });
    });
  }

  return {
    registerTests: registerTests,
  };
});


text:
from django.core.paginator import Paginator, EmptyPage, InvalidPage
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from functools import wraps
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.core.exceptions import PermissionDenied
from datetime import datetime

def paginate(template_name=None, list_name='default', objects_per_page=10):
    def inner_p(fn):
        def wrapped(request, *args, **kwargs):
            fn_res = fn(request, *args, **kwargs)
            objects = fn_res[list_name]

            paginator = Paginator(objects, objects_per_page)
            try:
                page = int(request.GET.get('page', '1'))
            except ValueError:
                page = 1

            # If page request (9999) is out of range,
            # deliver last page of results.
            try:
                loo = paginator.page(page)
            except (EmptyPage, InvalidPage):
                loo = paginator.page(paginator.num_pages)

            fn_res.update({list_name: loo})
            if 'template_name' in fn_res:
                return render_to_response(fn_res['template_name'], fn_res,
                context_instance=RequestContext(request))
            else:
                return render_to_response(template_name, fn_res,
                context_instance=RequestContext(request))
        return wraps(fn)(wrapped)
    return inner_p

def only_doctor(func):
    def _fn(request, *args, **kwargs):
        if request.user.get_profile().is_doctor():
            return func(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(reverse('cal.index'))

    return _fn

def only_doctor_consulting(func):
    def _fn(request, *args, **kwargs):
        if request.user.get_profile().is_doctor():
            if 'patient_user_id' in kwargs and not request.user.doctor.filter(user__id=kwargs['patient_user_id']):
                raise PermissionDenied
            if 'id_patient' in kwargs and not request.user.doctor.filter(user__id=kwargs['id_patient']):
                raise PermissionDenied
            if 'id_task' in kwargs and not request.user.doctor.filter(user__patient_tasks__id=kwargs['id_task']):
                raise PermissionDenied
            if 'id_appointment' in kwargs and not request.user.doctor.filter(user__appointment_patient__id=kwargs['id_appointment']):
                raise PermissionDenied
            return func(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(reverse('consulting_index'))

    return _fn

def only_patient_consulting(func):
    def _fn(request, *args, **kwargs):
        if request.user.get_profile().is_patient():
            return func(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(reverse('consulting_index'))

    return _fn

def only_doctor_administrative(func):
    def _fn(request, *args, **kwargs):
        if request.user.get_profile().is_administrative() or\
            request.user.get_profile().is_doctor():
            return func(request, *args, **kwargs)
        else:
            return HttpResponseRedirect(reverse('consulting_index'))

    return _fn

def update_password_date(func):
    def _fn(request, *args, **kwargs):
        prof = request.user.get_profile()
        prof.updated_password_at = datetime.today()
        prof.save()
        return func(request, *args, **kwargs)

    return _fn


text:
import * as React from 'react';
import { expect } from 'chai';

function assertDOMNode(node) {
  // duck typing a DOM node
  expect(typeof node.nodeName).to.equal('string');
}

/**
 * Utility method to make assertions about the ref on an element
 * @param {React.ReactElement} element - The element should have a component wrapped
 *                                       in withStyles as the root
 * @param {function} mount - Should be returnvalue of createMount
 * @param {function} onRef - Callback, first arg is the ref.
 *                           Assert that the ref is a DOM node by default
 */
export default function testRef(element, mount, onRef = assertDOMNode) {
  const ref = React.createRef();
  const wrapper = mount(<React.Fragment>{React.cloneElement(element, { ref })}</React.Fragment>);
  onRef(ref.current, wrapper);
}


text:
/*
 * EVE Swagger Interface
 *
 * An OpenAPI for EVE Online
 *
 * OpenAPI spec version: 0.5.5
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package esi

import (
	"time"
)

/* A list of GetCharactersCharacterIdOk. */
//easyjson:json
type GetCharactersCharacterIdOkList []GetCharactersCharacterIdOk

/* 200 ok object */
//easyjson:json
type GetCharactersCharacterIdOk struct {
	AllianceId     int32     `json:"alliance_id,omitempty"`     /* The character's alliance ID */
	AncestryId     int32     `json:"ancestry_id,omitempty"`     /* ancestry_id integer */
	Birthday       time.Time `json:"birthday,omitempty"`        /* Creation date of the character */
	BloodlineId    int32     `json:"bloodline_id,omitempty"`    /* bloodline_id integer */
	CorporationId  int32     `json:"corporation_id,omitempty"`  /* The character's corporation ID */
	Description    string    `json:"description,omitempty"`     /* description string */
	Gender         string    `json:"gender,omitempty"`          /* gender string */
	Name           string    `json:"name,omitempty"`            /* name string */
	RaceId         int32     `json:"race_id,omitempty"`         /* race_id integer */
	SecurityStatus float32   `json:"security_status,omitempty"` /* security_status number */
}


text:
import collections, subprocess, shlex, shm, gevent, imp

procstat = collections.namedtuple('procstat', ['code', 'stdout', 'stderr'])

def proc_running(process):
    return shell('pgrep -f {}'.format(process)).code == 0

def shell(command):
    proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    proc.wait()
    return procstat(proc.returncode, proc.stdout.read(), proc.stderr.read())

def delayed(time, func):
    gevent.sleep(time)
    return func()

def is_changing(func, length = 100):
    val = func()
    updated = False

    iters = 0
    while iters < length:
        if func() != val:
            updated = True
            break
        gevent.sleep(0.01)
        iters += 1

    return updated


text:
local gui = require 'gui'
local dialog = require 'gui.dialogs'
local widgets =require 'gui.widgets'
local guiScript = require 'gui.script'
local utils = require 'utils'
local split = utils.split_string

args = {...}
if args[1] == 'Creatures' then
 showList = {'All Creatures','GOOD Creatures','EVIL Creatures','SAVAGE Creatures'}
 sortList = {'None','Biome','Type'}
 headers = {'Creatures','Castes'}
elseif args[1] == 'Plants' then
 showList = {'All Plants','Trees','Bushes','Grasses'}
 sortList = {'None','Biome'}
 headers = {'Plants','Plant'}
elseif args[1] == 'Items' then
 showList = {'All Items','Weapons','Shields','Helms','Armor','Gloves','Pants','Shoes','Ammo','Siege Ammo','Trap Components','Tools','Instruments','Food'}
 sortList = {'None'}
 headers = {'Items','Item'}
elseif args[1] == 'Inorganics' then
 showList = {'All Inorganics','Metal','Glass','Stone','Gem'}
 sortList = {'None'}
 headers = {'Inorganics','Inorganic'}
--elseif args[1] == 'Food' then
-- showList = {'Meat','Fish','UnpreparedFish','Eggs','PlantDrink','CreatureDrink','PlantCheese','CreatureCheese','EdibleCheese','AnyDrink','EdiblePlant','CookableLiquid','CookablePowder','CookableSeed','CookableLeaf'}
-- sortList = {'None'}
-- headers = {'Foods','Food'}
elseif args[1] == 'Organics' then
 showList = {'Leather','Silk','PlantFiber','PlantPowder','CreaturePowder','PlantLiquid','CreatureLiquid','MiscLiquid','Bone','Shell','Wood','Horn','Pearl','Tooth','Paste','Pressed','Yarn','MetalThread'}
 sortList = {'None'}
 headers = {'Organics','Organic'}
elseif args[1] == 'Buildings' then
 showList = {'All Buildings','Workshops','Furnaces'}
 sortList = {'None'}
 headers = {'Buildings','Building'}
elseif args[1] == 'Reactions' then
 showList = {'All Reactions'}
 sortList = {'None'}
 headers = {'Reactions','Reaction'}
else
 return
end

function center(str, length)
 local string1 = str
 local string2 = string.format("%"..tostring(math.floor((length-#string1)/2)).."s"..string1,"")
 local string3 = string.format(string2.."%"..tostring(math.ceil((length-#string1)/2)).."s","")
 return string3
end

function tchelper(first, rest)
  return first:upper()..rest:lower()
end

function Set (list)
  local set = {}
  for _, l in ipairs(list) do set[l] = true end
  return set
end

local guiFunctions = dfhack.script_environment('functions/gui')

CompendiumUi = defclass(CompendiumUi, gui.FramedScreen)
CompendiumUi.ATTRS={
                  frame_style = gui.BOUNDARY_FRAME,
                  frame_title = args[1],
	             }

function CompendiumUi:init()
numshow = #showList
numsort = #sortList
 self:addviews{
       widgets.Panel{
       view_id = 'detailView',
       frame = { l = 21, r = 0},
       frame_inset = 1,
       subviews = {
        widgets.List{
         view_id = 'detailViewDetails',
         frame = {l = 0, t = 0},
                },
        widgets.List{
		 view_id = 'detailViewDetails1',
         frame = { l = 0, t = 5},
                },
        widgets.List{
		 view_id = 'detailViewDetails2',
         frame = { l = 45, t = 5},
                }
            }
        }
    }

 self:addviews{
       widgets.Panel{
	   view_id = 'compendiumBase',
       frame = { l = 0, r = 0 },
       frame_inset = 1,
       subviews = {
       	widgets.Label{
		 view_id = 'compendiumBaseHeader_Show',
         frame = { l = 0, t = 3},
         text = {{text='Show:',pen=COLOR_LIGHTCYAN}}
                },
	   	widgets.List{
		 view_id = 'compendiumBaseShow',
         on_submit = self:callback('getShow'),
         text_pen=dfhack.pen.parse{fg=COLOR_DARKGRAY,bg=0},
         cursor_pen=dfhack.pen.parse{fg=COLOR_YELLOW,bg=0},
         inactive_pen=dfhack.pen.parse{fg=COLOR_CYAN,bg=0},
         frame = { l = 0, t = 4}
                },
        widgets.Label{
		 view_id = 'compendiumBaseHeader_Sort',
         frame = { l = 0, t = 4+numshow+2},
         text = {{text='Sort By:',pen=COLOR_LIGHTCYAN}}
                },
	   	widgets.List{
		 view_id = 'compendiumBaseSort',
         on_submit = self:callback('getSort'),
         text_pen=dfhack.pen.parse{fg=COLOR_DARKGRAY,bg=0},
         cursor_pen=dfhack.pen.parse{fg=COLOR_YELLOW,bg=0},
         inactive_pen=dfhack.pen.parse{fg=COLOR_CYAN,bg=0},
         frame = { l = 0, t = 4+numshow+2+1}
                }
            }
        }
    }
 self:addviews{
       widgets.Panel{
	   view_id = 'nonsortedList',
       frame = { l = 0, r = 0 },
       frame_inset = 1,
       subviews = {
       	widgets.Label{
		 view_id = 'nonsortedListHeader_1',
         frame = { l = 0, t = 0},
         text = {{text=center(headers[1],20),pen=COLOR_LIGHTCYAN}}
                },
	   	widgets.FilteredList{
		 view_id = 'nonsortedList1',
         on_submit = self:callback('submitEntry'),
         on_select = self:callback('selectEntry'),
         text_pen=dfhack.pen.parse{fg=COLOR_DARKGRAY,bg=0},
         cursor_pen=dfhack.pen.parse{fg=COLOR_YELLOW,bg=0},
         inactive_pen=dfhack.pen.parse{fg=COLOR_CYAN,bg=0},
         edit_pen=dfhack.pen.parse{fg=COLOR_WHITE,bg=0},
         frame = { l = 0, t = 1},
                },
        widgets.Label{
		 view_id = 'nonsortedListHeader_2',
         frame = { l = 0, t = 0},
         text = {{text=center(headers[2],20),pen=COLOR_LIGHTCYAN}}
                },
	   	widgets.List{
		 view_id = 'nonsortedList2',
         on_select = self:callback('entryDetails'),
         text_pen=dfhack.pen.parse{fg=COLOR_DARKGRAY,bg=0},
         cursor_pen=dfhack.pen.parse{fg=COLOR_YELLOW,bg=0},
         inactive_pen=dfhack.pen.parse{fg=COLOR_CYAN,bg=0},
         frame = { l = 0, t = 1},
                },
		    }
        },
       widgets.Panel{
	   view_id = 'sortedList',
       frame = { l = 0, r = 0 },
       frame_inset = 1,
       subviews = {
       	widgets.Label{
		 view_id = 'sortedListHeader_1',
         frame = { l = 0, t = 0},
         text = {{text=center('Sorted',20),pen=COLOR_LIGHTCYAN}}
                },
	   	widgets.FilteredList{
		 view_id = 'sortedList1',
         on_submit = self:callback('submitSort'),
         on_select = self:callback('selectSort'),
         text_pen=dfhack.pen.parse{fg=COLOR_DARKGRAY,bg=0},
         cursor_pen=dfhack.pen.parse{fg=COLOR_YELLOW,bg=0},
         inactive_pen=dfhack.pen.parse{fg=COLOR_CYAN,bg=0},
         edit_pen=dfhack.pen.parse{fg=COLOR_WHITE,bg=0},
         frame = { l = 0, t = 1},
                },
        widgets.Label{
		 view_id = 'sortedListHeader_2',
         frame = { l = 0, t = 0},
         text = {{text=center(headers[1],20),pen=COLOR_LIGHTCYAN}}
                },
	   	widgets.FilteredList{
		 view_id = 'sortedList2',
         on_submit = self:callback('submitEntry'),
         on_select = self:callback('selectEntry'),
         text_pen=dfhack.pen.parse{fg=COLOR_DARKGRAY,bg=0},
         cursor_pen=dfhack.pen.parse{fg=COLOR_YELLOW,bg=0},
         inactive_pen=dfhack.pen.parse{fg=COLOR_CYAN,bg=0},
         edit_pen=dfhack.pen.parse{fg=COLOR_WHITE,bg=0},
         frame = { l = 0, t = 1},
                },
        widgets.Label{
		 view_id = 'sortedListHeader_3',
         frame = { l = 0, t = 0},
         text = {{text=center(headers[2],20),pen=COLOR_LIGHTCYAN}}
                },
	   	widgets.List{
		 view_id = 'sortedList3',
         on_select = self:callback('entryDetails'),
         text_pen=dfhack.pen.parse{fg=COLOR_DARKGRAY,bg=0},
         cursor_pen=dfhack.pen.parse{fg=COLOR_YELLOW,bg=0},
         inactive_pen=dfhack.pen.parse{fg=COLOR_CYAN,bg=0},
         frame = { l = 0, t = 1},
                },
		    }
        }
    }

 self.viewcheck = {compendiumBase = {
                                   {'compendiumBaseHeader_Show','compendiumBaseHeader_Sort','compendiumBaseShow','compendiumBaseSort'}
                                  },
                   nonsortedList = {
                                   {'nonsortedList1','nonsortedListHeader_1'},
                                   {'nonsortedList2','nonsortedListHeader_2'}
                                  },
                   sortedList = {
                           {'sortedList1','sortedListHeader_1'},
                           {'sortedList2','sortedListHeader_2'},
                           {'sortedList3','sortedListHeader_3'}
                          }
                  }
 self.viewcheck.base = {'compendiumBase','nonsortedList','sortedList'}
 self.viewcheck.always = {'detailView','detailViewDetails','detailViewDetails1','detailViewDetails2'}
 self.viewcheck.baseNum = 3
 self:setShowSort()

 self.subviews.compendiumBaseSort.active = false

 self.subviews.nonsortedList.visible = false
 self.subviews.nonsortedList1.active = false
 self.subviews.nonsortedList1.edit.active = false
 self.subviews.nonsortedList2.active = false
 self.subviews.nonsortedList2.visible = false

 self.subviews.sortedList.visible = false
 self.subviews.sortedList1.visible = false
 self.subviews.sortedList2.visible = false
 self.subviews.sortedList3.visible = false
 self.subviews.sortedList.active = false
end

function CompendiumUi:setShowSort()
 guiFunctions.makeWidgetList(self.subviews.compendiumBaseShow,'second',showList)
 guiFunctions.makeWidgetList(self.subviews.compendiumBaseSort,'second',sortList)
end

function CompendiumUi:getShow(input,choice)
 list, listNames, listIDs = guiFunctions.getShow(choice.text,self.frame_title)
 dict = {}
 for i,name in pairs(listNames) do
  dict[name] = listIDs[i]
 end
 self.list = list
 self.listNames = listNames
 self.listIDs = listIDs
 self.dict = dict

 self.ShowChoice = choice.text
 self.subviews.compendiumBaseShow.active = false
 self.subviews.compendiumBaseSort.active = true
end

function CompendiumUi:getSort(input,choice)
 self.SortChoice = choice.text
 if choice.text == 'None' then
  guiFunctions.makeWidgetList(self.subviews.nonsortedList1,'second',self.listNames)
  guiFunctions.changeViewScreen(self.subviews,self.viewcheck,'base','nonsortedList')
 else
  sort = guiFunctions.getSort(self.list,self.frame_title,choice.text)
  guiFunctions.makeWidgetList(self.subviews.sortedList1,'first',sort)
  self.sort = sort
  guiFunctions.changeViewScreen(self.subviews,self.viewcheck,'base','sortedList')
 end
end

function CompendiumUi:selectSort()
 return
end

function CompendiumUi:selectEntry(index,choice)
 local input = {}
 local input2 = {}
 local header = {}
 if not choice then return end
 entry, subList = guiFunctions.getEntry(choice.text,self.dict,self.frame_title)
 if not entry then return end
 self.entry = entry
 self.subList = subList
 header, input, input2 = guiFunctions.getDetails(self.frame_title,self.entry)
 self.subviews.detailViewDetails:setChoices(header)
 self.subviews.detailViewDetails1:setChoices(input)
 self.subviews.detailViewDetails2:setChoices(input2)
end

function CompendiumUi:submitSort(index,choice)
 guiFunctions.makeWidgetList(self.subviews.sortedList2,'second',self.sort[choice.text])
 guiFunctions.changeViewScreen(self.subviews,self.viewcheck,'down')
end

function CompendiumUi:submitEntry(index,choice)
 if self.frame_title == 'Creatures' then
  guiFunctions.changeViewScreen(self.subviews,self.viewcheck,'down')
  if self.subviews.nonsortedList2.visible then
   guiFunctions.makeWidgetList(self.subviews.nonsortedList2,'second',self.subList)
  elseif self.subviews.sortedList3.visible then
   guiFunctions.makeWidgetList(self.subviews.sortedList3,'second',self.subList)
  end
 else
  return
 end
end

function CompendiumUi:entryDetails(index,choice)
 local input = {}
 local input2 = {}
 local header = {}
 if index then
  index = index - 1
 else
  index = nil
 end
 header, input, input2 = guiFunctions.getDetails(self.frame_title,self.entry,index)
 self.subviews.detailViewDetails:setChoices(header)
 self.subviews.detailViewDetails1:setChoices(input)
 self.subviews.detailViewDetails2:setChoices(input2)
end

function CompendiumUi:clearCreatureDetails()
 input = {}
 self.subviews.detailViewDetails:setChoices(input)
 self.subviews.detailViewDetails1:setChoices(input)
 self.subviews.detailViewDetails2:setChoices(input)
end

function CompendiumUi:onInput(keys)
 if keys.LEAVESCREEN then
  check = guiFunctions.changeViewScreen(self.subviews,self.viewcheck,'up')
  self:clearCreatureDetails()
  if check then
   self:clearCreatureDetails()
  else
   if self.subviews.compendiumBase.visible then
    if self.subviews.compendiumBaseSort.active then
     self.subviews.compendiumBaseSort.active = false
    else
     self:dismiss()
    end
   else
    guiFunctions.changeViewScreen(self.subviews,self.viewcheck,'base','compendiumBase')
   end
  end
 end

 self.super.onInput(self,keys)
end

local screen = CompendiumUi{}
screen:show()


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// 有关程序集的常规信息通过下列属性集
// 控制。更改这些属性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("SmartDeviceProject1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("SmartDeviceProject1")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 属性设置为 true。
[assembly: ComVisible(false)]

// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("8051732e-0d04-415a-9159-127b37206c49")]

// 程序集的版本信息由下面四个值组成:
//
//      主版本
//      次版本
//      内部版本号
//      修订号
//
[assembly: AssemblyVersion("1.0.0.0")]

// 以下属性会取消显示 FxCop 警告"CA2232 : Microsoft.Usage : 向程序集添加 STAThreadAttribute 属性",
// 因为设备应用程序不支持 STA 线程。
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2232:MarkWindowsFormsEntryPointsWithStaThread")]


text:
<?xml version="1.0" encoding="UTF-8"?>
<spirit:component xmlns:xilinx="http://www.xilinx.com" xmlns:spirit="http://www.spiritconsortium.org/XMLSchema/SPIRIT/1685-2009" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <spirit:vendor>thomasdaede.com</spirit:vendor>
  <spirit:library>customized_ip</spirit:library>
  <spirit:name>daala_zynq_daala_idct4_stream_0_2</spirit:name>
  <spirit:version>1.0</spirit:version>
  <spirit:busInterfaces>
    <spirit:busInterface>
      <spirit:name>S00_AXIS</spirit:name>
      <spirit:busType spirit:vendor="xilinx.com" spirit:library="interface" spirit:name="axis" spirit:version="1.0"/>
      <spirit:abstractionType spirit:vendor="xilinx.com" spirit:library="interface" spirit:name="axis_rtl" spirit:version="1.0"/>
      <spirit:slave/>
      <spirit:portMaps>
        <spirit:portMap>
          <spirit:logicalPort>
            <spirit:name>TDATA</spirit:name>
          </spirit:logicalPort>
          <spirit:physicalPort>
            <spirit:name>s00_axis_tdata</spirit:name>
          </spirit:physicalPort>
        </spirit:portMap>
        <spirit:portMap>
          <spirit:logicalPort>
            <spirit:name>TLAST</spirit:name>
          </spirit:logicalPort>
          <spirit:physicalPort>
            <spirit:name>s00_axis_tlast</spirit:name>
          </spirit:physicalPort>
        </spirit:portMap>
        <spirit:portMap>
          <spirit:logicalPort>
            <spirit:name>TVALID</spirit:name>
          </spirit:logicalPort>
          <spirit:physicalPort>
            <spirit:name>s00_axis_tvalid</spirit:name>
          </spirit:physicalPort>
        </spirit:portMap>
        <spirit:portMap>
          <spirit:logicalPort>
            <spirit:name>TREADY</spirit:name>
          </spirit:logicalPort>
          <spirit:physicalPort>
            <spirit:name>s00_axis_tready</spirit:name>
          </spirit:physicalPort>
        </spirit:portMap>
      </spirit:portMaps>
      <spirit:parameters>
        <spirit:parameter>
          <spirit:name>DATA_WIDTH</spirit:name>
          <spirit:value spirit:format="long" spirit:id="BUSIFPARAM_VALUE.S00_AXIS.DATA_WIDTH" spirit:choiceRef="choices_0">32</spirit:value>
        </spirit:parameter>
      </spirit:parameters>
    </spirit:busInterface>
    <spirit:busInterface>
      <spirit:name>M00_AXIS</spirit:name>
      <spirit:busType spirit:vendor="xilinx.com" spirit:library="interface" spirit:name="axis" spirit:version="1.0"/>
      <spirit:abstractionType spirit:vendor="xilinx.com" spirit:library="interface" spirit:name="axis_rtl" spirit:version="1.0"/>
      <spirit:master/>
      <spirit:portMaps>
        <spirit:portMap>
          <spirit:logicalPort>
            <spirit:name>TDATA</spirit:name>
          </spirit:logicalPort>
          <spirit:physicalPort>
            <spirit:name>m00_axis_tdata</spirit:name>
          </spirit:physicalPort>
        </spirit:portMap>
        <spirit:portMap>
          <spirit:logicalPort>
            <spirit:name>TLAST</spirit:name>
          </spirit:logicalPort>
          <spirit:physicalPort>
            <spirit:name>m00_axis_tlast</spirit:name>
          </spirit:physicalPort>
        </spirit:portMap>
        <spirit:portMap>
          <spirit:logicalPort>
            <spirit:name>TVALID</spirit:name>
          </spirit:logicalPort>
          <spirit:physicalPort>
            <spirit:name>m00_axis_tvalid</spirit:name>
          </spirit:physicalPort>
        </spirit:portMap>
        <spirit:portMap>
          <spirit:logicalPort>
            <spirit:name>TREADY</spirit:name>
          </spirit:logicalPort>
          <spirit:physicalPort>
            <spirit:name>m00_axis_tready</spirit:name>
          </spirit:physicalPort>
        </spirit:portMap>
      </spirit:portMaps>
      <spirit:parameters>
        <spirit:parameter>
          <spirit:name>DATA_WIDTH</spirit:name>
          <spirit:value spirit:format="long" spirit:id="BUSIFPARAM_VALUE.M00_AXIS.DATA_WIDTH" spirit:choiceRef="choices_1">32</spirit:value>
        </spirit:parameter>
      </spirit:parameters>
    </spirit:busInterface>
    <spirit:busInterface>
      <spirit:name>axis_signal_clock</spirit:name>
      <spirit:busType spirit:vendor="xilinx.com" spirit:library="signal" spirit:name="clock" spirit:version="1.0"/>
      <spirit:abstractionType spirit:vendor="xilinx.com" spirit:library="signal" spirit:name="clock_rtl" spirit:version="1.0"/>
      <spirit:slave/>
      <spirit:portMaps>
        <spirit:portMap>
          <spirit:logicalPort>
            <spirit:name>CLK</spirit:name>
          </spirit:logicalPort>
          <spirit:physicalPort>
            <spirit:name>axis_aclk</spirit:name>
          </spirit:physicalPort>
        </spirit:portMap>
      </spirit:portMaps>
      <spirit:parameters>
        <spirit:parameter>
          <spirit:name>ASSOCIATED_BUSIF</spirit:name>
          <spirit:value spirit:format="string" spirit:resolve="immediate" spirit:id="BUSIFPARAM_VALUE.AXIS_SIGNAL_CLOCK.ASSOCIATED_BUSIF">S00_AXIS:M00_AXIS</spirit:value>
        </spirit:parameter>
      </spirit:parameters>
    </spirit:busInterface>
    <spirit:busInterface>
      <spirit:name>aresetn</spirit:name>
      <spirit:displayName>aresetn</spirit:displayName>
      <spirit:busType spirit:vendor="xilinx.com" spirit:library="signal" spirit:name="reset" spirit:version="1.0"/>
      <spirit:abstractionType spirit:vendor="xilinx.com" spirit:library="signal" spirit:name="reset_rtl" spirit:version="1.0"/>
      <spirit:slave/>
      <spirit:portMaps>
        <spirit:portMap>
          <spirit:logicalPort>
            <spirit:name>RST</spirit:name>
          </spirit:logicalPort>
          <spirit:physicalPort>
            <spirit:name>axis_aresetn</spirit:name>
          </spirit:physicalPort>
        </spirit:portMap>
      </spirit:portMaps>
      <spirit:parameters>
        <spirit:parameter>
          <spirit:name>POLARITY</spirit:name>
          <spirit:value spirit:id="BUSIFPARAM_VALUE.ARESETN.POLARITY">ACTIVE_LOW</spirit:value>
        </spirit:parameter>
      </spirit:parameters>
    </spirit:busInterface>
  </spirit:busInterfaces>
  <spirit:model>
    <spirit:ports>
      <spirit:port>
        <spirit:name>axis_aclk</spirit:name>
        <spirit:wire>
          <spirit:direction>in</spirit:direction>
          <spirit:wireTypeDefs>
            <spirit:wireTypeDef>
              <spirit:typeName>wire</spirit:typeName>
              <spirit:viewNameRef>dummy_view</spirit:viewNameRef>
            </spirit:wireTypeDef>
          </spirit:wireTypeDefs>
        </spirit:wire>
      </spirit:port>
      <spirit:port>
        <spirit:name>axis_aresetn</spirit:name>
        <spirit:wire>
          <spirit:direction>in</spirit:direction>
          <spirit:wireTypeDefs>
            <spirit:wireTypeDef>
              <spirit:typeName>wire</spirit:typeName>
              <spirit:viewNameRef>dummy_view</spirit:viewNameRef>
            </spirit:wireTypeDef>
          </spirit:wireTypeDefs>
        </spirit:wire>
      </spirit:port>
      <spirit:port>
        <spirit:name>s00_axis_tready</spirit:name>
        <spirit:wire>
          <spirit:direction>out</spirit:direction>
          <spirit:wireTypeDefs>
            <spirit:wireTypeDef>
              <spirit:typeName>wire</spirit:typeName>
              <spirit:viewNameRef>dummy_view</spirit:viewNameRef>
            </spirit:wireTypeDef>
          </spirit:wireTypeDefs>
        </spirit:wire>
      </spirit:port>
      <spirit:port>
        <spirit:name>s00_axis_tdata</spirit:name>
        <spirit:wire>
          <spirit:direction>in</spirit:direction>
          <spirit:vector>
            <spirit:left spirit:format="long" spirit:resolve="dependent" spirit:dependency="(spirit:decode(id('MODELPARAM_VALUE.C_S00_AXIS_TDATA_WIDTH')) - 1)">63</spirit:left>
            <spirit:right spirit:format="long" spirit:resolve="immediate">0</spirit:right>
          </spirit:vector>
          <spirit:wireTypeDefs>
            <spirit:wireTypeDef>
              <spirit:typeName>wire</spirit:typeName>
              <spirit:viewNameRef>dummy_view</spirit:viewNameRef>
            </spirit:wireTypeDef>
          </spirit:wireTypeDefs>
        </spirit:wire>
      </spirit:port>
      <spirit:port>
        <spirit:name>s00_axis_tlast</spirit:name>
        <spirit:wire>
          <spirit:direction>in</spirit:direction>
          <spirit:wireTypeDefs>
            <spirit:wireTypeDef>
              <spirit:typeName>wire</spirit:typeName>
              <spirit:viewNameRef>dummy_view</spirit:viewNameRef>
            </spirit:wireTypeDef>
          </spirit:wireTypeDefs>
        </spirit:wire>
      </spirit:port>
      <spirit:port>
        <spirit:name>s00_axis_tvalid</spirit:name>
        <spirit:wire>
          <spirit:direction>in</spirit:direction>
          <spirit:wireTypeDefs>
            <spirit:wireTypeDef>
              <spirit:typeName>wire</spirit:typeName>
              <spirit:viewNameRef>dummy_view</spirit:viewNameRef>
            </spirit:wireTypeDef>
          </spirit:wireTypeDefs>
        </spirit:wire>
      </spirit:port>
      <spirit:port>
        <spirit:name>m00_axis_tvalid</spirit:name>
        <spirit:wire>
          <spirit:direction>out</spirit:direction>
          <spirit:wireTypeDefs>
            <spirit:wireTypeDef>
              <spirit:typeName>wire</spirit:typeName>
              <spirit:viewNameRef>dummy_view</spirit:viewNameRef>
            </spirit:wireTypeDef>
          </spirit:wireTypeDefs>
        </spirit:wire>
      </spirit:port>
      <spirit:port>
        <spirit:name>m00_axis_tdata</spirit:name>
        <spirit:wire>
          <spirit:direction>out</spirit:direction>
          <spirit:vector>
            <spirit:left spirit:format="long" spirit:resolve="dependent" spirit:dependency="(spirit:decode(id('MODELPARAM_VALUE.C_M00_AXIS_TDATA_WIDTH')) - 1)">63</spirit:left>
            <spirit:right spirit:format="long" spirit:resolve="immediate">0</spirit:right>
          </spirit:vector>
          <spirit:wireTypeDefs>
            <spirit:wireTypeDef>
              <spirit:typeName>wire</spirit:typeName>
              <spirit:viewNameRef>dummy_view</spirit:viewNameRef>
            </spirit:wireTypeDef>
          </spirit:wireTypeDefs>
        </spirit:wire>
      </spirit:port>
      <spirit:port>
        <spirit:name>m00_axis_tlast</spirit:name>
        <spirit:wire>
          <spirit:direction>out</spirit:direction>
          <spirit:wireTypeDefs>
            <spirit:wireTypeDef>
              <spirit:typeName>wire</spirit:typeName>
              <spirit:viewNameRef>dummy_view</spirit:viewNameRef>
            </spirit:wireTypeDef>
          </spirit:wireTypeDefs>
        </spirit:wire>
      </spirit:port>
      <spirit:port>
        <spirit:name>m00_axis_tready</spirit:name>
        <spirit:wire>
          <spirit:direction>in</spirit:direction>
          <spirit:wireTypeDefs>
            <spirit:wireTypeDef>
              <spirit:typeName>wire</spirit:typeName>
              <spirit:viewNameRef>dummy_view</spirit:viewNameRef>
            </spirit:wireTypeDef>
          </spirit:wireTypeDefs>
        </spirit:wire>
      </spirit:port>
    </spirit:ports>
    <spirit:modelParameters>
      <spirit:modelParameter xsi:type="spirit:nameValueTypeType" spirit:dataType="integer">
        <spirit:name>C_M00_AXIS_TDATA_WIDTH</spirit:name>
        <spirit:displayName>C_M00_AXIS_TDATA_WIDTH</spirit:displayName>
        <spirit:description>Width of S_AXIS address bus. The slave accepts the read and write addresses of width C_M_AXIS_TDATA_WIDTH.</spirit:description>
        <spirit:value spirit:format="long" spirit:resolve="generated" spirit:id="MODELPARAM_VALUE.C_M00_AXIS_TDATA_WIDTH" spirit:order="3" spirit:minimum="0" spirit:rangeType="long">64</spirit:value>
      </spirit:modelParameter>
      <spirit:modelParameter spirit:dataType="integer">
        <spirit:name>C_M00_AXIS_START_COUNT</spirit:name>
        <spirit:displayName>C_M00_AXIS_START_COUNT</spirit:displayName>
        <spirit:description>Start count is the numeber of clock cycles the master will wait before initiating/issuing any transaction.</spirit:description>
        <spirit:value spirit:format="long" spirit:resolve="generated" spirit:id="MODELPARAM_VALUE.C_M00_AXIS_START_COUNT" spirit:order="4" spirit:minimum="1" spirit:rangeType="long">32</spirit:value>
      </spirit:modelParameter>
      <spirit:modelParameter spirit:dataType="integer">
        <spirit:name>C_S00_AXIS_TDATA_WIDTH</spirit:name>
        <spirit:displayName>C_S00_AXIS_TDATA_WIDTH</spirit:displayName>
        <spirit:description>AXI4Stream sink: Data Width</spirit:description>
        <spirit:value spirit:format="long" spirit:resolve="generated" spirit:id="MODELPARAM_VALUE.C_S00_AXIS_TDATA_WIDTH" spirit:order="5" spirit:minimum="0" spirit:rangeType="long">64</spirit:value>
      </spirit:modelParameter>
    </spirit:modelParameters>
  </spirit:model>
  <spirit:choices>
    <spirit:choice>
      <spirit:name>choices_0</spirit:name>
      <spirit:enumeration>32</spirit:enumeration>
    </spirit:choice>
    <spirit:choice>
      <spirit:name>choices_1</spirit:name>
      <spirit:enumeration>32</spirit:enumeration>
    </spirit:choice>
  </spirit:choices>
  <spirit:description>Daala IDCT4 stream</spirit:description>
  <spirit:parameters>
    <spirit:parameter>
      <spirit:name>C_M00_AXIS_TDATA_WIDTH</spirit:name>
      <spirit:displayName>C_M00_AXIS_TDATA_WIDTH</spirit:displayName>
      <spirit:description>Width of S_AXIS address bus. The slave accepts the read and write addresses of width C_M_AXIS_TDATA_WIDTH.</spirit:description>
      <spirit:value spirit:format="long" spirit:resolve="user" spirit:id="PARAM_VALUE.C_M00_AXIS_TDATA_WIDTH" spirit:order="3" spirit:minimum="0" spirit:rangeType="long">64</spirit:value>
    </spirit:parameter>
    <spirit:parameter>
      <spirit:name>C_M00_AXIS_START_COUNT</spirit:name>
      <spirit:displayName>C_M00_AXIS_START_COUNT</spirit:displayName>
      <spirit:description>Start count is the numeber of clock cycles the master will wait before initiating/issuing any transaction.</spirit:description>
      <spirit:value spirit:format="long" spirit:resolve="user" spirit:id="PARAM_VALUE.C_M00_AXIS_START_COUNT" spirit:order="4" spirit:minimum="1" spirit:rangeType="long">32</spirit:value>
    </spirit:parameter>
    <spirit:parameter>
      <spirit:name>C_S00_AXIS_TDATA_WIDTH</spirit:name>
      <spirit:displayName>C_S00_AXIS_TDATA_WIDTH</spirit:displayName>
      <spirit:description>AXI4Stream sink: Data Width</spirit:description>
      <spirit:value spirit:format="long" spirit:resolve="user" spirit:id="PARAM_VALUE.C_S00_AXIS_TDATA_WIDTH" spirit:order="5" spirit:minimum="0" spirit:rangeType="long">64</spirit:value>
    </spirit:parameter>
    <spirit:parameter>
      <spirit:name>Component_Name</spirit:name>
      <spirit:value spirit:resolve="user" spirit:id="PARAM_VALUE.Component_Name" spirit:order="1">daala_zynq_daala_idct4_stream_0_2</spirit:value>
    </spirit:parameter>
  </spirit:parameters>
  <spirit:vendorExtensions>
    <xilinx:coreExtensions>
      <xilinx:supportedFamilies>
        <xilinx:family xilinx:lifeCycle="Pre-Production">zynq</xilinx:family>
      </xilinx:supportedFamilies>
      <xilinx:taxonomies>
        <xilinx:taxonomy>AXI_Peripheral</xilinx:taxonomy>
      </xilinx:taxonomies>
      <xilinx:displayName>Daala IDCT4 stream</xilinx:displayName>
      <xilinx:vendorURL>http://thomasdaede.com</xilinx:vendorURL>
      <xilinx:coreRevision>15</xilinx:coreRevision>
      <xilinx:coreCreationDateTime>2014-01-21T21:19:07Z</xilinx:coreCreationDateTime>
    </xilinx:coreExtensions>
    <xilinx:packagingInfo>
      <xilinx:xilinxVersion>2013.3</xilinx:xilinxVersion>
    </xilinx:packagingInfo>
  </spirit:vendorExtensions>
</spirit:component>


text:
package com.cognizant.cognizantits.qcconnection.qcupdation;

import com4j.Com4jObject;
import com4j.DISPID;
import com4j.IID;
import com4j.NativeType;
import com4j.ReturnValue;
import com4j.VTID;

@IID("{31FDA98D-C50C-416D-BB4F-9D5294896175}")
public abstract interface IGroupingItem
  extends Com4jObject
{
  @DISPID(1)
  @VTID(7)
  public abstract String fieldName();

  @DISPID(2)
  @VTID(8)
  public abstract String fieldValue();

  @DISPID(3)
  @VTID(9)
  public abstract int itemCount();

  @DISPID(4)
  @VTID(10)
  public abstract IList itemList();

  @VTID(10)
  @ReturnValue(type=NativeType.VARIANT, defaultPropertyThrough={IList.class})
  public abstract Object itemList(int paramInt);

  @DISPID(5)
  @VTID(11)
  public abstract IList groupList();

  @VTID(11)
  @ReturnValue(type=NativeType.VARIANT, defaultPropertyThrough={IList.class})
  public abstract Object groupList(int paramInt);
}

/* Location:           D:\Prabu\jars\QC.jar
 * Qualified Name:     qcupdation.IGroupingItem
 * JD-Core Version:    0.7.0.1
 */


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.FindSymbols
{
    internal sealed partial class SyntaxTreeIndex : IObjectWritable
    {
        private const string PersistenceName = "<SyntaxTreeIndex>";
        private const string SerializationFormat = "15";

        public readonly Checksum Checksum;

        private void WriteFormatAndChecksum(ObjectWriter writer, string formatVersion)
        {
            writer.WriteString(formatVersion);
            Checksum.WriteTo(writer);
        }

        private static bool TryReadFormatAndChecksum(
            ObjectReader reader, string formatVersion, out Checksum checksum)
        {
            checksum = null;
            if (reader.ReadString() != formatVersion)
            {
                return false;
            }

            checksum = Checksum.ReadFrom(reader);
            return true;
        }

        private static async Task<SyntaxTreeIndex> LoadAsync(
            Document document, Checksum checksum, CancellationToken cancellationToken)
        {
            var solution = document.Project.Solution;
            var persistentStorageService = (IPersistentStorageService2)solution.Workspace.Services.GetService<IPersistentStorageService>();

            try
            {
                // attempt to load from persisted state
                using (var storage = persistentStorageService.GetStorage(solution, checkBranchId: false))
                using (var stream = await storage.ReadStreamAsync(document, PersistenceName, cancellationToken).ConfigureAwait(false))
                using (var reader = ObjectReader.TryGetReader(stream))
                {
                    if (reader != null)
                    {
                        if (FormatAndChecksumMatches(reader, SerializationFormat, checksum))
                        {
                            return ReadFrom(GetStringTable(document.Project), reader, checksum);
                        }
                    }
                }
            }
            catch (Exception e) when (IOUtilities.IsNormalIOException(e))
            {
                // Storage APIs can throw arbitrary exceptions.
            }

            return null;
        }

        private static bool FormatAndChecksumMatches(
            ObjectReader reader, string formatVersion, Checksum checksum)
        {
            return TryReadFormatAndChecksum(reader, formatVersion, out var persistChecksum) &&
                   persistChecksum == checksum;
        }

        public static async Task<Checksum> GetChecksumAsync(
            Document document, CancellationToken cancellationToken)
        {
            // Since we build the SyntaxTreeIndex from a SyntaxTree, we need our checksum to change
            // any time the SyntaxTree could have changed.  Right now, that can only happen if the
            // text of the document changes, or the ParseOptions change.  So we get the checksums
            // for both of those, and merge them together to make the final checksum.
            var projectChecksumState = await document.Project.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false);
            var parseOptionsChecksum = projectChecksumState.ParseOptions;

            var documentChecksumState = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false);
            var textChecksum = documentChecksumState.Text;

            return Checksum.Create(WellKnownSynchronizationKind.SyntaxTreeIndex, new[] { textChecksum, parseOptionsChecksum });
        }

        private async Task<bool> SaveAsync(
            Document document, CancellationToken cancellationToken)
        {
            var solution = document.Project.Solution;
            var persistentStorageService = (IPersistentStorageService2)solution.Workspace.Services.GetService<IPersistentStorageService>();

            try
            {
                using (var storage = persistentStorageService.GetStorage(solution, checkBranchId: false))
                using (var stream = SerializableBytes.CreateWritableStream())
                using (var writer = new ObjectWriter(stream, cancellationToken: cancellationToken))
                {
                    this.WriteFormatAndChecksum(writer, SerializationFormat);
                    this.WriteTo(writer);

                    stream.Position = 0;
                    return await storage.WriteStreamAsync(document, PersistenceName, stream, cancellationToken).ConfigureAwait(false);
                }
            }
            catch (Exception e) when (IOUtilities.IsNormalIOException(e))
            {
                // Storage APIs can throw arbitrary exceptions.
            }

            return false;
        }

        private static async Task<bool> PrecalculatedAsync(
            Document document, Checksum checksum, CancellationToken cancellationToken)
        {
            var solution = document.Project.Solution;
            var persistentStorageService = (IPersistentStorageService2)solution.Workspace.Services.GetService<IPersistentStorageService>();

            // check whether we already have info for this document
            try
            {
                using (var storage = persistentStorageService.GetStorage(solution, checkBranchId: false))
                using (var stream = await storage.ReadStreamAsync(document, PersistenceName, cancellationToken).ConfigureAwait(false))
                using (var reader = ObjectReader.TryGetReader(stream))
                {
                    if (reader != null)
                    {
                        return FormatAndChecksumMatches(reader, SerializationFormat, checksum);
                    }
                }
            }
            catch (Exception e) when (IOUtilities.IsNormalIOException(e))
            {
                // Storage APIs can throw arbitrary exceptions.
            }

            return false;
        }

        bool IObjectWritable.ShouldReuseInSerialization => true;

        public void WriteTo(ObjectWriter writer)
        {
            _literalInfo.WriteTo(writer);
            _identifierInfo.WriteTo(writer);
            _contextInfo.WriteTo(writer);
            _declarationInfo.WriteTo(writer);
        }

        private static SyntaxTreeIndex ReadFrom(
            StringTable stringTable, ObjectReader reader, Checksum checksum)
        {
            var literalInfo = LiteralInfo.TryReadFrom(reader);
            var identifierInfo = IdentifierInfo.TryReadFrom(reader);
            var contextInfo = ContextInfo.TryReadFrom(reader);
            var declarationInfo = DeclarationInfo.TryReadFrom(stringTable, reader);

            if (literalInfo == null || identifierInfo == null || contextInfo == null || declarationInfo == null)
            {
                return null;
            }

            return new SyntaxTreeIndex(
                checksum, literalInfo.Value, identifierInfo.Value, contextInfo.Value, declarationInfo.Value);
        }
    }
}