text:
        <md-button ui-sref="my_projects" class="_nav-actions">
            <md-icon md-font-set="material-icons">chevron_left</md-icon>
        </md-button>
        Project Authoring

            {{ project.saveMessage }}
            <md-button ng-if="project.project.status==1" style="margin-right: 0" class="_nav-actions" ng-class="{'_button-active': project.showPreview}"
                       ng-click="project.preview($event)">
                <md-icon md-font-set="material-icons">remove_red_eye</md-icon>
                <md-tooltip>Preview</md-tooltip>
            </md-button>
            <md-button style="margin-left: 4px" ng-if="project.project.status==1" class="_nav-actions"
                       ng-click="project.deleteProject()">
                <md-icon md-font-set="material-icons">delete</md-icon>
                <md-tooltip>Discard Draft</md-tooltip>
            </md-button>
            <md-button ng-cloak="" ng-if="project.showPublish()"
                       class="_nav-actions md-raised md-accent _text-button" ng-click="project.validate($event)">
                <md-tooltip>Publish</md-tooltip>
                Publish
            </md-button>

                    PREVIEWING A SAMPLE TASK

Task #1 - {{ project.project.name }}

            <md-input-container class="_authoring_content">
                Title
                <input ng-disabled="project.isDisabled()" ng-model="project.project.name" autocomplete="off">
            </md-input-container>

            This project has launched. {{ project.unlockText }} click

{{ project.unlockButtonText }}

                    <ng-include src="'/static/templates/template/base.html'"></ng-include>

                <md-button ng-repeat="component in template.templateComponents"
                           ng-click="template.addComponent(component)">
                    <md-icon md-font-set="material-icons">{{ component.icon }}</md-icon>
                    <md-tooltip>
                        {{ component.tooltip }}
                    </md-tooltip>
                </md-button>

Upload a CSV if you want to create a task for each row. You can use the CSV headers as {{ '\{\{variables\}\}' }} in the task design.

            <md-button style="width: 172px" ng-if="project.project.batch_files.length==0" ng-cloak="" ngf-select
                       ngf-change="project.upload($files)">Upload a spreadsheet
            </md-button>

        <md-list style="padding-left: 16px" ng-if="!project.isDisabled() && project.project.batch_files.length>0"
                 class="_meta-sources"
                 ng-cloak="">
            <md-list-item class="md-line-2 layout-row layout-align-start-center"
                          ng-repeat="file in project.project.batch_files">

{{ file.name }}
                        ({{ file.size }}, {{ file.number_of_rows }} rows)

                <md-icon style="padding-top: 4px" ng-click="project.removeFile(file.id)" class="_file-action"
                         md-font-set="material-icons">clear
                </md-icon>
            </md-list-item>
        </md-list>

            <form name="metaForm" style="margin-bottom: 0">

                    <md-input-container flex="20">
                        Assignments per task
                        <input ng-disabled="project.isDisabled()" name="repetition" type="number" min="1"
                               ng-model="project.project.repetition">
                    </md-input-container>
                    <md-input-container flex="20" class="_ml-24 md-block md-input-has-placeholder">
                        Price per assignment

$
                            <input ng-disabled="project.isDisabled()"
                                   name="price" type="number" min="0.01"
                                   decimals="2" integers="15" is-currency
                                   step="0.01" ng-model="project.project.price"
                                   class="currency-field">

                    </md-input-container>

                        {{ (project.project.repetition * project.project.price || 0) | currency}} per task

                    To achieve California Minimum Wage, workers need to be able to finish this task in
                    {{ project.getMinWage() }}.

0 && project.project.batch_files[0].number_of_rows > 1">
                        Tasks: {{ project.project.batch_files[0].number_of_rows }}

Total cost: {{ project.totalCost() | currency}}

Your Daemo funds: {{ project.financial_data.account_balance | currency}}

 project.financial_data.account_balance">

                            You don't have enough funds to publish this project. Please deposit at least
                            {{ (project.totalCost() - project.financial_data.account_balance) | currency}}

                        <md-button class="md-accent" ng-click="project.goTo('payment_deposit')"
                                   style="margin-left: -6px;">
                            Deposit Funds
                        </md-button>

                    <md-button ng-click="project.isExpanded = !project.isExpanded" class="button-icon">Advanced

                                keyboard_arrow_down
                                keyboard_arrow_up

                    </md-button>

                        <md-input-container flex class="md-block larger md-input-has-placeholder">
                            Time limit per task (minutes)
                            <input ng-disabled="project.isDisabled()" name="timeout" type="number"
                                   ng-model="project.project.timeout" min="1">
                        </md-input-container>

                            <md-input-container>
                                <md-checkbox ng-disabled="project.isDisabled()" name="has_review"
                                             ng-model="project.project.has_review">Peer Review
                                </md-checkbox>
                            </md-input-container>
                            <md-input-container class="_ml-24" ng-if="project.project.has_review">
                                $/Task
                                <input ng-disabled="project.isDisabled()" name="review_price" required type="number"
                                       min="0.01"
                                       step="0.01"
                                       ng-model="project.project.review_price">
                            </md-input-container>

                        Mechanical Turk Qualifications

                                <md-input-container flex="33">
                                    Attribute
                                    <md-select ng-model="item.expression.attribute"
                                               aria-label="qualification attribute" ng-disabled="true">
                                        <md-option value="{{ option.value }}"
                                                   ng-repeat="option in project.qualificationItemOptions">
                                            {{ option.name }}
                                        </md-option>
                                    </md-select>
                                </md-input-container>
                                <md-input-container flex="20">
                                    Operator
                                    <md-select ng-disabled="project.isDisabled()"
                                               ng-change="project.updateQualificationItem(item)"
                                               class="_ml-16" ng-model="item.expression.operator"
                                               aria-label="qualification operator">
                                        <md-option value="{{ option.value }}"
                                                   ng-repeat="option in project.qualificationOperatorMapping[item.expression.attribute]">
                                            {{ option.name }}
                                        </md-option>
                                    </md-select>
                                </md-input-container>
                                <md-input-container class="_ml-16">
                                    Value(s)
                                    <input ng-disabled="project.isDisabled()"
                                           ng-change="project.updateQualificationItem(item)"
                                           ng-if="item.expression.attribute=='approval_rate'" type="number"
                                           ng-model="item.expression.value" min="1" max="99">
                                    <input ng-disabled="project.isDisabled()"
                                           ng-change="project.updateQualificationItem(item)"
                                           ng-if="item.expression.attribute=='total_tasks'" type="number"
                                           ng-model="item.expression.value" min="1">
                                    <input ng-disabled="project.isDisabled()"
                                           ng-change="project.updateQualificationItem(item)"
                                           ng-if="item.expression.attribute=='location'" type="text"
                                           ng-model="item.expression.value">
                                </md-input-container>
                                <md-icon ng-if="!project.isDisabled()"
                                         ng-click="project.deleteQualificationItem(item.id)" class="_icon-18 _clickable"
                                         md-font-set="material-icons">delete
                                </md-icon>

                            <md-input-container>
                                Attribute
                                <md-select ng-disabled="project.isDisabled()"
                                           ng-model="project.qualificationItemAttribute"
                                           aria-label="qualification attribute">
                                    <md-option value="{{ option.value }}"
                                               ng-repeat="option in project.qualificationItemOptions">
                                        {{ option.name }}
                                    </md-option>
                                </md-select>
                            </md-input-container>
                            <md-input-container>
                                Operator
                                <md-select ng-disabled="project.isDisabled()" class="_ml-16"
                                           ng-model="project.qualificationItemOperator"
                                           aria-label="qualification operator">
                                    <md-option value="{{ option.value }}"
                                               ng-repeat="option in project.qualificationOperatorMapping[project.qualificationItemAttribute]">
                                        {{ option.name }}
                                    </md-option>
                                </md-select>
                            </md-input-container>
                            <md-input-container class="_ml-16"
                                                ng-if="project.qualificationItemAttribute=='approval_rate' &&
                                                project.qualificationItemAttribute &&
                                                project.qualificationItemAttribute!='worker_groups'">
                                Value(s)
                                <input ng-disabled="project.isDisabled()"
                                       type="number"
                                       ng-model="project.qualificationItemValue" min="1" max="99">

                            </md-input-container>
                            <md-input-container class="_ml-16"
                                                ng-if="project.qualificationItemAttribute=='total_tasks' &&
                                                project.qualificationItemAttribute &&
                                                project.qualificationItemAttribute!='worker_groups'">
                                Value(s)
                                <input ng-disabled="project.isDisabled()" type="number"
                                       ng-model="project.qualificationItemValue" min="1">
                            </md-input-container>
                            <md-input-container class="_ml-16"
                                                ng-if="project.qualificationItemAttribute=='location' &&
                                                project.qualificationItemAttribute &&
                                                project.qualificationItemAttribute!='worker_groups'">
                                Value(s)
                                <input ng-disabled="project.isDisabled()"
                                       type="text"
                                       ng-model="project.qualificationItemValue">

                            </md-input-container>
                            <md-button
                                    ng-disabled="project.isDisabled() || (!project.qualificationItemAttribute || !project.qualificationItemOperator
                                    || project.qualificationItemValue==null) && project.qualificationItemAttribute!='worker_groups'"
                                    ng-click="project.createQualificationItem()">Add
                            </md-button>

                        Worker selection

                            <md-input-container ng-show="project.workerGroups.length" class="_mr-16">
                                Group
                                <md-select ng-disabled="project.isDisabled()"
                                           ng-change="project.addWorkerGroupQualification()" class="_ml-16"
                                           ng-model="project.project.workerGroup"
                                           aria-label="worker group">
                                    <md-option value="0">None</md-option>
                                    <md-option value="{{ option.id }}"
                                               ng-repeat="option in project.workerGroups">
                                        {{ option.name }}
                                    </md-option>
                                </md-select>
                            </md-input-container>

                            Add group

Deadline:
                        {{ project.project.deadline | date:'MMM d, y' || "Not Defined" }}

                        Time limit per task: {{ project.project.timeout || 0 }} minutes

            </form>

                <md-button ng-if="project.showResume()" ng-click="project.done($event)"
                           class="md-accent">{{ project.resumeButtonText }}</md-button>

            <ng-include src="'/static/templates/user/demographics.html'"></ng-include>

            <ng-include src="'/static/templates/project/launch-instructions.html'"></ng-include>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class net.didion.jwnl.data.PointerTarget
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
net.didion.jwnl.data.PointerTarget

Packages that use PointerTarget

net.didion.jwnl.data
Classes for extracting and containing data from the dictionary.

net.didion.jwnl.data.list
Lists and associated classes that hold the results of relationship operations.

net.didion.jwnl.data.relationship
Tools for finding pointer relationships between words.

Uses of PointerTarget in net.didion.jwnl.data

Subclasses of PointerTarget in net.didion.jwnl.data

 class
Adjective

          An Adjective is a Word that can have an adjective position.

 class
Synset

          A Synset, or synonym set, represents a
 line of a WordNet <var>pos</var>.data file.

 class
SynsetProxy

          Proxy for a Synset.

 class
Verb

          A Verb is a subclass of Word that can have 1 or more
 VerbFrames (use cases of the verb).

 class
Word

          A Word represents the lexical information related to a specific sense of an IndexWord.

Methods in net.didion.jwnl.data that return PointerTarget

 PointerTarget
Pointer.getSource()

          Get the source of this pointer.

 PointerTarget
Pointer.getTarget()

          Get the actual target of this pointer.

 PointerTarget[]
SynsetProxy.getTargets()

 PointerTarget[]
PointerTarget.getTargets()

          Get all the pointer targets of this synset

 PointerTarget[]
SynsetProxy.getTargets(PointerType type)

 PointerTarget[]
PointerTarget.getTargets(PointerType type)

          Get all the targets of the pointers of type type.

Constructors in net.didion.jwnl.data with parameters of type PointerTarget

Pointer(PointerTarget source,
        int index,
        PointerType pointerType,
        POS targetPOS,
        long targetOffset,
        int targetIndex)

Uses of PointerTarget in net.didion.jwnl.data.list

Methods in net.didion.jwnl.data.list that return PointerTarget

 PointerTarget
PointerTargetNode.getPointerTarget()

Methods in net.didion.jwnl.data.list with parameters of type PointerTarget

 void
PointerTargetTreeNodeList.add(PointerTarget target)

 void
PointerTargetNodeList.add(PointerTarget target)

 void
PointerTargetTreeNodeList.add(PointerTarget target,
    PointerTargetTreeNodeList childTreeList,
    PointerTargetTreeNodeList pointerTreeList,
    PointerType type)

 void
PointerTargetTreeNodeList.add(PointerTarget target,
    PointerTargetTreeNodeList childTreeList,
    PointerTargetTreeNodeList pointerTreeList,
    PointerType type,
    PointerTargetTreeNode parent)

 void
PointerTargetTreeNodeList.add(PointerTarget target,
    PointerTargetTreeNodeList childTreeList,
    PointerType type)

 void
PointerTargetTreeNodeList.add(PointerTarget target,
    PointerTargetTreeNodeList childTreeList,
    PointerType type,
    PointerTargetTreeNode parent)

 void
PointerTargetTreeNodeList.add(PointerTarget target,
    PointerType type)

 void
PointerTargetNodeList.add(PointerTarget target,
    PointerType type)

 void
PointerTargetTreeNodeList.add(PointerTarget target,
    PointerType type,
    PointerTargetTreeNode parent)

 PointerTargetTreeNode[]
PointerTargetTree.findAll(PointerTarget target)

          Find all  nodes in the tree whose target is <var>target</var>

 PointerTargetTreeNode
PointerTargetTree.findFirst(PointerTarget target)

          Find the first node in the tree whose target is <var>target</var>

Constructors in net.didion.jwnl.data.list with parameters of type PointerTarget

PointerTargetNode(PointerTarget target)

PointerTargetNode(PointerTarget target,
                  PointerType type)

PointerTargetNodeList(PointerTarget[] targets)

PointerTargetTreeNode(PointerTarget target)

PointerTargetTreeNode(PointerTarget target,
                      PointerTargetTreeNodeList childTreeList,
                      PointerTargetTreeNodeList pointerTreeList,
                      PointerType type)

PointerTargetTreeNode(PointerTarget target,
                      PointerTargetTreeNodeList childTreeList,
                      PointerTargetTreeNodeList pointerTreeList,
                      PointerType type,
                      PointerTargetTreeNode parent)

PointerTargetTreeNode(PointerTarget target,
                      PointerTargetTreeNodeList childTreeList,
                      PointerType type)

PointerTargetTreeNode(PointerTarget target,
                      PointerTargetTreeNodeList childTreeList,
                      PointerType type,
                      PointerTargetTreeNode parent)

PointerTargetTreeNode(PointerTarget target,
                      PointerType type)

PointerTargetTreeNode(PointerTarget target,
                      PointerType type,
                      PointerTargetTreeNode parent)

PointerTargetTreeNodeList.FindTargetOperation(PointerTarget target)

Uses of PointerTarget in net.didion.jwnl.data.relationship

Methods in net.didion.jwnl.data.relationship that return PointerTarget

 PointerTarget
Relationship.getSourcePointerTarget()

          Get the pointer target of the source node.

 PointerTarget
Relationship.getTargetPointerTarget()

          Get the pointer target of the target node.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

redpajama_set_name: RedPajamaGithub


text:
module Freeflow
  class Configuration

    class << self
      def registered_filters
        @@registered_filters ||= {}
      end

      def registered_extensions
        registered_filters.keys
      end
    end

    def filter(*args)
      options = args.pop
      name = options.delete(:with)
      extensions = args.map(&:to_sym)

      filter = ->(context) { context.filter(name, options) }
      extensions.each { |extension| self.class.registered_filters[extension] = filter }
    end
  end
end


text:
package com.asakusafw.yaess.core.task;

import java.io.IOException;

import com.asakusafw.yaess.core.ExecutionContext;
import com.asakusafw.yaess.core.ExecutionMonitor;
import com.asakusafw.yaess.core.ExecutionScriptHandler;

/**
 * A job to cleanup each {@link ExecutionScriptHandler}.
 * @since 0.2.3
 */
public class CleanupJob extends HandlerLifecycleJob {

    private static final String JOB_ID = "(cleanup)";

    /**
     * Creates a new instance.
     * @param handler target handler
     * @throws IllegalArgumentException if some parameters were {@code null}
     */
    public CleanupJob(ExecutionScriptHandler<?> handler) {
        super(handler);
    }

    @Override
    public void execute(
            ExecutionMonitor monitor,
            ExecutionContext context) throws InterruptedException, IOException {
        handler.cleanUp(monitor, context);
    }

    @Override
    public String getServiceLabel() {
        return handler.getHandlerId();
    }

    @Override
    public String getJobLabel() {
        return JOB_ID;
    }
}


text:
/**
 ***********************************************************************************************************************
 * @file  llpcAutoLayout.cpp
 * @brief LLPC source file: auto layout of pipeline state when compiling a single shader with AMDLLPC
 ***********************************************************************************************************************
 */
#ifdef WIN_OS
// NOTE: Disable Windows-defined min()/max() because we use STL-defined std::min()/std::max() in LLPC.
#define NOMINMAX
#endif

#include "llpcAutoLayout.h"
#include "SPIRVFunction.h"
#include "SPIRVInstruction.h"
#include "SPIRVModule.h"
#include "SPIRVType.h"
#include "llpcCompilationUtils.h"
#include "llpcDebug.h"
#include "llpcUtil.h"
#include "vfx.h"
#include "llvm/Support/Format.h"

#define DEBUG_TYPE "llpc-auto-layout"

using namespace llvm;
using namespace SPIRV;

namespace Llpc {
namespace StandaloneCompiler {

// Offset in Node will be a fixed number, which will be conveniently to identify offset in auto-layout.
static const unsigned OffsetStrideInDwords = 12;

// =====================================================================================================================
// Get the storage size in bytes of a SPIR-V type.
// This does not need to be completely accurate, as it is only used to fake up a push constant user data node.
//
// @param ty : Type to determine the data size of
// @returns : Type storage size in bytes
static unsigned getTypeDataSize(const SPIRVType *ty) {
  switch (ty->getOpCode()) {
  case OpTypeVector:
    return getTypeDataSize(ty->getVectorComponentType()) * ty->getVectorComponentCount();
  case OpTypeMatrix:
    return getTypeDataSize(ty->getMatrixColumnType()) * ty->getMatrixColumnCount();
  case OpTypeArray:
    return getTypeDataSize(ty->getArrayElementType()) * ty->getArrayLength();
  case OpTypeStruct: {
    unsigned totalSize = 0;
    for (unsigned memberIdx = 0; memberIdx < ty->getStructMemberCount(); ++memberIdx)
      totalSize += getTypeDataSize(ty->getStructMemberType(memberIdx));
    return totalSize;
  }
  default:
    return (ty->getBitWidth() + 7) / 8;
  }
}

// =====================================================================================================================
// Find VaPtr userDataNode with the specified set.
//
// @param resourceMapping : Resource mapping data, possibly containing user data nodes
// @param set : According this set to find ResourceMappingNode
// @returns : userDataNode with the specified set
static const ResourceMappingRootNode *findDescriptorTableVaPtr(const ResourceMappingData *resourceMapping,
                                                               unsigned set) {
  const ResourceMappingRootNode *descriptorTableVaPtr = nullptr;

  for (unsigned k = 0; k < resourceMapping->userDataNodeCount; ++k) {
    const ResourceMappingRootNode *userDataNode = &resourceMapping->pUserDataNodes[k];

    if (userDataNode->node.type == Llpc::ResourceMappingNodeType::DescriptorTableVaPtr) {
      if (userDataNode->node.tablePtr.pNext[0].srdRange.set == set) {
        descriptorTableVaPtr = userDataNode;
        break;
      }
    }
  }

  return descriptorTableVaPtr;
}

// =====================================================================================================================
// Find userDataNode with specified set and binding. And return Node index.
//
// @param userDataNode : ResourceMappingNode pointer
// @param nodeCount : User data node count
// @param set : Find same set in node array
// @param binding : Find same binding in node array
// @param [out] index : Return node position in node array
static const ResourceMappingNode *findResourceNode(const ResourceMappingNode *userDataNode, unsigned nodeCount,
                                                   unsigned set, unsigned binding, unsigned *index) {
  const ResourceMappingNode *resourceNode = nullptr;

  for (unsigned j = 0; j < nodeCount; ++j) {
    const ResourceMappingNode *next = &userDataNode[j];

    if (set == next->srdRange.set && binding == next->srdRange.binding) {
      resourceNode = next;
      *index = j;
      break;
    }
  }

  return resourceNode;
}

// =====================================================================================================================
// Find userDataNode with specified set and binding. And return Node index.
//
// @param userDataNode : ResourceMappingRootNode pointer
// @param nodeCount : User data node count
// @param set : Find same set in node array
// @param binding : Find same binding in node array
// @param [out] index : Return node position in node array
// @returns : The Node index
static const ResourceMappingRootNode *findResourceNode(const ResourceMappingRootNode *userDataNode, unsigned nodeCount,
                                                       unsigned set, unsigned binding, unsigned *index) {
  const ResourceMappingRootNode *resourceNode = nullptr;

  for (unsigned j = 0; j < nodeCount; ++j) {
    const ResourceMappingRootNode *next = &userDataNode[j];

    if (set == next->node.srdRange.set && binding == next->node.srdRange.binding) {
      resourceNode = next;
      *index = j;
      break;
    }
  }

  return resourceNode;
}

// =====================================================================================================================
// Check if autoLayoutUserDataNodes is a subset of userDataNodes.
//
// @param [in] resourceMapping : Resource mapping data, which can contain user data nodes
// @param [in] autoLayoutUserDataNodeCount : UserData Node count
// @param [in] autoLayoutUserDataNodes : ResourceMappingNode
// @returns : true if compatible
bool checkResourceMappingCompatible(const ResourceMappingData *resourceMapping, unsigned autoLayoutUserDataNodeCount,
                                    const ResourceMappingRootNode *autoLayoutUserDataNodes) {
  bool hit = false;

  if (autoLayoutUserDataNodeCount == 0)
    hit = true;
  else if (resourceMapping->pStaticDescriptorValues)
    hit = false;
  else if (resourceMapping->userDataNodeCount >= autoLayoutUserDataNodeCount) {
    for (unsigned n = 0; n < autoLayoutUserDataNodeCount; ++n) {
      const ResourceMappingRootNode *autoLayoutUserDataNode = &autoLayoutUserDataNodes[n];

      // Multiple levels
      if (autoLayoutUserDataNode->node.type == Llpc::ResourceMappingNodeType::DescriptorTableVaPtr) {
        unsigned set = autoLayoutUserDataNode->node.tablePtr.pNext[0].srdRange.set;
        const ResourceMappingRootNode *userDataNode = findDescriptorTableVaPtr(resourceMapping, set);

        if (userDataNode) {
          bool hitNode = false;
          for (unsigned i = 0; i < autoLayoutUserDataNode->node.tablePtr.nodeCount; ++i) {
            const ResourceMappingNode *autoLayoutNext = &autoLayoutUserDataNode->node.tablePtr.pNext[i];

            unsigned index = 0;
            const ResourceMappingNode *node =
                findResourceNode(userDataNode->node.tablePtr.pNext, userDataNode->node.tablePtr.nodeCount,
                                 autoLayoutNext->srdRange.set, autoLayoutNext->srdRange.binding, &index);

            if (node) {
              if (autoLayoutNext->type == node->type && autoLayoutNext->sizeInDwords == node->sizeInDwords &&
                  autoLayoutNext->sizeInDwords <= OffsetStrideInDwords &&
                  autoLayoutNext->offsetInDwords == (index * OffsetStrideInDwords)) {
                hitNode = true;
                continue;
              } else { // NOLINT
                outs() << "AutoLayoutNode:"
                       << "\n ->type                    : "
                       << format("0x%016" PRIX64, static_cast<unsigned>(autoLayoutNext->type))
                       << "\n ->sizeInDwords            : " << autoLayoutNext->sizeInDwords
                       << "\n ->offsetInDwords          : " << autoLayoutNext->offsetInDwords;

                outs() << "\nShaderInfoNode:"
                       << "\n ->type                    : "
                       << format("0x%016" PRIX64, static_cast<unsigned>(node->type))
                       << "\n ->sizeInDwords            : " << node->sizeInDwords
                       << "\n OffsetStrideInDwords      : " << OffsetStrideInDwords
                       << "\n index*OffsetStrideInDwords: " << (index * OffsetStrideInDwords) << "\n";
                hitNode = false;
                break;
              }
            } else
              break;
          }
          if (!hitNode) {
            hit = false;
            break;
          } else // NOLINT
            hit = true;
        } else {
          hit = false;
          break;
        }
      }
      // Single level
      else {
        unsigned index = 0;
        const ResourceMappingRootNode *node = findResourceNode(
            resourceMapping->pUserDataNodes, resourceMapping->userDataNodeCount,
            autoLayoutUserDataNode->node.srdRange.set, autoLayoutUserDataNode->node.srdRange.binding, &index);
        if (node && autoLayoutUserDataNode->node.sizeInDwords == node->node.sizeInDwords) {
          hit = true;
          continue;
        } else { // NOLINT
          hit = false;
          break;
        }
      }
    }
  }

  return hit;
}

// =====================================================================================================================
// Check if necessary pipeline state is same.
//
// @param compiler : LLPC compiler object
// @param pipelineInfo : Graphics pipeline info
// @param autoLayoutPipelineInfo : Layout pipeline info
// @param gfxIp : Graphics IP version
// @returns : true if compatible
bool checkPipelineStateCompatible(const ICompiler *compiler, Llpc::GraphicsPipelineBuildInfo *pipelineInfo,
                                  Llpc::GraphicsPipelineBuildInfo *autoLayoutPipelineInfo, Llpc::GfxIpVersion gfxIp) {
  bool compatible = true;

  auto cbState = &pipelineInfo->cbState;
  auto autoLayoutCbState = &autoLayoutPipelineInfo->cbState;

  for (unsigned i = 0; i < MaxColorTargets; ++i) {
    if (cbState->target[i].format != VK_FORMAT_UNDEFINED) {
      // NOTE: Alpha-to-coverage only take effect for output from color target 0.
      const bool enableAlphaToCoverage = cbState->alphaToCoverageEnable && i == 0;
      unsigned exportFormat =
          compiler->ConvertColorBufferFormatToExportFormat(&cbState->target[i], enableAlphaToCoverage);
      const bool autoLayoutEnableAlphaToCoverage = autoLayoutCbState->alphaToCoverageEnable && i == 0;
      unsigned autoLayoutExportFormat = compiler->ConvertColorBufferFormatToExportFormat(
          &autoLayoutCbState->target[i], autoLayoutEnableAlphaToCoverage);

      if (exportFormat != autoLayoutExportFormat) {
        outs() << "pPipelineInfo->cbState.target[" << i << "] export format:" << format("0x%016" PRIX64, exportFormat)
               << "\n"
               << "pAutoLayoutPipelineInfo->cbState.target[" << i
               << "] export format:" << format("0x%016" PRIX64, autoLayoutExportFormat) << "\n";

        compatible = false;
        break;
      }
    }
  }
  // TODO: RsState and other members in CbState except target[].format

  return compatible;
}

// =====================================================================================================================
// Lay out dummy bottom-level descriptors and other information for one shader stage. This is used when running
// standalone compiler on a single SPIR-V or GLSL shader, rather than on a .pipe file. Memory allocated here may be
// leaked, but that does not matter because we are running a short-lived command-line utility.
//
// @param shaderStage : Shader stage
// @param spirvBin : SPIR-V binary
// @param [in/out] pipelineInfo : Graphics pipeline info, will have dummy information filled in. nullptr if not a
//                                graphics pipeline.
// @param [in] shaderInfo : Shader info, used to check entry point name
// @param [in/out] resNodeSets : Resource map, will have user data nodes added to it
// @param [in/out] pushConstSize : Cumulative push constant node size
// @param autoLayoutDesc : Whether to automatically create descriptor layout based on resource usages
// @param reverseThreadGroup : Whether reverse thread group optimization is enabled.
void doAutoLayoutDesc(ShaderStage shaderStage, BinaryData spirvBin, GraphicsPipelineBuildInfo *pipelineInfo,
                      PipelineShaderInfo *shaderInfo, ResourceMappingNodeMap &resNodeSets, unsigned &pushConstSize,
                      bool autoLayoutDesc, bool reverseThreadGroup) {
  // Read the SPIR-V.
  std::string spirvCode(static_cast<const char *>(spirvBin.pCode), spirvBin.codeSize);
  std::istringstream spirvStream(spirvCode);
  std::unique_ptr<SPIRVModule> module(SPIRVModule::createSPIRVModule());
  spirvStream >> *module;

  // Find the entry target.
  SPIRVEntryPoint *entryPoint = nullptr;
  SPIRVFunction *func = nullptr;
  for (unsigned i = 0, funcCount = module->getNumFunctions(); i < funcCount; ++i) {
    func = module->getFunction(i);
    entryPoint = module->getEntryPoint(func->getId());
    if (entryPoint && entryPoint->getExecModel() == convertToExecModel(shaderStage) &&
        entryPoint->getName() == shaderInfo->pEntryTarget)
      break;
    func = nullptr;
  }
  if (!entryPoint)
    return;

  // Shader stage specific processing
  auto inOuts = entryPoint->getInOuts();
  if (shaderStage == ShaderStageVertex && autoLayoutDesc) {
    // Create dummy vertex info (only if -auto-layout-desc is on).
    auto vertexBindings = new std::vector<VkVertexInputBindingDescription>;
    auto vertexAttribs = new std::vector<VkVertexInputAttributeDescription>;

    for (auto varId : ArrayRef<SPIRVWord>(inOuts.first, inOuts.second)) {
      auto var = static_cast<SPIRVVariable *>(module->getValue(varId));
      if (var->getStorageClass() == StorageClassInput) {
        SPIRVWord location = SPIRVID_INVALID;
        if (var->hasDecorate(DecorationLocation, 0, &location)) {
          auto varElemTy = var->getType()->getPointerElementType();
          if (varElemTy->getOpCode() == OpTypeArray)
            varElemTy = varElemTy->getArrayElementType();

          if (varElemTy->getOpCode() == OpTypeMatrix)
            varElemTy = varElemTy->getMatrixColumnType();

          if (varElemTy->getOpCode() == OpTypeVector)
            varElemTy = varElemTy->getVectorComponentType();

          VkFormat format = VK_FORMAT_UNDEFINED;
          switch (varElemTy->getOpCode()) {
          case OpTypeInt: {
            bool isSigned = reinterpret_cast<SPIRVTypeInt *>(varElemTy)->isSigned();
            switch (varElemTy->getIntegerBitWidth()) {
            case 8:
              format = isSigned ? VK_FORMAT_R8G8B8A8_SINT : VK_FORMAT_R8G8B8A8_UINT;
              break;
            case 16:
              format = isSigned ? VK_FORMAT_R16G16B16A16_SINT : VK_FORMAT_R16G16B16A16_UINT;
              break;
            case 32:
              format = isSigned ? VK_FORMAT_R32G32B32A32_SINT : VK_FORMAT_R32G32B32A32_UINT;
              break;
            case 64:
              format = isSigned ? VK_FORMAT_R64G64B64A64_SINT : VK_FORMAT_R64G64B64A64_UINT;
              break;
            }
            break;
          }
          case OpTypeFloat: {
            switch (varElemTy->getFloatBitWidth()) {
            case 16:
              format = VK_FORMAT_R16G16B16A16_SFLOAT;
              break;
            case 32:
              format = VK_FORMAT_R32G32B32A32_SFLOAT;
              break;
            case 64:
              format = VK_FORMAT_R64G64_SFLOAT;
              break;
            }
            break;
          }
          default: {
            break;
          }
          }
          assert(format != VK_FORMAT_UNDEFINED);

          VkVertexInputBindingDescription vertexBinding = {};
          vertexBinding.binding = location;
          vertexBinding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
          vertexBinding.stride = SizeOfVec4;

          VkVertexInputAttributeDescription vertexAttrib = {};
          vertexAttrib.binding = location;
          vertexAttrib.location = location;
          vertexAttrib.offset = 0;
          vertexAttrib.format = format;

          vertexBindings->push_back(vertexBinding);
          vertexAttribs->push_back(vertexAttrib);
        }
      }
    }

    auto vertexInputState = new VkPipelineVertexInputStateCreateInfo;
    pipelineInfo->pVertexInput = vertexInputState;
    vertexInputState->sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
    vertexInputState->pNext = nullptr;
    vertexInputState->vertexBindingDescriptionCount = vertexBindings->size();
    vertexInputState->pVertexBindingDescriptions = vertexBindings->data();
    vertexInputState->vertexAttributeDescriptionCount = vertexAttribs->size();
    vertexInputState->pVertexAttributeDescriptions = vertexAttribs->data();

    // Set primitive topology
    pipelineInfo->iaState.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
  } else if (shaderStage == ShaderStageTessControl || shaderStage == ShaderStageTessEval) {
    // Set primitive topology and patch control points
    pipelineInfo->iaState.topology = VK_PRIMITIVE_TOPOLOGY_PATCH_LIST;
    pipelineInfo->iaState.patchControlPoints = 3;
  } else if (shaderStage == ShaderStageGeometry) {
    // Set primitive topology
    auto topology = VkPrimitiveTopology(0);
    if (func->getExecutionMode(ExecutionModeInputPoints))
      topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
    else if (func->getExecutionMode(ExecutionModeInputLines))
      topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
    else if (func->getExecutionMode(ExecutionModeInputLinesAdjacency))
      topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY;
    else if (func->getExecutionMode(ExecutionModeTriangles))
      topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
    else if (func->getExecutionMode(ExecutionModeInputTrianglesAdjacency))
      topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY;
    else
      llvm_unreachable("Should never be called!");
    pipelineInfo->iaState.topology = topology;
  } else if (shaderStage == ShaderStageFragment && autoLayoutDesc) {
    // Set dummy color formats for fragment outputs, but only if -auto-layout-desc is on.
    for (auto varId : ArrayRef<SPIRVWord>(inOuts.first, inOuts.second)) {
      auto entry = module->getValue(varId);
      if (!entry->isVariable())
        continue;
      auto var = static_cast<SPIRVVariable *>(entry);
      if (var->getStorageClass() != StorageClassOutput)
        continue;

      SPIRVWord location = SPIRVID_INVALID;
      if (!var->hasDecorate(DecorationLocation, 0, &location))
        continue;

      SPIRVType *varElemTy = var->getType()->getPointerElementType();
      unsigned elemCount = 1;
      if (varElemTy->getOpCode() == OpTypeVector) {
        elemCount = varElemTy->getVectorComponentCount();
        varElemTy = varElemTy->getVectorComponentType();
      }
      static const VkFormat UndefinedFormatTable[] = {
          VK_FORMAT_UNDEFINED,
          VK_FORMAT_UNDEFINED,
          VK_FORMAT_UNDEFINED,
          VK_FORMAT_UNDEFINED,
      };
      const VkFormat *formatTable = UndefinedFormatTable;

      switch (varElemTy->getOpCode()) {
      case OpTypeInt: {
        switch (varElemTy->getIntegerBitWidth()) {
        case 8: {
          if (reinterpret_cast<SPIRVTypeInt *>(varElemTy)->isSigned()) {
            static const VkFormat FormatTable[] = {
                VK_FORMAT_R8_SINT,
                VK_FORMAT_R8G8_SINT,
                VK_FORMAT_R8G8B8_SINT,
                VK_FORMAT_R8G8B8A8_SINT,
            };
            formatTable = FormatTable;
          } else {
            static const VkFormat FormatTable[] = {
                VK_FORMAT_R8_UINT,
                VK_FORMAT_R8G8_UINT,
                VK_FORMAT_R8G8B8_UINT,
                VK_FORMAT_R8G8B8A8_UINT,
            };
            formatTable = FormatTable;
          }
          break;
        }
        case 16: {
          if (reinterpret_cast<SPIRVTypeInt *>(varElemTy)->isSigned()) {
            static const VkFormat FormatTable[] = {
                VK_FORMAT_R16_SINT,
                VK_FORMAT_R16G16_SINT,
                VK_FORMAT_R16G16B16_SINT,
                VK_FORMAT_R16G16B16A16_SINT,
            };
            formatTable = FormatTable;
          } else {
            static const VkFormat FormatTable[] = {
                VK_FORMAT_R16_UINT,
                VK_FORMAT_R16G16_UINT,
                VK_FORMAT_R16G16B16_UINT,
                VK_FORMAT_R16G16B16A16_UINT,
            };
            formatTable = FormatTable;
          }
          break;
        }
        case 32: {
          if (reinterpret_cast<SPIRVTypeInt *>(varElemTy)->isSigned()) {
            static const VkFormat FormatTable[] = {
                VK_FORMAT_R32_SINT,
                VK_FORMAT_R32G32_SINT,
                VK_FORMAT_R32G32B32_SINT,
                VK_FORMAT_R32G32B32A32_SINT,
            };
            formatTable = FormatTable;
          } else {
            static const VkFormat FormatTable[] = {
                VK_FORMAT_R32_UINT,
                VK_FORMAT_R32G32_UINT,
                VK_FORMAT_R32G32B32_UINT,
                VK_FORMAT_R32G32B32A32_UINT,
            };
            formatTable = FormatTable;
          }
          break;
        }
        }
        break;
      }

      case OpTypeFloat: {
        switch (varElemTy->getFloatBitWidth()) {
        case 16: {
          static const VkFormat FormatTable[] = {
              VK_FORMAT_R16_SFLOAT,
              VK_FORMAT_R16G16_SFLOAT,
              VK_FORMAT_R16G16B16_SFLOAT,
              VK_FORMAT_R16G16B16A16_SFLOAT,
          };
          formatTable = FormatTable;
        } break;
        case 32: {
          static const VkFormat FormatTable[] = {
              VK_FORMAT_R32_SFLOAT,
              VK_FORMAT_R32G32_SFLOAT,
              VK_FORMAT_R32G32B32_SFLOAT,
              VK_FORMAT_R32G32B32A32_SFLOAT,
          };
          formatTable = FormatTable;
        } break;
        }
        break;
      }

      default: {
        break;
      }
      }

      assert(elemCount <= 4);
      VkFormat format = formatTable[elemCount - 1];
      assert(format != VK_FORMAT_UNDEFINED);

      assert(location < MaxColorTargets);
      auto colorTarget = &pipelineInfo->cbState.target[location];
      colorTarget->format = format;
      colorTarget->channelWriteMask = (1U << elemCount) - 1;
    }
  }

  // Only auto-layout descriptors if -auto-layout-desc is on, or reverse thread group is enabled (we need to insert
  // an internal buffer descriptor in this case).
  if (!autoLayoutDesc && !reverseThreadGroup)
    return;

  // Collect ResourceMappingNode entries in sets.
  for (unsigned i = 0, varCount = module->getNumVariables(); i < varCount; ++i) {
    auto var = module->getVariable(i);
    switch (var->getStorageClass()) {
    case StorageClassFunction: {
      break;
    }

    case StorageClassPushConstant: {
      // Push constant: Get the size of the data and add to the total.
      auto varElemTy = var->getType()->getPointerElementType();
      pushConstSize += (getTypeDataSize(varElemTy) + 3) / 4;
      break;
    }

    default: {
      SPIRVWord binding = SPIRVID_INVALID;
      SPIRVWord descSet = 0;
      if (var->hasDecorate(DecorationBinding, 0, &binding)) {
        // Test shaderdb/OpDecorationGroup_TestGroupAndGroupMember_lit.spvasm
        // defines a variable with a binding but no set. Handle that case.
        var->hasDecorate(DecorationDescriptorSet, 0, &descSet);

        // Find/create the node entry for this set and binding.
        ResourceNodeSet &resNodeSet = resNodeSets[descSet];
        auto iteratorAndCreated = resNodeSet.bindingMap.insert({binding, resNodeSet.nodes.size()});
        unsigned nodesIndex = iteratorAndCreated.first->second;
        if (iteratorAndCreated.second) {
          resNodeSet.nodes.push_back({});
          resNodeSet.nodes.back().type = ResourceMappingNodeType::Unknown;
        }
        resNodeSet.visibility |= shaderStageToMask(shaderStage);
        ResourceMappingNode *node = &resNodeSet.nodes[nodesIndex];

        // Get the element type and array size.
        auto varElemTy = var->getType()->getPointerElementType();
        unsigned arraySize = 1;
        while (varElemTy->isTypeArray()) {
          arraySize *= varElemTy->getArrayLength();
          varElemTy = varElemTy->getArrayElementType();
        }

        // Map the SPIR-V opcode to descriptor type and size.
        ResourceMappingNodeType nodeType;
        unsigned sizeInDwords;
        switch (varElemTy->getOpCode()) {
        case OpTypeSampler: {
          // Sampler descriptor.
          nodeType = ResourceMappingNodeType::DescriptorSampler;
          sizeInDwords = 4 * arraySize;
          break;
        }
        case OpTypeImage: {
          // Image descriptor.
          auto imageType = static_cast<SPIRVTypeImage *>(varElemTy);
          nodeType = imageType->getDescriptor().Dim == spv::DimBuffer ? ResourceMappingNodeType::DescriptorTexelBuffer
                                                                      : ResourceMappingNodeType::DescriptorResource;
          sizeInDwords = 8 * arraySize;
          break;
        }
        case OpTypeSampledImage: {
          // Combined image and sampler descriptors.
          nodeType = ResourceMappingNodeType::DescriptorCombinedTexture;
          sizeInDwords = 12 * arraySize;
          break;
        }
        default: {
          // Normal buffer.
          nodeType = ResourceMappingNodeType::DescriptorBuffer;
          sizeInDwords = 4 * arraySize;
          break;
        }
        }

        // Check if the node already had a different type set. A DescriptorResource/DescriptorTexelBuffer
        // and a DescriptorSampler can use the same set/binding, in which case it is
        // DescriptorCombinedTexture.
        if (node->type == ResourceMappingNodeType::Unknown)
          node->type = nodeType;
        else if (node->type != nodeType) {
          {
            assert(nodeType == ResourceMappingNodeType::DescriptorCombinedTexture ||
                   nodeType == ResourceMappingNodeType::DescriptorResource ||
                   nodeType == ResourceMappingNodeType::DescriptorTexelBuffer ||
                   nodeType == ResourceMappingNodeType::DescriptorSampler);
          }
          {
            assert(node->type == ResourceMappingNodeType::DescriptorCombinedTexture ||
                   node->type == ResourceMappingNodeType::DescriptorResource ||
                   node->type == ResourceMappingNodeType::DescriptorTexelBuffer ||
                   node->type == ResourceMappingNodeType::DescriptorSampler);
          }

          node->type = ResourceMappingNodeType::DescriptorCombinedTexture;
          sizeInDwords = 12 * arraySize;
        }

        // Fill out the rest of the node.
        node->sizeInDwords = sizeInDwords;
        node->srdRange.set = descSet;
        node->srdRange.binding = binding;
      }
      break;
    }
    }
  }

  if (reverseThreadGroup) {
    ResourceNodeSet &resNodeSet = resNodeSets[Vkgc::InternalDescriptorSetId];
    auto ret = resNodeSet.bindingMap.insert({Vkgc::ReverseThreadGroupControlBinding, resNodeSet.nodes.size()});
    unsigned nodesIndex = ret.first->second;
    if (ret.second) {
      resNodeSet.nodes.push_back({});
      resNodeSet.nodes.back().type = ResourceMappingNodeType::Unknown;
    }
    resNodeSet.visibility |= shaderStageToMask(ShaderStageCompute);
    ResourceMappingNode *node = &resNodeSet.nodes[nodesIndex];
    node->type = ResourceMappingNodeType::DescriptorBufferCompact;
    node->sizeInDwords = 2;
    node->srdRange.set = Vkgc::InternalDescriptorSetId;
    node->srdRange.binding = Vkgc::ReverseThreadGroupControlBinding;
  }

  // Allocate dword offset to each node.
  for (auto &it : resNodeSets) {
    ResourceNodeSet &resNodeSet = it.second;
    unsigned offsetInDwords = 0;
    for (auto &node : resNodeSet.nodes) {
      node.offsetInDwords = offsetInDwords;
      offsetInDwords += node.sizeInDwords;
    }
  }
}

// =====================================================================================================================
// Lay out dummy top-level descriptors and populate ResourceMappingData. This is used when running standalone compiler
// on a single SPIR-V or GLSL shader, rather than on a .pipe file.
//
// @param shaderMask : Shader stage mask
// @param resNodeSets : User-data nodes to be pointed to by top level nodes
// @param pushConstSize : Push constant node size
// @param [in/out] resourceMapping : Resource map, will have user data nodes added to it
// @param autoLayoutDesc : Whether to automatically create descriptor layout based on resource usages
void buildTopLevelMapping(unsigned shaderMask, const ResourceMappingNodeMap &resNodeSets, unsigned pushConstSize,
                          ResourceMappingData *resourceMapping, bool autoLayoutDesc) {
  // Only auto-layout descriptors if -auto-layout-desc is on.
  if (!autoLayoutDesc)
    return;

  unsigned topLevelOffset = 0;

  // Add up how much memory we need and allocate it.
  unsigned topLevelCount = resNodeSets.size();
  topLevelCount += 3; // Allow one for push consts, one for XFB and one for vertex buffer.
  unsigned subLevelCount = 0;
  for (const auto &resNodeSet : resNodeSets)
    subLevelCount += resNodeSet.second.nodes.size();

  size_t bufferSize = sizeof(ResourceMappingRootNode) * topLevelCount + sizeof(ResourceMappingNode) * subLevelCount;
  auto rootNodes = static_cast<ResourceMappingRootNode *>(malloc(bufferSize));
  auto subNodes = reinterpret_cast<ResourceMappingNode *>(rootNodes + topLevelCount);
  resourceMapping->pUserDataNodes = rootNodes;
  memset(rootNodes, 0, bufferSize);

  // Add a node for each set.
  for (const auto &resNodeSet : resNodeSets) {
    rootNodes->node.type = ResourceMappingNodeType::DescriptorTableVaPtr;
    rootNodes->node.sizeInDwords = 1;
    rootNodes->node.offsetInDwords = topLevelOffset;
    topLevelOffset += rootNodes->node.sizeInDwords;
    rootNodes->node.tablePtr.nodeCount = resNodeSet.second.nodes.size();
    rootNodes->node.tablePtr.pNext = subNodes;
    for (auto &resNode : resNodeSet.second.nodes)
      *subNodes++ = resNode;
    rootNodes->visibility = resNodeSet.second.visibility;
    ++rootNodes;
  }

  if (shaderMask & ShaderStageVertexBit) {
    // Add a node for vertex buffer.
    rootNodes->node.type = ResourceMappingNodeType::IndirectUserDataVaPtr;
    rootNodes->node.sizeInDwords = 1;
    rootNodes->node.offsetInDwords = topLevelOffset;
    topLevelOffset += rootNodes->node.sizeInDwords;
    rootNodes->node.userDataPtr.sizeInDwords = 256;
    rootNodes->visibility = ShaderStageVertexBit;
    ++rootNodes;
  }

  const unsigned xfbStageMask = ShaderStageVertexBit | ShaderStageTessEvalBit | ShaderStageGeometryBit;
  if (shaderMask & xfbStageMask) {
    // Add a node for XFB.
    rootNodes->node.type = ResourceMappingNodeType::StreamOutTableVaPtr;
    rootNodes->node.sizeInDwords = 1;
    rootNodes->node.offsetInDwords = topLevelOffset;
    topLevelOffset += rootNodes->node.sizeInDwords;
    rootNodes->visibility = xfbStageMask & shaderMask;
    ++rootNodes;
  }

  if (pushConstSize > 0) {
    // Add push const node
    rootNodes->node.type = ResourceMappingNodeType::PushConst;
    rootNodes->node.sizeInDwords = pushConstSize;
    rootNodes->node.offsetInDwords = topLevelOffset;
    topLevelOffset += rootNodes->node.sizeInDwords;
    rootNodes->visibility = shaderMask;
    ++rootNodes;
  }

  resourceMapping->userDataNodeCount = rootNodes - resourceMapping->pUserDataNodes;

  assert(resourceMapping->userDataNodeCount <= topLevelCount);
  assert(static_cast<unsigned>(subNodes - reinterpret_cast<const ResourceMappingNode *>(
                                              resourceMapping->pUserDataNodes + topLevelCount)) <= subLevelCount);
}

} // namespace StandaloneCompiler
} // namespace Llpc


text:
require 'rake'
require 'rake/tasklib'

module NetLinx
  module Rake
    module ERB

      # Generate Netlinx source code files from the erb template files.
      class GenerateERB < ::Rake::TaskLib

        attr_accessor :name

        def initialize name = :generate_erb
          @name = name
          yield self if block_given?

          desc "Generate Netlinx source code files from the erb template files."

          task(name) do
            require 'netlinx-erb'

            puts "Generating NetLinx files from ERB..."
            puts "------------------------------------"

            templates = Dir['include/**/*.erb']

            templates.each do |template|
              file_name = template.gsub /\.erb$/, ''
              puts "   #{file_name}"

              $AUTOGEN_HEADER = <<-HEADER
(***********************************************************)
(*                         WARNING                         *)
(***********************************************************}
    This file was generated from the following template
    and should NOT be edited directly:

      #{template}

    See the documentation at `doc/index.html` for
    information about maintaining this project.

    Generated with netlinx-erb:
      https://github.com/amclain/netlinx-erb
{***********************************************************)

          HEADER

              File.open file_name, 'w+' do |file|
                  file.write NetLinx::ERB.execute(template)
              end
            end

            puts "\nDone."
          end
        end

      end
    end
  end
end


text:
package com.developerphil.adbidea.adb;

import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.ShellCommandUnresponsiveException;
import com.android.ddmlib.TimeoutException;
import com.developerphil.adbidea.adb.command.receiver.GenericReceiver;
import org.jetbrains.android.facet.AndroidFacet;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class AdbUtil {

    public static boolean isAppInstalled(IDevice device, String packageName) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException {
        GenericReceiver receiver = new GenericReceiver();
        // "pm list packages com.my.package" will return one line per package installed that corresponds to this package.
        // if this list is empty, we know for sure that the app is not installed
        device.executeShellCommand("pm list packages " + packageName, receiver, 15L, TimeUnit.SECONDS);

        //TODO make sure that it is the exact package name and not a subset.
        // e.g. if our app is called com.example but there is another app called com.example.another.app, it will match and return a false positive
        return !receiver.getAdbOutputLines().isEmpty();
    }

    /**
     * Computes the project's package while preserving backward compatibility between android studio 0.4.3 and 0.4.4
     */
    public static String computePackageName(AndroidFacet facet) {
        try {
            Object androidModuleInfo = facet.getClass().getMethod("getAndroidModuleInfo").invoke(facet);
            return (String) androidModuleInfo.getClass().getMethod("getPackage").invoke(androidModuleInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}


text:
define(function(require, exports, module) {
	"use strict";

	var Backbone = require("backbone");

	var videoTemplate = require("text!templates/video.html");

	var VideoView = Backbone.View.extend({
		tpl: _.template(videoTemplate),

		render: function() {
			this.$el.html(this.tpl({
				video: this.model.toJSON()
			}));
			return this;
		},

	});

	module.exports = VideoView;

});


text:
#include "squid.h"
#include "heap.h"
#include "store_heap_replacement.h"

REMOVALPOLICYCREATE createRemovalPolicy_heap;

static int nr_heap_policies = 0;

typedef struct _HeapPolicyData HeapPolicyData;
struct _HeapPolicyData {
    RemovalPolicy *policy;
    heap *heap;
    heap_key_func *keyfunc;
    int count;
    int nwalkers;
    enum heap_entry_type {
	TYPE_UNKNOWN = 0, TYPE_STORE_ENTRY, TYPE_STORE_MEM
    } type;
};

/* Hack to avoid having to remember the RemovalPolicyNode location.
 * Needed by the purge walker.
 */
static enum heap_entry_type
heap_guessType(StoreEntry * entry, RemovalPolicyNode * node)
{
    if (node == &entry->repl)
	return TYPE_STORE_ENTRY;
    if (entry->mem_obj && node == &entry->mem_obj->repl)
	return TYPE_STORE_MEM;
    fatal("Heap Replacement: Unknown StoreEntry node type");
    return TYPE_UNKNOWN;
}
#define SET_POLICY_NODE(entry,value) \
    switch(heap->type) { \
    case TYPE_STORE_ENTRY: entry->repl.data = value; break ; \
    case TYPE_STORE_MEM: entry->mem_obj->repl.data = value ; break ; \
    default: break; \
    }

static void
heap_add(RemovalPolicy * policy, StoreEntry * entry, RemovalPolicyNode * node)
{
    HeapPolicyData *heap = policy->_data;
    assert(!node->data);
    if (EBIT_TEST(entry->flags, ENTRY_SPECIAL))
	return;			/* We won't manage these.. they messes things up */
    node->data = heap_insert(heap->heap, entry);
    heap->count += 1;
    if (!heap->type)
	heap->type = heap_guessType(entry, node);
    /* Add a little more variance to the aging factor */
    heap->heap->age += heap->heap->age / 100000000;
}

static void
heap_remove(RemovalPolicy * policy, StoreEntry * entry,
    RemovalPolicyNode * node)
{
    HeapPolicyData *heap = policy->_data;
    heap_node *hnode = node->data;
    if (!hnode)
	return;
    heap_delete(heap->heap, hnode);
    node->data = NULL;
    heap->count -= 1;
}

static void
heap_referenced(RemovalPolicy * policy, const StoreEntry * entry,
    RemovalPolicyNode * node)
{
    HeapPolicyData *heap = policy->_data;
    heap_node *hnode = node->data;
    if (!hnode)
	return;
    heap_update(heap->heap, hnode, (StoreEntry *) entry);
}

/** RemovalPolicyWalker **/

typedef struct _HeapWalkData HeapWalkData;
struct _HeapWalkData {
    int current;
};

static const StoreEntry *
heap_walkNext(RemovalPolicyWalker * walker)
{
    HeapWalkData *heap_walk = walker->_data;
    RemovalPolicy *policy = walker->_policy;
    HeapPolicyData *heap = policy->_data;
    StoreEntry *entry;
    if (heap_walk->current >= heap_nodes(heap->heap))
	return NULL;		/* done */
    entry = (StoreEntry *) heap_peep(heap->heap, heap_walk->current++);
    return entry;
}

static void
heap_walkDone(RemovalPolicyWalker * walker)
{
    RemovalPolicy *policy = walker->_policy;
    HeapPolicyData *heap = policy->_data;
    assert(strcmp(policy->_type, "heap") == 0);
    assert(heap->nwalkers > 0);
    heap->nwalkers -= 1;
    safe_free(walker->_data);
    cbdataFree(walker);
}

static RemovalPolicyWalker *
heap_walkInit(RemovalPolicy * policy)
{
    HeapPolicyData *heap = policy->_data;
    RemovalPolicyWalker *walker;
    HeapWalkData *heap_walk;
    heap->nwalkers += 1;
    walker = cbdataAlloc(RemovalPolicyWalker);
    heap_walk = xcalloc(1, sizeof(*heap_walk));
    heap_walk->current = 0;
    walker->_policy = policy;
    walker->_data = heap_walk;
    walker->Next = heap_walkNext;
    walker->Done = heap_walkDone;
    return walker;
}

/** RemovalPurgeWalker **/

typedef struct _HeapPurgeData HeapPurgeData;
struct _HeapPurgeData {
    link_list *locked_entries;
    heap_key min_age;
};

static StoreEntry *
heap_purgeNext(RemovalPurgeWalker * walker)
{
    HeapPurgeData *heap_walker = walker->_data;
    RemovalPolicy *policy = walker->_policy;
    HeapPolicyData *heap = policy->_data;
    StoreEntry *entry;
    heap_key age;
  try_again:
    if (!heap_nodes(heap->heap) > 0)
	return NULL;		/* done */
    age = heap_peepminkey(heap->heap);
    entry = heap_extractmin(heap->heap);
    if (storeEntryLocked(entry)) {
	storeLockObject(entry);
	linklistPush(&heap_walker->locked_entries, entry);
	goto try_again;
    }
    heap_walker->min_age = age;
    SET_POLICY_NODE(entry, NULL);
    return entry;
}

static void
heap_purgeDone(RemovalPurgeWalker * walker)
{
    HeapPurgeData *heap_walker = walker->_data;
    RemovalPolicy *policy = walker->_policy;
    HeapPolicyData *heap = policy->_data;
    StoreEntry *entry;
    assert(strcmp(policy->_type, "heap") == 0);
    assert(heap->nwalkers > 0);
    heap->nwalkers -= 1;
    if (heap_walker->min_age > 0) {
	heap->heap->age = heap_walker->min_age;
	debug(81, 3) ("heap_purgeDone: Heap age set to %f\n",
	    (double) heap->heap->age);
    }
    /*
     * Reinsert the locked entries
     */
    while ((entry = linklistShift(&heap_walker->locked_entries))) {
	heap_node *node = heap_insert(heap->heap, entry);
	SET_POLICY_NODE(entry, node);
	storeUnlockObject(entry);
    }
    safe_free(walker->_data);
    cbdataFree(walker);
}

static RemovalPurgeWalker *
heap_purgeInit(RemovalPolicy * policy, int max_scan)
{
    HeapPolicyData *heap = policy->_data;
    RemovalPurgeWalker *walker;
    HeapPurgeData *heap_walk;
    heap->nwalkers += 1;
    walker = cbdataAlloc(RemovalPurgeWalker);
    heap_walk = xcalloc(1, sizeof(*heap_walk));
    heap_walk->min_age = 0.0;
    heap_walk->locked_entries = NULL;
    walker->_policy = policy;
    walker->_data = heap_walk;
    walker->max_scan = max_scan;
    walker->Next = heap_purgeNext;
    walker->Done = heap_purgeDone;
    return walker;
}

static void
heap_free(RemovalPolicy * policy)
{
    HeapPolicyData *heap = policy->_data;
    /* Make some verification of the policy state */
    assert(strcmp(policy->_type, "heap") == 0);
    assert(heap->nwalkers);
    assert(heap->count);
    /* Ok, time to destroy this policy */
    safe_free(policy->_data);
    memset(policy, 0, sizeof(*policy));
    cbdataFree(policy);
}

RemovalPolicy *
createRemovalPolicy_heap(wordlist * args)
{
    RemovalPolicy *policy;
    HeapPolicyData *heap_data;
    const char *keytype;
    /* Allocate the needed structures */
    policy = cbdataAlloc(RemovalPolicy);
    heap_data = xcalloc(1, sizeof(*heap_data));
    /* Initialize the policy data */
    heap_data->policy = policy;
    if (args) {
	keytype = args->key;
	args = args->next;
    } else {
	debug(81, 1) ("createRemovalPolicy_heap: No key type specified. Using LRU\n");
	keytype = "LRU";
    }
    if (!strcmp(keytype, "GDSF"))
	heap_data->keyfunc = HeapKeyGen_StoreEntry_GDSF;
    else if (!strcmp(keytype, "LFUDA"))
	heap_data->keyfunc = HeapKeyGen_StoreEntry_LFUDA;
    else if (!strcmp(keytype, "LRU"))
	heap_data->keyfunc = HeapKeyGen_StoreEntry_LRU;
    else {
	debug(81, 0) ("createRemovalPolicy_heap: Unknown key type \"%s\". Using LRU\n",
	    keytype);
	heap_data->keyfunc = HeapKeyGen_StoreEntry_LRU;
    }
    /* No additional arguments expected */
    assert(!args);
    heap_data->heap = new_heap(1000, heap_data->keyfunc);
    heap_data->heap->age = 1.0;
    /* Populate the policy structure */
    policy->_type = "heap";
    policy->_data = heap_data;
    policy->Free = heap_free;
    policy->Add = heap_add;
    policy->Remove = heap_remove;
    policy->Referenced = NULL;
    policy->Dereferenced = heap_referenced;
    policy->WalkInit = heap_walkInit;
    policy->PurgeInit = heap_purgeInit;
    /* Increase policy usage count */
    nr_heap_policies += 0;
    return policy;
}


text:
#ifndef _Stroika_Foundation_Configuration_Private_Defaults_Characters_TChar_h_
#define _Stroika_Foundation_Configuration_Private_Defaults_Characters_TChar_h_ 1

/*
 * This file is a private Stroika implementation detail, and shouldn't be included directly.
 * Its used by StroikaConfig.h - optionally included there -
 * to help implement the set of Stroika public configuration defines.
 */

// First DEFINE qTargetPlatformSDKUseswchar_t
#ifndef qTargetPlatformSDKUseswchar_t
#if (defined(_UNICODE) || defined(UNICODE))
#define qTargetPlatformSDKUseswchar_t 1
#else
#define qTargetPlatformSDKUseswchar_t 0
#endif
#endif

// Then VALIDATE qTargetPlatformSDKUseswchar_t with respect to other common defines
#if defined(_WINDOWS)
#if qTargetPlatformSDKUseswchar_t
#if !defined(_UNICODE) || !defined(UNICODE)
#error "INCONSITENT VALS"
#endif
#else
#if defined(_UNICODE) || defined(UNICODE)
#error "INCONSITENT VALS"
#endif
#endif
#endif

#endif /*_Stroika_Foundation_Configuration_Private_Defaults_Characters_TChar_h_*/


text:
/**
 * The main file of node-rfr.
 * @author Su Su <s@warmsea.net>
 */

var constants = require('./constants');
if (constants.isGlobal) {
  console.warn('Using rfr as a global module is error-prone.');
}

/**
 * The default root.
 * @type {String}
 */
var defaultRoot = constants.defaultRoot;
if (defaultRoot === null) {
  defaultRoot = process.env.RFR_ROOT || process.env.PWD || '';
}
defaultRoot = coerceRoot(defaultRoot);

/**
 * Trim a root and add tailing slash if not exists.
 * @param {String} root A root.
 * @returns {String} The coerced root.
 * @private
 */
function coerceRoot(root) {
  var coerced = root.substring().trim();
  var len = coerced.length;
  if (len > 0 && coerced[len - 1] !== '/') {
    coerced = coerced + '/';
  }
  return coerced;
}

/**
 * Return a module id which can be used by the builtin `require()`.
 * @param {String} idFromRoot A RFR module id.
 * @param {String} root The root.
 * @returns {String} A standard module id.
 * @private
 */
function normalizeId(idFromRoot, root) {
  var id = idFromRoot.substring().trim();
  if (root && id.length > 0 && id[0] === '/') {
    id = id.substring(1);
  }
  id = root + id;
  return id;
}

/**
 * Create a new version of rfr with a function.
 * @param {Function} callable The rfr require function.
 * @param {String} root The root for rfr require.
 * @param {Boolean} isMaster Whether this is a master rfr.
 * @private
 */
var createRfr = function(callable, root, isMaster) {
  rfr = callable.bind(callable);

  /**
   * A read-only property tells whether this rfr instance is a master one.
   * Call `require('rfr')` to get a master rfr instance.
   * User created rfr instances, such as `require('rfr')({ root: '...' })` are
   * not master ones.
   * @type {Boolean}
   */
  Object.defineProperty(rfr, 'isMaster', {
    configurable: false,
    enumerable: true,
    value: !!isMaster,
    writable: false
  });

  /**
   * A read-only property tells whether this rfr instance is a global master.
   * Call `require('rfr')` on a global rfr module to get a master rfr instance.
   * Using the global master is error-prone.
   * @type {Boolean}
   */
  Object.defineProperty(rfr, 'isGlobalMaster', {
    configurable: false,
    enumerable: true,
    value: constants.isGlobal && !!isMaster,
    writable: false
  });

  /**
   * The root of a rfr instance.
   * @type {String}
   */
  Object.defineProperty(rfr, 'root', {
    configurable: false,
    enumerable: true,
    get: function() {
      return callable.root;
    },
    set: function(root) {
      callable.root = coerceRoot(root);
    }
  });

  /**
   * Set the root.
   * @param {String} root The new root.
   */
  rfr.setRoot = function(root) {
    this.root = root;
  };

  /**
   * Get the filename that will be loaded when this rfr is called.
   * @returns {String} module filename.
   */
  rfr.resolve = function(idFromRoot) {
    return require.resolve(normalizeId(idFromRoot, this.root));
  };

  rfr.root = root;
  return rfr;
};

/**
 * Create a new version of rfr.
 * @param {{root:String}} config config of this version.
 * @returns {rfr} a new rfr version.
 * @private
 */
function createVersion(config) {
  if (!(config && (typeof config.root === 'string'
      || config.root === null || config.root === undefined))) {
    throw new Error('"config.root" is required and must be a string');
  }
  var root = config.root;
  if (root === null || root === undefined) {
    root = defaultRoot;
  }

  return createRfr(function(idFromRoot) {
    if (typeof idFromRoot !== 'string') {
      throw new Error('A string is required for the argument of ' +
      'a user created RFR version.');
    }
    return require(normalizeId(idFromRoot, this.root));
  }, root);
}

/**
 * Do the RFR require action, or create a new version of RFR.
 * If a string is passed as the argument, this function will do the RFR require
 * action. Else, this function will create a new version of RFR with the
 * argument as config.
 * @function
 * @param {String|Object} idFromRoot Module id or RFR config.
 * @returns {Module|RFR} A module or a RFR version.
 */
var rfr = createRfr(function(idFromRoot) {
  if (typeof idFromRoot === 'string') {
    return require(normalizeId(idFromRoot, this.root));
  } else {
    return createVersion(idFromRoot);
  }
}, defaultRoot, true);

module.exports = rfr;


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using work.bacome.imapclient.support;

namespace work.bacome.imapclient
{
    /// <summary>
    /// Carries data sent to a server.
    /// </summary>
    /// <seealso cref="cIMAPClient.NetworkSend"/>
    public class cNetworkSendEventArgs : EventArgs
    {
        /// <summary>
        /// The number of bytes sent (<see langword="null"/> if this can't be disclosed).
        /// </summary>
        public readonly int? Bytes;

        /// <summary>
        /// The bytes sent (sensitive data redacted).
        /// </summary>
        public readonly ReadOnlyCollection<cBytes> Buffers;

        internal cNetworkSendEventArgs(cBytes pBuffer)
        {
            Bytes = pBuffer.Count;
            List<cBytes> lBuffers = new List<cBytes>(1);
            lBuffers.Add(pBuffer);
            Buffers = lBuffers.AsReadOnly();
        }

        internal cNetworkSendEventArgs(IEnumerable<byte> pBuffer)
        {
            cBytes lBuffer = new cBytes(new List<byte>(pBuffer));
            Bytes = lBuffer.Count;
            List<cBytes> lBuffers = new List<cBytes>(1);
            lBuffers.Add(lBuffer);
            Buffers = lBuffers.AsReadOnly();
        }

        internal cNetworkSendEventArgs(int? pBytes, IEnumerable<cBytes> pBuffers)
        {
            Bytes = pBytes;
            Buffers = new List<cBytes>(pBuffers).AsReadOnly();
        }

        /// <inheritdoc/>
        public override string ToString()
        {
            var lBuilder = new cListBuilder(nameof(cNetworkSendEventArgs));
            if (Bytes != null) lBuilder.Append(Bytes);
            foreach (var lBuffer in Buffers) lBuilder.Append(lBuffer.ToString(80));
            return lBuilder.ToString();
        }
    }
}


text:
<!DOCTYPE html>

    <title>05 IfBit3IsOneOrZero</title>
    <meta http-equiv="Content-Type" content="text/html" charset="utf-8" />

05. Write a boolean expression for finding if the bit 3 (counting from 0) of a given integer is 1 or 0.

The result is printed on the JS console...


text:
package org.cloudfoundry.operations.useradmin;

import org.junit.Test;

public final class DeleteUserRequestTest {

    @Test(expected = IllegalStateException.class)
    public void noUsername() {
        DeleteUserRequest.builder()
            .build();
    }

    @Test
    public void valid() {
        DeleteUserRequest.builder()
            .username("test-username")
            .build();
    }

}


text:
import Ember from 'ember';

export default Ember.Test.registerAsyncHelper('waitFor', (app, ms) => {
  Ember.run.later(() => {}, ms);
  return app.testHelpers.wait();
});


text:
<?php

namespace Google\AdsApi\Dfp\v201702;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class ConversionEvent
{
    const UNKNOWN = 'UNKNOWN';
    const CREATIVE_VIEW = 'CREATIVE_VIEW';
    const START = 'START';
    const SKIP_SHOWN = 'SKIP_SHOWN';
    const FIRST_QUARTILE = 'FIRST_QUARTILE';
    const MIDPOINT = 'MIDPOINT';
    const THIRD_QUARTILE = 'THIRD_QUARTILE';
    const ENGAGED_VIEW = 'ENGAGED_VIEW';
    const COMPLETE = 'COMPLETE';
    const MUTE = 'MUTE';
    const UNMUTE = 'UNMUTE';
    const PAUSE = 'PAUSE';
    const REWIND = 'REWIND';
    const RESUME = 'RESUME';
    const SKIPPED = 'SKIPPED';
    const FULLSCREEN = 'FULLSCREEN';
    const EXPAND = 'EXPAND';
    const COLLAPSE = 'COLLAPSE';
    const ACCEPT_INVITATION = 'ACCEPT_INVITATION';
    const CLOSE = 'CLOSE';
    const CLICK_TRACKING = 'CLICK_TRACKING';
    const SURVEY = 'SURVEY';
    const CUSTOM_CLICK = 'CUSTOM_CLICK';
    const MEASURABLE_IMPRESSION = 'MEASURABLE_IMPRESSION';
    const VIEWABLE_IMPRESSION = 'VIEWABLE_IMPRESSION';
    const VIDEO_ABANDON = 'VIDEO_ABANDON';
    const FULLY_VIEWABLE_AUDIBLE_HALF_DURATION_IMPRESSION = 'FULLY_VIEWABLE_AUDIBLE_HALF_DURATION_IMPRESSION';

}


text:
// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

package jodd.upload;

import java.io.IOException;
import java.io.InputStream;

/**
 * Encapsulates base for uploaded file. Its instance may be
 * either valid, when it represent an uploaded file, or invalid
 * when uploaded file doesn't exist or there was a problem with it.
 */
public abstract class FileUpload {

	protected final MultipartRequestInputStream input;
	protected final int maxFileSize;
	protected final FileUploadHeader header;

	protected FileUpload(MultipartRequestInputStream input, int maxFileSize) {
		this.input = input;
		this.header = input.lastHeader;
		this.maxFileSize = maxFileSize;
	}

	// ----------------------------------------------------------------  header

	/**
	 * Returns {@link FileUploadHeader} of uploaded file.
	 */
	public FileUploadHeader getHeader() {
		return header;
	}

	// ---------------------------------------------------------------- data

	/**
	 * Returns all bytes of uploaded file.
	 */
	public abstract byte[] getFileContent() throws IOException;

	/**
	 * Returns input stream of uploaded file.
	 */
	public abstract InputStream getFileInputStream() throws IOException;

	// ---------------------------------------------------------------- size and validity

	protected boolean valid;

	protected int size = -1;

	protected boolean fileTooBig;

	/**
	 * Returns the file upload size or -1 if file was not uploaded.
	 */
	public int getSize() {
		return size;
	}

	/**
	 * Returns true if file was uploaded.
	 */
	public boolean isUploaded() {
		return size != -1;
	}

	/**
	 * Returns true if upload process went correctly.
	 * This still does not mean that file is uploaded, e.g. when file
	 * was not specified on the form.
	 */
	public boolean isValid() {
		return valid;
	}

	/**
	 * Returns max file size or -1 if there is no max file size.
	 */
	public int getMaxFileSize() {
		return maxFileSize;
	}

	/**
	 * Returns true if file is too big. File will be marked as invalid.
	 */
	public boolean isFileTooBig() {
		return fileTooBig;
	}

	// ---------------------------------------------------------------- status

	/**
	 * Returns true if uploaded file content is stored in memory.
	 */
	public abstract boolean isInMemory();

	// ---------------------------------------------------------------- process

	/**
	 * Process request input stream. Note that file size is unknown at this point.
	 * Therefore, the implementation should set the {@link #getSize() size}
	 * attribute after successful processing. This method also must set the
	 * {@link #isValid() valid} attribute.
	 *
	 * @see MultipartRequestInputStream
	 */
	protected abstract void processStream() throws IOException;

	// ---------------------------------------------------------------- toString

	/**
	 * Returns basic information about the uploaded file.
	 */
	@Override
	public String toString() {
		return "FileUpload: uploaded=[" + isUploaded() + "] valid=[" + valid + "] field=[" +
				header.getFormFieldName() + "] name=[" + header.getFileName() + "] size=[" + size + ']';
	}
}