signature:
public class SizeableLinkedList { /** * Inserts the specified element at the specified position in this list ( optional operation ) . Shifts the element
 * currently at that position ( if any ) and any subsequent elements to the right ( adds one to their indices ) .
 * @ param index index at which the specified element is to be inserted .
 * @ param element element to be inserted .
 * @ throws UnsupportedOperationException if the < tt > add < / tt > method is not supported by this list .
 * @ throws ClassCastException if the class of the specified element prevents it from being added to this
 * list .
 * @ throws NullPointerException if the specified element is null and this list does not support null
 * elements .
 * @ throws IllegalArgumentException if some aspect of the specified element prevents it from being added to
 * this list .
 * @ throws IndexOutOfBoundsException if the index is out of range ( index & lt ; 0 | | index & gt ; size ( ) ) . */
public void add ( int index , T element ) { } }

implementation: super . add ( index , element ) ; sizeOf += element . sizeof ( ) ;


signature:
public class SizeableLinkedList { /** * Removes the element at the specified position in this list ( optional operation ) . Shifts any subsequent elements
 * to the left ( subtracts one from their indices ) . Returns the element that was removed from the list .
 * @ param index the index of the element to removed .
 * @ return the element previously at the specified position .
 * @ throws UnsupportedOperationException if the < tt > remove < / tt > method is not supported by this list .
 * @ throws IndexOutOfBoundsException if the index is out of range ( index & lt ; 0 | | index & gt ; = size ( ) ) . */
public T remove ( int index ) { } }

implementation: T result = super . remove ( index ) ; sizeOf += ( result != null ) ? result . sizeof ( ) : 0 ; return result ;


signature:
public class SizeableLinkedList { /** * Appends all of the elements in the specified collection to the end of this list , in the order that they are
 * returned by the specified collection ' s iterator ( optional operation ) . The behavior of this operation is
 * unspecified if the specified collection is modified while the operation is in progress . ( Note that this will
 * occur if the specified collection is this list , and it ' s nonempty . )
 * @ param c collection whose elements are to be added to this list .
 * @ return < tt > true < / tt > if this list changed as a result of the call .
 * @ throws UnsupportedOperationException if the < tt > addAll < / tt > method is not supported by this list .
 * @ throws ClassCastException if the class of an element in the specified collection prevents it from
 * being added to this list .
 * @ throws NullPointerException if the specified collection contains one or more null elements and this
 * list does not support null elements , or if the specified collection is < tt >
 * null < / tt > .
 * @ throws IllegalArgumentException if some aspect of an element in the specified collection prevents it from
 * being added to this list .
 * @ see # add ( Object ) */
public boolean addAll ( Collection < ? extends T > c ) { } }

implementation: if ( c instanceof Sizeable ) { sizeOf += ( ( Sizeable ) c ) . sizeof ( ) ; } return super . addAll ( c ) ;


signature:
public class UnoptimizedByteCodePrinter { /** * { @ inheritDoc } */
protected void enterClause ( Clause clause ) { } }

implementation: if ( clause instanceof WAMCompiledQuery ) { WAMOptimizeableListing query = ( WAMCompiledQuery ) clause ; for ( WAMInstruction instruction : query . getUnoptimizedInstructions ( ) ) { addLineToRow ( instruction . toString ( ) ) ; nextRow ( ) ; } }


signature:
public class UnoptimizedByteCodePrinter { /** * { @ inheritDoc } */
protected void enterPredicate ( Predicate predicate ) { } }

implementation: if ( predicate instanceof WAMCompiledPredicate ) { WAMOptimizeableListing compiledPredicate = ( WAMCompiledPredicate ) predicate ; for ( WAMInstruction instruction : compiledPredicate . getUnoptimizedInstructions ( ) ) { addLineToRow ( instruction . toString ( ) ) ; nextRow ( ) ; } }


signature:
public class BaseHeuristicSearch { /** * Creates the correct type of search nodes for this search . This search uses heuristic search nodes .
 * @ param state The search space state to create a search node for .
 * @ return The state encapsulated in a heuristic search node . */
public SearchNode < O , T > createSearchNode ( T state ) { } }

implementation: return new HeuristicSearchNode < O , T > ( state , heuristic ) ;


signature:
public class BuiltInTransform { /** * Applies a built - in replacement transformation to functors . If the functor matches built - in , a
 * { @ link BuiltInFunctor } is created with a mapping to the functors built - in implementation , and the functors
 * arguments are copied into this new functor . If the functor does not match a built - in , it is returned unmodified .
 * @ param functor The functor to attempt to map onto a built - in .
 * @ return The functor umodified , or a { @ link BuiltInFunctor } replacement for it . */
public BuiltInFunctor apply ( Functor functor ) { } }

implementation: FunctorName functorName = interner . getFunctorFunctorName ( functor ) ; Class < ? extends BuiltInFunctor > builtInClass ; if ( builtIns . containsKey ( functorName ) ) { builtInClass = builtIns . get ( functorName ) ; } else { builtInClass = DefaultBuiltIn . class ; } return ReflectionUtils . newInstance ( ReflectionUtils . getConstructor ( builtInClass , new Class [ ] { Functor . class } ) , new Object [ ] { functor } ) ;


signature:
public class TraceIndenter { /** * Generates a sequence of spaces to indent debugging output with .
 * @ param delta The amount to change the current trace indent by . If this is negative it is subtracted before the
 * sequence of spaces is generated , if it is positive it is added after .
 * @ return A sequence of spaces to use for nesting call traces in debug output with . */
public String generateTraceIndent ( int delta ) { } }

implementation: if ( ! useIndent ) { return "" ; } else { if ( delta >= 1 ) { indentStack . push ( delta ) ; } else if ( delta < 0 ) { indentStack . pop ( ) ; } StringBuffer result = new StringBuffer ( ) ; traceIndent += ( delta < 0 ) ? delta : 0 ; for ( int i = 0 ; i < traceIndent ; i ++ ) { result . append ( " " ) ; } traceIndent += ( delta > 0 ) ? delta : 0 ; return result . toString ( ) ; }


signature:
public class DefaultBuiltIn { /** * { @ inheritDoc } */
public SizeableLinkedList < WAMInstruction > compileBodyCall ( Functor expression , boolean isFirstBody , boolean isLastBody , boolean chainRule , int permVarsRemaining ) { } }

implementation:
// Used to build up the results in .
SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Generate the call or tail - call instructions , followed by the call address , which is f _ n of the
// called program .
if ( isLastBody ) { // Deallocate the stack frame at the end of the clause , but prior to calling the last
// body predicate .
// This is not required for chain rules , as they do not need a stack frame .
if ( ! chainRule ) { instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Deallocate ) ) ; } instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Execute , interner . getFunctorFunctorName ( expression ) ) ) ; } else { instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Call , ( byte ) ( permVarsRemaining & 0xff ) , interner . getFunctorFunctorName ( expression ) ) ) ; } return instructions ;


signature:
public class DefaultBuiltIn { /** * { @ inheritDoc } */
public SizeableLinkedList < WAMInstruction > compileBodyArguments ( Functor expression , boolean isFirstBody , FunctorName clauseName , int bodyNumber ) { } }

implementation:
// Used to build up the results in .
SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Allocate argument registers on the body , to all functors as outermost arguments .
// Allocate temporary registers on the body , to all terms not already allocated .
/* if ( ! isFirstBody )
 lastAllocatedRegister = 0; */
allocateArgumentRegisters ( expression ) ; allocateTemporaryRegisters ( expression ) ; // Loop over all of the arguments to the outermost functor .
int numOutermostArgs = expression . getArity ( ) ; for ( int j = 0 ; j < numOutermostArgs ; j ++ ) { Term nextOutermostArg = expression . getArgument ( j ) ; int allocation = ( Integer ) symbolTable . get ( nextOutermostArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; byte addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; byte address = ( byte ) ( allocation & 0xff ) ; // On the first occurrence of a variable output a put _ var .
// On a subsequent variable occurrence output a put _ val .
if ( nextOutermostArg . isVar ( ) && ! seenRegisters . contains ( allocation ) ) { seenRegisters . add ( allocation ) ; // The variable has been moved into an argument register .
// varNames . remove ( ( byte ) allocation ) ;
// varNames . put ( ( byte ) j , ( ( Variable ) nextOutermostArg ) . getName ( ) ) ;
/* log . fine ( " PUT _ VAR " + ( ( addrMode = = REG _ ADDR ) ? " X " : " Y " ) + address + " , A " + j ) ; */
WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutVar , addrMode , address , ( byte ) ( j & 0xff ) ) ; instructions . add ( instruction ) ; // Record the way in which this variable was introduced into the clause .
symbolTable . put ( nextOutermostArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Put ) ; } else if ( nextOutermostArg . isVar ( ) ) { // Check if this is the last body functor in which this variable appears , it does so only in argument
// position , and this is the first occurrence of these conditions . In which case , an unsafe put is to
// be used .
if ( isLastBodyTermInArgPositionOnly ( ( Variable ) nextOutermostArg , expression ) && ( addrMode == WAMInstruction . STACK_ADDR ) ) { /* log . fine ( " PUT _ UNSAFE _ VAL " + ( ( addrMode = = REG _ ADDR ) ? " X " : " Y " ) + address + " , A " + */
WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutUnsafeVal , addrMode , address , ( byte ) ( j & 0xff ) ) ; instructions . add ( instruction ) ; symbolTable . put ( nextOutermostArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_LAST_ARG_FUNCTOR , null ) ; } else { /* log . fine ( " PUT _ VAL " + ( ( addrMode = = REG _ ADDR ) ? " X " : " Y " ) + address + " , A " + j ) ; */
WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutVal , addrMode , address , ( byte ) ( j & 0xff ) ) ; instructions . add ( instruction ) ; } } // When a functor is encountered , output a put _ struc .
else if ( nextOutermostArg . isFunctor ( ) ) { Term nextFunctorArg = ( Functor ) nextOutermostArg ; // Heap cells are to be created in an order such that no heap cell can appear before other cells that it
// refers to . A postfix traversal of the functors in the term to compile is used to achieve this , as
// child functors in a head will be visited first .
// Walk over the query term in post - fix order , picking out just the functors .
QueueBasedSearchMethod < Term , Term > postfixSearch = new PostFixSearch < Term , Term > ( ) ; postfixSearch . reset ( ) ; postfixSearch . addStartState ( nextFunctorArg ) ; postfixSearch . setGoalPredicate ( new FunctorTermPredicate ( ) ) ; Iterator < Term > treeWalker = Searches . allSolutions ( postfixSearch ) ; // For each functor encountered : put _ struc .
while ( treeWalker . hasNext ( ) ) { Functor nextFunctor = ( Functor ) treeWalker . next ( ) ; allocation = ( Integer ) symbolTable . get ( nextFunctor . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; address = ( byte ) ( allocation & 0xff ) ; // Ouput a put _ struc instuction , except on the outermost functor .
/* log . fine ( " PUT _ STRUC " + interner . getFunctorName ( nextFunctor ) + " / " + nextFunctor . getArity ( ) +
 ( ( addrMode = = REG _ ADDR ) ? " , X " : " , Y " ) + address ) ; */
WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . PutStruc , addrMode , address , interner . getDeinternedFunctorName ( nextFunctor . getName ( ) ) , nextFunctor ) ; instructions . add ( instruction ) ; // For each argument of the functor .
int numArgs = nextFunctor . getArity ( ) ; for ( int i = 0 ; i < numArgs ; i ++ ) { Term nextArg = nextFunctor . getArgument ( i ) ; allocation = ( Integer ) symbolTable . get ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; address = ( byte ) ( allocation & 0xff ) ; // If it is new variable : set _ var or put _ var .
// If it is variable or functor already seen : set _ val or put _ val .
if ( nextArg . isVar ( ) && ! seenRegisters . contains ( allocation ) ) { seenRegisters . add ( allocation ) ; /* log . fine ( " SET _ VAR " + ( ( addrMode = = REG _ ADDR ) ? " X " : " Y " ) + address ) ; */
instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . SetVar , addrMode , address , nextArg ) ; // Record the way in which this variable was introduced into the clause .
symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Set ) ; } else { // Check if the variable is ' local ' and use a local instruction on the first occurrence .
VarIntroduction introduction = ( VarIntroduction ) symbolTable . get ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO ) ; if ( isLocalVariable ( introduction , addrMode ) ) { /* log . fine ( " SET _ LOCAL _ VAL " + ( ( addrMode = = REG _ ADDR ) ? " X " : " Y " ) +
 address ) ; */
instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . SetLocalVal , addrMode , address , nextArg ) ; symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , null ) ; } else { /* log . fine ( " SET _ VAL " + ( ( addrMode = = REG _ ADDR ) ? " X " : " Y " ) + address ) ; */
instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . SetVal , addrMode , address , nextArg ) ; } } instructions . add ( instruction ) ; } } } } return instructions ;


signature:
public class DefaultBuiltIn { /** * For a predicate of arity n , the first n registers are used to receive its arguments in .
 * < p / > Non - variable arguments appearing directly within a functor are allocated to argument registers . This means
 * that they are directly referenced from the argument registers that pass them to predicate calls , or directly
 * referenced from the argument registers that are used to read them as call arguments .
 * < p / > Variables appearing as functor arguments are not allocated in this way , but are kept in registers with
 * positions higher than the number of arguments . The reason for this , is that a variable can appear multiple times
 * in an expression ; it may not always be the same argument . Variables are assigned to other registers , then copied
 * into the argument registers as needed .
 * < p / > Argument registers are allocated by argument position within the functor . This means that gaps will be left
 * in the numbering for variables to be copied in as needed .
 * @ param expression The clause head functor to allocate argument registers to . */
protected void allocateArgumentRegisters ( Functor expression ) { } }

implementation:
// Assign argument registers to functors appearing directly in the argument of the outermost functor .
// Variables are never assigned directly to argument registers .
int reg = 0 ; for ( ; reg < expression . getArity ( ) ; reg ++ ) { Term term = expression . getArgument ( reg ) ; if ( term instanceof Functor ) { /* log . fine ( " X " + lastAllocatedTempReg + " = " + interner . getFunctorFunctorName ( ( Functor ) term ) ) ; */
int allocation = ( reg & 0xff ) | ( REG_ADDR << 8 ) ; symbolTable . put ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION , allocation ) ; } }


signature:
public class DefaultBuiltIn { /** * Allocates terms within a functor expression to registers . The outermost functor itself is not assigned to a
 * register in WAM ( only in l0 ) . Functors already directly assigned to argument registers will not be re - assigned by
 * this . Variables as arguments will be assigned but not as argument registers .
 * @ param expression The expression to walk over . */
protected void allocateTemporaryRegisters ( Term expression ) { } }

implementation:
// Need to assign registers to the whole syntax tree , working in from the outermost functor . The outermost
// functor itself is not assigned to a register in l3 ( only in l0 ) . Functors already directly assigned to
// argument registers will not be re - assigned by this , variables as arguments will be assigned .
SearchMethod outInSearch = new BreadthFirstSearch < Term , Term > ( ) ; outInSearch . reset ( ) ; outInSearch . addStartState ( expression ) ; Iterator < Term > treeWalker = Searches . allSolutions ( outInSearch ) ; // Discard the outermost functor from the variable allocation .
treeWalker . next ( ) ; // For each term encountered : set X + + = term .
while ( treeWalker . hasNext ( ) ) { Term term = treeWalker . next ( ) ; if ( symbolTable . get ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) == null ) { int allocation = ( lastAllocatedTempReg ++ & 0xff ) | ( REG_ADDR << 8 ) ; symbolTable . put ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION , allocation ) ; } }


signature:
public class DefaultBuiltIn { /** * Determines whether a variable is local , that is , it may only exist on the stack . When variables are introduced
 * into clauses , the way in which they are introduced is recorded using the { @ link VarIntroduction } enum . When a
 * variable is being written to the heap for the first time , this check may be used to see if a ' local ' variant of
 * an instruction is needed , in order to globalize the variable on the heap .
 * < p / > The conditions for a variable being deemed local are :
 * < ul >
 * < li > For a permanent variable , not initialized in this clause with set _ var or unify _ var instruction . < / li >
 * < li > For a temporary variable , not initialized in this clause with set _ var or unify _ var or put _ var instruction .
 * < / li >
 * < / ul >
 * @ param introduction The type of instruction that introduced the variable into the clause .
 * @ param addrMode The addressing mode of the variable , permanent variables are stack allocated .
 * @ return < tt > true < / tt > iff the variable is unsafe . */
protected boolean isLocalVariable ( VarIntroduction introduction , byte addrMode ) { } }

implementation: if ( WAMInstruction . STACK_ADDR == addrMode ) { return ( introduction == VarIntroduction . Get ) || ( introduction == VarIntroduction . Put ) ; } else { return introduction == VarIntroduction . Get ; }


signature:
public class DefaultBuiltIn { /** * Checks if a variable is appearing within the last body functor in which it occurs , and only does so within
 * argument position .
 * @ param var The variable to check .
 * @ param body The current body functor being processed .
 * @ return < tt > true < / tt > iff this is the last body functor that the variable appears in and does so only in argument
 * position . */
private boolean isLastBodyTermInArgPositionOnly ( Term var , Functor body ) { } }

implementation: return body == symbolTable . get ( var . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_LAST_ARG_FUNCTOR ) ;


signature:
public class ProtoDTLearningMethod { /** * Builds a decision tree by repeatedly selecting the best property of the data examples to split on . The best
 * property is chosen to be the one that reveals the most information about the target property to learn .
 * < p > The constructed decision tree is then used to create a classifying machine for that tree which is returned .
 * @ return A classifying machine built from the learned decision tree .
 * @ throws LearningFailureException If there is not exactly one output property to learn for . This algorithm can
 * only handle a single output property . */
public ClassifyingMachine learn ( ) throws LearningFailureException { } }

implementation:
/* log . fine ( " public ClassifyingMachine learn ( ) : called " ) ; */
// Call the initialize method to ensure that input and output properties are correctly set up .
initialize ( ) ; // Check that there is only one output property to learn for . Decision trees can only output a single
// property classification ( although mutliple trees could be built for multiple properties ) .
if ( outputProperties . size ( ) != 1 ) { throw new LearningFailureException ( "Decision trees can only learn a classification for a single property, " + "but " + outputProperties . size ( ) + " have been set as outputs." , null ) ; } // Extract the single output property to learn for .
String outputProperty = outputProperties . iterator ( ) . next ( ) ; // Check that the output property to be learnt is one with a finite number of values . Decision trees
// cannot learn infinite valued attributes , such as real numbers etc .
int numValues = inputExamples . iterator ( ) . next ( ) . getComponentType ( ) . getPropertyType ( outputProperty ) . getNumPossibleValues ( ) ; if ( numValues < 1 ) { throw new LearningFailureException ( "Decision trees can only learn a classification for a " + "property with a finite number of values. The property, " + outputProperty + " can have an infinite number of values and should be " + "discretized prior to being learned by decision trees." , null ) ; } // Used to queue nodes that are pending construction .
Queue < DecisionTree > pendingNodes = new LinkedList < DecisionTree > ( ) ; // Create a pending node , ( an empty tree , the examples , the attributes , the default classification ) .
Pending startNode = new Pending ( inputExamples , inputProperties , getMajorityClassification ( outputProperty , inputExamples ) , null ) ; // Create the root of the decision tree out of this start pending node .
DecisionTree decisionTree = new DecisionTree ( startNode ) ; // Push this new pending node onto the construction queue .
pendingNodes . offer ( decisionTree ) ; // Loop until the queue of nodes pending construction is empty .
while ( ! pendingNodes . isEmpty ( ) ) { /* log . fine ( " Got next pending node . " ) ; */
// Get the tree fragment for the next pending node . The data element should always be safe to cast to a
// Pending node as this algorithm only pushes pending nodes onto the queue .
DecisionTree currentTreePendingNode = pendingNodes . remove ( ) ; DecisionTreeElement currentTreePendingNodeElement = currentTreePendingNode . getElement ( ) ; Pending currentNode = ( Pending ) currentTreePendingNodeElement ; // Extract the examples , the attributes , the default classification , and the attribute to be matched ,
// for this pending node .
Collection < State > examples = currentNode . getExamples ( ) ; Collection < String > undecidedProperties = currentNode . getUndecidedProperties ( ) ; OrdinalAttribute defaultAttribute = currentNode . getDefault ( ) ; OrdinalAttribute matchingAttribute = currentNode . getAttributeValue ( ) ; /* log . fine ( " Pending node corresponds to " + examples . size ( ) + " examples . " ) ; */
/* log . fine ( " Pending node has " + undecidedProperties . size ( ) + " undecided properties left . " ) ; */
// Used to hold the decision tree fragment ( decision node , pending node or assignment leaf ) that will
// be inserted into the decision tree to replace the current pending node .
DecisionTree newTreeFragment = null ; // If the set of examples is empty then set the default as the leaf .
if ( examples . isEmpty ( ) ) { /* log . fine ( " Examples is empty . " ) ; */
newTreeFragment = new DecisionTree ( new Assignment ( outputProperty , defaultAttribute , matchingAttribute ) ) ; } // Else if undecided properties is empty then set the majority value of the classification of
// examples as the leaf .
else if ( undecidedProperties . isEmpty ( ) ) { /* log . fine ( " No undecided properties left . " ) ; */
// Work out what the majority classification is and create a leaf with that assignment .
OrdinalAttribute majority = getMajorityClassification ( outputProperty , inputExamples ) ; newTreeFragment = new DecisionTree ( new Assignment ( outputProperty , majority , matchingAttribute ) ) ; } // Else if all the examples have the same classification then set that classification as the leaf .
else if ( allHaveSameClassification ( outputProperty , examples ) ) { /* log . fine ( " All examples have the same classification . " ) ; */
newTreeFragment = new DecisionTree ( new Assignment ( outputProperty , allClassification , matchingAttribute ) ) ; } // Else choose the best attribute ( with the largest estimated information gain ) on the classification .
else { /* log . fine ( " Choosing the best property to split on . " ) ; */
String bestProperty = chooseBestPropertyToDecideOn ( outputProperty , examples , inputProperties ) ; // Check if a best property could not be found , in which case behave as if there are no
// input properties left to work with .
if ( bestProperty == null ) { /* log . fine ( " Couldn ' t find a best property to split on . " ) ; */
// Put the pending node back onto the construction queue but with zero input properties .
Pending newPendingNode = new Pending ( examples , new ArrayList < String > ( ) , defaultAttribute , matchingAttribute ) ; newTreeFragment = new DecisionTree ( newPendingNode ) ; pendingNodes . offer ( newTreeFragment ) ; } else { // Extract an attribute with this property name from the first example and use this to get
// a listing of all the possible values of that attribute .
Attribute bestAttribute = ( OrdinalAttribute ) examples . iterator ( ) . next ( ) . getProperty ( bestProperty ) ; /* log . fine ( " bestProperty = " + bestProperty ) ; */
/* log . fine ( " bestAttribute = " + bestAttribute ) ; */
// Create a decision node that decides on the best property . New pending nodes will be created
// as children of this node and added to it .
newTreeFragment = new DecisionTree ( new Decision ( bestProperty , bestAttribute . getType ( ) . getNumPossibleValues ( ) , matchingAttribute ) ) ; // Produce a cut down input property set equal to the old one but with the selected best property
// removed as a decision node is to be created for it .
Set < String > newInputProperties = new HashSet < String > ( inputProperties ) ; newInputProperties . remove ( bestProperty ) ; // For each possible value of the best attribute .
for ( Iterator < ? extends Attribute > i = bestAttribute . getType ( ) . getAllPossibleValuesIterator ( ) ; i . hasNext ( ) ; ) { OrdinalAttribute nextAttribute = ( OrdinalAttribute ) i . next ( ) ; // Extract just those examples with the current value . To implement this efficiently first sort
// the examples by their attribute value for the best property to split on using a range sort
// ( O ( n ) time as num possible values is limited and they are already indexed by their order ) .
// Create the new example collection as simply a pair of indexes into the sorted list .
Collection < State > matchingExamples = new ArrayList < State > ( ) ; for ( State example : examples ) { // Extract the attribute value for the property to decide on .
OrdinalAttribute testAttribute = ( OrdinalAttribute ) example . getProperty ( bestProperty ) ; // Check if it matches the current value being extracted and add it to the collection of
// extracted examples if so .
if ( nextAttribute . equals ( testAttribute ) ) { matchingExamples . add ( example ) ; } } // Push onto the queue , a child node for this value , the subset of examples ( or the value to
// select that subset on ) , attributes without the best one ( or an exclusion list of attributes
// used so far ) , default majority - value of classification of these examples .
Pending newPendingNode = new Pending ( matchingExamples , newInputProperties , getMajorityClassification ( outputProperty , matchingExamples ) , nextAttribute ) ; DecisionTree newPendingNodeTreeFragment = new DecisionTree ( newPendingNode ) ; pendingNodes . offer ( newPendingNodeTreeFragment ) ; /* log . fine ( " Created new pending node below the split , for " + matchingExamples . size ( ) +
 " examples and " + newInputProperties . size ( ) + " undecided properties . " ) ; */
// Add the new pending node as a child of the parent decision node for the best property .
newTreeFragment . addChild ( newPendingNodeTreeFragment ) ; } } } // Remove the current pending node from the decision tree and replace it with the new element that the
// algorithm has selected .
Tree . Node parentTree = ( DecisionTree ) currentTreePendingNode . getParent ( ) ; // Check if the current pending node has a parent ( if not it is the real tree root and the first pending
// node created ) .
if ( parentTree != null ) { // Remove the pending node from its parents child list .
parentTree . getChildren ( ) . remove ( currentTreePendingNode ) ; // Replace the pending node with the newly built tree fragment in its parent child list .
parentTree . addChild ( newTreeFragment ) ; } else { // Update the root tree pointer to point to the newly built tree fragment .
decisionTree = newTreeFragment ; } /* log . fine ( " There are now " + pendingNodes . size ( ) + " pending nodes on the construction queue . " ) ; */
} // Loop over the whole decision tree initializing its quick lookup tables for all the decisions it contains .
for ( Iterator < SimpleTree < DecisionTreeElement > > i = decisionTree . iterator ( Tree . IterationOrder . PreOrder ) ; i . hasNext ( ) ; ) { DecisionTree nextTreeFragment = ( DecisionTree ) i . next ( ) ; DecisionTreeElement nextElement = nextTreeFragment . getElement ( ) ; // Check if it is a decision and build its lookup table if so .
if ( nextElement instanceof Decision ) { Decision decision = ( Decision ) nextElement ; decision . initializeLookups ( nextTreeFragment ) ; } } // Create a new decisition tree machine out of the fully constructed decision tree .
ProtoDTMachine dtMachine = new ProtoDTMachine ( ) ; dtMachine . setDecisionTree ( decisionTree ) ; // Return the trained decision tree classifying machine .
return dtMachine ;


signature:
public class ProtoDTLearningMethod { /** * This helper method works out how the majority of the specified examples are classified by the named property . The
 * property should always be the goal property that the algorithm is learning and must always take on a finite
 * number of different values .
 * @ param property The name of the property to find the majority classification for .
 * @ param examples A collection of state objects to count over in order to find the majority classification for the
 * named property .
 * @ return The value of the majority classification for the named property or null if the example collection was
 * empty so no majority could be found .
 * @ throws LearningFailureException If the number of possible value that the specified property can take on is not
 * finite . */
private OrdinalAttribute getMajorityClassification ( String property , Iterable < State > examples ) throws LearningFailureException { } }

implementation:
/* log . fine ( " private OrdinalAttribute getMajorityClassification ( String property , Collection < State > examples ) : called " ) ; */
/* log . fine ( " property = " + property ) ; */
// Flag used to indicate that the map to hold the value counts in has been initialized .
Map < OrdinalAttribute , Integer > countMap = null ; // Used to hold the biggest count found so far .
int biggestCount = 0 ; // Used to hold the value with the biggest count found so far .
OrdinalAttribute biggestAttribute = null ; // Loop over all the examples counting the number of occurences of each possible classification by the
// named property .
for ( State example : examples ) { OrdinalAttribute nextAttribute = ( OrdinalAttribute ) example . getProperty ( property ) ; /* log . fine ( " nextAttribute = " + nextAttribute ) ; */
// If this is the first attribute then find out how many possible values it can take on .
if ( countMap == null ) { // A check has already been performed at the start of the learning method to ensure that the output
// property only takes on a finite number of values .
countMap = new HashMap < OrdinalAttribute , Integer > ( ) ; } int count ; // Increment the count for the number of occurences of this classification .
if ( ! countMap . containsKey ( nextAttribute ) ) { count = 1 ; countMap . put ( nextAttribute , count ) ; } else { count = countMap . get ( nextAttribute ) ; countMap . put ( nextAttribute , count ++ ) ; } // Compare it to the biggest score found so far to see if it is bigger .
if ( count > biggestCount ) { // Update the biggest score .
biggestCount = count ; // Update the value of the majority classification .
biggestAttribute = nextAttribute ; } } // Return the majority classification found .
return biggestAttribute ;


signature:
public class ProtoDTLearningMethod { /** * Tests if a property of a set of examples has the same value for all the examples . This algorithm works by
 * iterating through the examples until two different values are found or the end of the collection is reached
 * having found only one value .
 * < p > As a side effect this method leaves the value of the classification in the member variable
 * { @ link # allClassification } when all the examples do match .
 * @ param property The name of the property to test .
 * @ param examples A collection of state objects to iterate over in order to test if they all have the same value
 * for the named property .
 * @ return true if they all have the same value ; false otherwise . */
private boolean allHaveSameClassification ( String property , Iterable < State > examples ) { } }

implementation:
// Used to hold the value of the first attribute seen .
OrdinalAttribute firstAttribute = null ; // Flag used to indicate that the test passed successfully .
boolean success = true ; // Loop over all the examples .
for ( State example : examples ) { OrdinalAttribute nextAttribute = ( OrdinalAttribute ) example . getProperty ( property ) ; // If this is the first example just store its attribute value .
if ( firstAttribute == null ) { firstAttribute = nextAttribute ; } // Otherwise check if the attribute value does not match the first one in which case the test fails .
else if ( ! nextAttribute . equals ( firstAttribute ) ) { success = false ; break ; } } // If the test passed then store the matching classification that all the examples have in a memeber variable
// from where it can be accessed .
if ( success ) { allClassification = firstAttribute ; } return success ;


signature:
public class ProtoDTLearningMethod { /** * For a given set of examples , input properties and an output property this method chooses the input property that
 * provides the largest information gain on the value of the output property .
 * @ param outputProperty The name of the property to compare the information gain of the input properties against .
 * @ param examples A collection of state objects to count over in order to find the highest information gain
 * input property .
 * @ param inputProperties A collection of input properties to find the best one amongst .
 * @ return The name of the input property with the highest information gain . */
private String chooseBestPropertyToDecideOn ( String outputProperty , Iterable < State > examples , Iterable < String > inputProperties ) { } }

implementation:
/* log . fine ( " private String chooseBestPropertyToDecideOn ( String outputProperty , Collection < State > examples , " +
 " Collection < String > inputProperties ) : called " ) ; */
// for ( State e : examples ) / * log . fine ( e ) ; * /
// Determine how many possible values ( symbols ) the output property can have .
int numOutputValues = examples . iterator ( ) . next ( ) . getComponentType ( ) . getPropertyType ( outputProperty ) . getNumPossibleValues ( ) ; // Used to hold the largest information gain found so far .
double largestGain = 0.0d ; // Used to hold the input property that gives the largest gain found so far .
String largestGainProperty = null ; // Loop over all the input properties .
for ( String inputProperty : inputProperties ) { // let G = the set of goal property values .
// let A = the set of property values that the input property can have .
// Determine how many possible values ( symbols ) the input property can have .
int numInputValues = examples . iterator ( ) . next ( ) . getComponentType ( ) . getPropertyType ( inputProperty ) . getNumPossibleValues ( ) ; // Create an array to hold the counts of the output symbols .
int [ ] outputCounts = new int [ numOutputValues ] ; // Create arrays to hold the counts of the input symbols and the joint input / output counts .
int [ ] inputCounts = new int [ numInputValues ] ; int [ ] [ ] jointCounts = new int [ numInputValues ] [ numOutputValues ] ; // Loop over all the examples .
for ( State example : examples ) { // Extract the output property attribute value .
OrdinalAttribute outputAttribute = ( OrdinalAttribute ) example . getProperty ( outputProperty ) ; // Extract the input property attribute value .
OrdinalAttribute inputAttribute = ( OrdinalAttribute ) example . getProperty ( inputProperty ) ; // Increment the count for the occurence of this value of the output property .
outputCounts [ outputAttribute . ordinal ( ) ] ++ ; // Increment the count for the occurence of this value of the input property .
inputCounts [ inputAttribute . ordinal ( ) ] ++ ; // Increment the count for the joint occurrence of this input / output value pair .
jointCounts [ inputAttribute . ordinal ( ) ] [ outputAttribute . ordinal ( ) ] ++ ; } // Calculate the estimated probability distribution of G from the occurrence counts over the examples .
double [ ] pForG = InformationTheory . pForDistribution ( outputCounts ) ; // Calculate the estimated probability distribution of A from the occurrence counts over the examples .
double [ ] pForA = InformationTheory . pForDistribution ( inputCounts ) ; // Calculate the estimated probability distribution p ( g | a ) from the joint occurrence counts over the
// examples .
double [ ] [ ] pForGGivenA = InformationTheory . pForJointDistribution ( jointCounts ) ; // Calculate the information gain on G by knowing A .
double gain = InformationTheory . gain ( pForG , pForA , pForGGivenA ) ; // Check if the gain is larger than the best found so far and update the best if so .
if ( gain > largestGain ) { largestGain = gain ; largestGainProperty = inputProperty ; } } return largestGainProperty ;


signature:
public class TermBuilder { /** * Creates a functor .
 * @ param name The name of the functor .
 * @ param args The functors arguments .
 * @ return A functor . */
public Functor functor ( String name , Term ... args ) { } }

implementation: int internedName = interner . internFunctorName ( name , args . length ) ; return new Functor ( internedName , args ) ;


signature:
public class TermBuilder { /** * Creates an atom ( functor with no arguments ) .
 * @ param name The name of the atom .
 * @ return An atom . */
public Functor atom ( String name ) { } }

implementation: int internedName = interner . internFunctorName ( name , 0 ) ; return new Functor ( internedName , null ) ;


signature:
public class TermBuilder { /** * Creates a variable . If the variable name begins with an underscore " _ " , it will be anonymous , otherwise it will
 * be named .
 * @ param name The name of the variable .
 * @ return A variable . */
public Variable var ( String name ) { } }

implementation: boolean isAnonymous = name . startsWith ( "_" ) ; int internedName = interner . internVariableName ( name ) ; return new Variable ( internedName , null , isAnonymous ) ;


signature:
public class RedirectAction { /** * Handles an HTTP request sent to this action by struts . This simply forwards to the location specified by the
 * " redirect " request parameter .
 * @ param mapping The Struts action mapping .
 * @ param form The Struts form associated with this action .
 * @ param request The HTTP request .
 * @ param response The HTTP response .
 * @ param errors The Struts action errors object to place any errors in .
 * @ return A forward to the " redirect " location . */
public ActionForward executeWithErrorHandling ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response , ActionErrors errors ) { } }

implementation:
log . fine ( "public ActionForward performWithErrorHandling(ActionMapping mapping, ActionForm form," + "HttpServletRequest request, HttpServletResponse response, " + "ActionErrors errors): called" ) ; HttpSession session = request . getSession ( ) ; DynaBean dynaForm = ( DynaActionForm ) form ; // Redirect to the specified location
String redirect = ( String ) dynaForm . get ( REDIRECT ) ; log . fine ( "redirect = " + redirect ) ; return new ActionForward ( redirect , true ) ;


signature:
public class PagedList { /** * Extracts the sub - list at the specified page index . The returned list will have size equal to the page size unless
 * it is the last page in which case it may not be a full page .
 * @ param index The sub - list index to extract .
 * @ return The sub - list as a { @ link java . util . List } .
 * @ throws IndexOutOfBoundsException If the index is < 0 or larger that the number of pages ( list size / page size +
 * ( list size % page size = = 0 ? 0 : 1 ) ) . */
public List < E > get ( int index ) { } }

implementation:
/* log . fine ( " public List < E > get ( int index ) : called " ) ; */
// Check that the index is not to large .
int originalSize = original . size ( ) ; int size = ( originalSize / pageSize ) + ( ( ( originalSize % pageSize ) == 0 ) ? 0 : 1 ) ; /* log . fine ( " originalSize = " + originalSize ) ; */
/* log . fine ( " size = " + size ) ; */
// Check if the size of the underlying list is zero , in which case return an empty list , so long as page zero
// was requested .
if ( ( index == 0 ) && ( originalSize == 0 ) ) { return new ArrayList < E > ( ) ; } // Check if the requested index exceeds the number of pages , or is an illegal negative value .
if ( ( index >= size ) || ( index < 0 ) ) { /* log . fine ( " ( index > = size ) | | ( index < 0 ) , throwing out of bounds exception . " ) ; */
throw new IndexOutOfBoundsException ( "Index " + index + " is less than zero or more than the number of pages: " + size ) ; } // Extract the appropriate sub - list .
// Note that if this is the last page it may not be a full page . Just up to the last page will be returned .
/* log . fine ( " Requesting sublist from , " + ( pageSize * index ) + " , to , " +
 ( ( ( pageSize * ( index + 1 ) ) > = originalSize ) ? originalSize : ( pageSize * ( index + 1 ) ) ) + " . " ) ; */
List < E > result = original . subList ( pageSize * index , ( ( pageSize * ( index + 1 ) ) >= originalSize ) ? originalSize : ( pageSize * ( index + 1 ) ) ) ; return result ;


signature:
public class DiscreetScrollBarUI { /** * { @ inheritDoc } */
protected void paintTrack ( Graphics g , JComponent c , Rectangle bounds ) { } }

implementation: g . setColor ( colorScheme . getToolingBackground ( ) ) ; g . fillRect ( bounds . x , bounds . y , bounds . width , bounds . height ) ;


signature:
public class DiscreetScrollBarUI { /** * { @ inheritDoc } */
protected void paintThumb ( Graphics g , JComponent c , Rectangle thumbBounds ) { } }

implementation:
if ( thumbBounds . isEmpty ( ) || ! scrollbar . isEnabled ( ) ) { return ; } g . translate ( thumbBounds . x , thumbBounds . y ) ; boolean vertical = isVertical ( ) ; int hgap = vertical ? 2 : 1 ; int vgap = vertical ? 1 : 2 ; int w = thumbBounds . width - ( hgap * 2 ) ; int h = thumbBounds . height - ( vgap * 2 ) ; // leave one pixel between thumb and right or bottom edge
if ( vertical ) { h -= 1 ; } else { w -= 1 ; } g . setColor ( colorScheme . getToolingActiveBackground ( ) ) ; g . fillRect ( hgap + 1 , vgap + 1 , w - 1 , h - 1 ) ; g . setColor ( colorScheme . getToolingActiveBackground ( ) ) ; g . drawRoundRect ( hgap , vgap , w , h , 3 , 3 ) ; g . translate ( - thumbBounds . x , - thumbBounds . y ) ;


signature:
public class DiscreetScrollBarUI { /** * { @ inheritDoc } */
protected Dimension getMinimumThumbSize ( ) { } }

implementation: int thickness = THICKNESS ; return isVertical ( ) ? new Dimension ( thickness , thickness * 2 ) : new Dimension ( thickness * 2 , thickness ) ;


signature:
public class Surface { /** * Sets the kind of paint to use . For the image background ?
 * @ param obj The paint to use . */
public void setTexture ( Paint obj ) { } }

implementation: if ( obj instanceof GradientPaint ) { texture = new GradientPaint ( 0 , 0 , Color . white , getSize ( ) . width * 2 , 0 , Color . green ) ; } else { texture = obj ; }


signature:
public class Surface { /** * Immediately repaints the surface .
 * < p / > It ' s possible to turn off double - buffering for just the repaint calls invoked directly on the non double
 * buffered component . This can be done by overriding paintImmediately ( ) ( which is called as a result of repaint )
 * and getting the current RepaintManager and turning off double buffering in the RepaintManager before calling
 * super . paintImmediately ( g ) .
 * @ param x The X coord to start painting at .
 * @ param y The Y coord to start painting at .
 * @ param w The width of the region to paint .
 * @ param h The height of the region to paint . */
public void paintImmediately ( int x , int y , int w , int h ) { } }

implementation: RepaintManager repaintManager = null ; boolean save = true ; if ( ! isDoubleBuffered ( ) ) { repaintManager = RepaintManager . currentManager ( this ) ; save = repaintManager . isDoubleBufferingEnabled ( ) ; repaintManager . setDoubleBufferingEnabled ( false ) ; } super . paintImmediately ( x , y , w , h ) ; if ( repaintManager != null ) { repaintManager . setDoubleBufferingEnabled ( save ) ; }


signature:
public class Surface { /** * Renders the surface . This method will create a buffered image to render in if one does not already exist . If
 * rendering is to be done directly to the screen no buffered image will be generated . If the size of the buffered
 * image does not match the Graphics context size then a new buffered image will be generated of the correct size
 * before rendering . The { @ link # render } method will be called to do the actual drawing .
 * @ param g The graphics context to paint . */
public void paint ( Graphics g ) { } }

implementation:
// Get the size of the surface
Dimension d = getSize ( ) ; // Check if direct to screen rendering is to be used
if ( imageType == 1 ) { // Use no buffered image for direct rendering
bimg = null ; } // Check if no buffered image has been created yet or if the existing one has the wrong size
else if ( ( bimg == null ) || ( biw != d . width ) || ( bih != d . height ) ) { // Create a new bufferd image . Note that imageType has two subtracted for it as type 0 stands for auto
// selection and type 1 for direct to screen . Subtracting two corresponds to the image types in the
// BufferedImage class .
bimg = createBufferedImage ( d . width , d . height , imageType - 2 ) ; // Set clear once flag to clear the new image on the first pass
clearOnce = true ; } // Build a Graphics2D context for the image
Graphics2D g2 = createGraphics2D ( d . width , d . height , bimg , g ) ; // Call the subclass to perform rendering
render ( d . width , d . height , g2 ) ; // Clear up the Graphics2D context
g2 . dispose ( ) ; // Check if a buffered image was used ( and not direct to screen rendering )
if ( bimg != null ) { // Copy the buffered image onto the screen
g . drawImage ( bimg , 0 , 0 , null ) ; // Ensure screen is up to date
toolkit . sync ( ) ; }


signature:
public class Surface { /** * Generates a fresh buffered image of the appropriate type .
 * @ param w The image width .
 * @ param h The image height .
 * @ param imgType The image type . Note that this should be two less than the image types defined as constants in
 * this class to correspond with the image type constants defined in BufferedImage . This class uses
 * 0 for auto image type selection and 1 for direct to screen .
 * @ return A buffered image of the specifed size and type . */
protected BufferedImage createBufferedImage ( int w , int h , int imgType ) { } }

implementation:
BufferedImage bi = null ; if ( imgType == 0 ) { bi = ( BufferedImage ) createImage ( w , h ) ; } else if ( ( imgType > 0 ) && ( imgType < 14 ) ) { bi = new BufferedImage ( w , h , imgType ) ; } else if ( imgType == 14 ) { bi = createBinaryImage ( w , h , 2 ) ; } else if ( imgType == 15 ) { bi = createBinaryImage ( w , h , 4 ) ; } else if ( imgType == 16 ) { bi = createSGISurface ( w , h , 32 ) ; } else if ( imgType == 17 ) { bi = createSGISurface ( w , h , 16 ) ; } // Store the buffered image size
biw = w ; bih = h ; return bi ;


signature:
public class Surface { /** * Creates a Graphics2D drawing context from a BufferedImage or Graphics context . The graphics context is built
 * using the properties defined for the surface . This method is used to generate the Graphics2D context that
 * subclasses will render in . IF the buffered image is null then the passed in Graphics context will be used to
 * generate the Graphics2D context . This is the case when no buffered image is used and the subclass renders
 * straight to the screen .
 * @ param width The width of the buffered image .
 * @ param height The height of the buffered image .
 * @ param bi The buffered image to generate a Graphics2D context for , or null if the next param is to be used .
 * @ param g The Graphics context to generate a Graphics2D context for , only used if bi is null .
 * @ return A Graphics2D drawing context of the specified size and type . */
protected Graphics2D createGraphics2D ( int width , int height , BufferedImage bi , Graphics g ) { } }

implementation:
Graphics2D g2 = null ; // Check if the buffered image is null
if ( bi != null ) { // Create Graphics2D context for the buffered image
g2 = bi . createGraphics ( ) ; } else { // The buffered image is null so create Graphics2D context for the Graphics context
g2 = ( Graphics2D ) g ; } // @ todo what is this for ?
g2 . setBackground ( getBackground ( ) ) ; // Set the rendering properties of the graphics context
g2 . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , antiAlias ) ; g2 . setRenderingHint ( RenderingHints . KEY_RENDERING , rendering ) ; // Check the clear flags to see if the graphics context should be cleared
if ( clearSurface || clearOnce ) { // Clear the image
g2 . clearRect ( 0 , 0 , width , height ) ; // Reset the clear once flag to show that clearing has been done
clearOnce = false ; } // Check if a background fill texture is to be used
if ( texture != null ) { // set composite to opaque for texture fills
g2 . setComposite ( AlphaComposite . SrcOver ) ; g2 . setPaint ( texture ) ; g2 . fillRect ( 0 , 0 , width , height ) ; } // Check if alpha compositing is to be used
if ( composite != null ) { // Set the alpha compositing algorithm
g2 . setComposite ( composite ) ; } return g2 ;


signature:
public class Surface { /** * Creates a custom grey - scale binary image format .
 * @ param w The image width .
 * @ param h The image height .
 * @ param pixelBits The number of grey - scale bits to use . Must be 1 , 2 or 4.
 * @ return A buffered image of the specifed size and type . */
private BufferedImage createBinaryImage ( int w , int h , int pixelBits ) { } }

implementation: int bytesPerRow = w * pixelBits / 8 ; if ( ( w * pixelBits % 8 ) != 0 ) { bytesPerRow ++ ; } byte [ ] imageData = new byte [ h * bytesPerRow ] ; IndexColorModel cm = null ; switch ( pixelBits ) { case 1 : { cm = new IndexColorModel ( pixelBits , lut1Arr . length , lut1Arr , lut1Arr , lut1Arr ) ; break ; } case 2 : { cm = new IndexColorModel ( pixelBits , lut2Arr . length , lut2Arr , lut2Arr , lut2Arr ) ; break ; } case 4 : { cm = new IndexColorModel ( pixelBits , lut4Arr . length , lut4Arr , lut4Arr , lut4Arr ) ; break ; } default : { new Exception ( "Invalid # of bit per pixel" ) . printStackTrace ( ) ; } } DataBuffer db = new DataBufferByte ( imageData , imageData . length ) ; WritableRaster r = Raster . createPackedRaster ( db , w , h , pixelBits , null ) ; return new BufferedImage ( cm , r , false , null ) ;


signature:
public class Surface { /** * Creates a custom colour image format .
 * @ param w The image width .
 * @ param h The image height .
 * @ param pixelBits The number of bits - per - pixel to use . Must be 16 or 32.
 * @ return A buffered image of the specifed size and type . */
private BufferedImage createSGISurface ( int w , int h , int pixelBits ) { } }

implementation: int rMask32 = 0xFF000000 ; int rMask16 = 0xF800 ; int gMask32 = 0x00FF0000 ; int gMask16 = 0x07C0 ; int bMask32 = 0x0000FF00 ; int bMask16 = 0x003E ; DirectColorModel dcm = null ; DataBuffer db = null ; WritableRaster wr = null ; switch ( pixelBits ) { case 16 : { short [ ] imageDataUShort = new short [ w * h ] ; dcm = new DirectColorModel ( 16 , rMask16 , gMask16 , bMask16 ) ; db = new DataBufferUShort ( imageDataUShort , imageDataUShort . length ) ; wr = Raster . createPackedRaster ( db , w , h , w , new int [ ] { rMask16 , gMask16 , bMask16 } , null ) ; break ; } case 32 : { int [ ] imageDataInt = new int [ w * h ] ; dcm = new DirectColorModel ( 32 , rMask32 , gMask32 , bMask32 ) ; db = new DataBufferInt ( imageDataInt , imageDataInt . length ) ; wr = Raster . createPackedRaster ( db , w , h , w , new int [ ] { rMask32 , gMask32 , bMask32 } , null ) ; break ; } default : { new Exception ( "Invalid # of bit per pixel" ) . printStackTrace ( ) ; } } return new BufferedImage ( dcm , wr , false , null ) ;


signature:
public class WAMCompiledPredicatePrintingVisitor { /** * { @ inheritDoc } */
public void visit ( Predicate predicate ) { } }

implementation: if ( traverser . isEnteringContext ( ) ) { initializePrinters ( ) ; } else if ( traverser . isLeavingContext ( ) ) { printTable ( ) ; } super . visit ( predicate ) ;


signature:
public class MockWebServerUtils { /** * Workaround MockWebServer issue # 11.
 * @ see < a href = " https : / / code . google . com / p / mockwebserver / issues / detail ? id = 11 " > Issue # 11 < / a > */
public static RecordedRequest takeRequest ( MockWebServer server ) throws InterruptedException { } }

implementation: RecordedRequest request = server . takeRequest ( ) ; while ( "GET /favicon.ico HTTP/1.1" . equals ( request . getRequestLine ( ) ) ) { request = server . takeRequest ( ) ; } return request ;


signature:
public class ValidEnumValidator { /** * { @ inheritDoc } */
public boolean isValid ( EnumeratedStringAttribute value , ConstraintValidatorContext context ) { } }

implementation: if ( value == null ) { return true ; } return value . getId ( ) != - 1 ;


signature:
public class ApiController { /** * Handles requests that accept application / json . */
@ RequestMapping ( value = { } }

implementation: "/{schema:[^\\.]+}" , "/{schema}.json" } , produces = "application/json" , headers = { "Accept=application/json" } ) @ ResponseBody public Report processJsonRequest ( @ PathVariable String schema , HttpServletRequest request ) throws ServiceException , InvalidParameterException , InvalidSchemaException { LOG . info ( "Processing JSON request for parameters " + request . getQueryString ( ) ) ; return processRequest ( schema , request ) ;


signature:
public class ApiController { /** * Generic processor of all types of requests .
 * Validates schema availability , mandatory fields for the specified schema
 * and creates chains of { @ link QueryParameterAware } to be processed by the
 * underlying { @ link GenericSchemaService } .
 * @ param schema Schema from where to extract the information .
 * @ param request Request in generic form so the parameters can be dynamically
 * extract .
 * @ return Returns a { @ link Report } Object delivered by the { @ link GenericSchemaService } .
 * @ throws ServiceException Exception generated by the underlying Service .
 * @ throws InvalidParameterException Exception generated by the controller due to an invalid
 * parameter for the chosen schema .
 * @ throws InvalidSchemaException Exception generated by the controller when an invalid schema
 * is requested . */
@ SuppressWarnings ( "unchecked" ) private Report processRequest ( String schema , HttpServletRequest request ) throws ServiceException , InvalidParameterException , InvalidSchemaException { } }

implementation:
long begin = System . currentTimeMillis ( ) ; SchemaDefinition config = schemaRepository . getStarSchemaConfig ( schema ) ; if ( config == null ) { LOG . warn ( "Invalid endpoint \"" + schema + "\"" ) ; throw new InvalidSchemaException ( "Invalid endpoint" ) ; } Map < String , String [ ] > params = request . getParameterMap ( ) ; for ( String mandatory : MANDATORY_FIELDS ) { if ( ! params . containsKey ( mandatory ) ) { // mandatory fields are case sensitive
LOG . error ( "Mandatory field \"" + mandatory + "\" missing" ) ; throw new InvalidParameterException ( "Missing mandatory field " + mandatory ) ; } } QueryParameterEnvelope queryParameterDto = new QueryParameterEnvelope ( ) ; for ( String key : params . keySet ( ) ) { if ( DOMAIN_PARAMETERS . contains ( key ) ) { String domainParameter = params . get ( key ) [ 0 ] ; final DomainParserAware systemParameter = SystemParameter . valueOf ( key ) ; systemParameter . parseValue ( domainParameter , config , queryParameterDto ) ; } else { Pair < String , String > pair = splitKey ( key ) ; if ( ! config . isValidDimension ( pair . getLeft ( ) , pair . getRight ( ) ) ) { LOG . warn ( "Invalid parameter \"" + key + "\" for endpoint \"" + schema + "\"." ) ; throw new InvalidParameterException ( "Invalid parameter " + key + " for endpoint " + schema + "" ) ; } String [ ] multiParam = request . getParameterValues ( key ) ; for ( String param : multiParam ) { queryParameterDto . addConstraints ( new HttpQueryConstraint ( config , key , param ) ) ; } } } final Report report = schemaService . generateReport ( config , queryParameterDto ) ; report . setRecords ( inMemoryPagination ( report . getRecords ( ) , queryParameterDto ) ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "Query successfully processed for schema " + schema + " in " + ( System . currentTimeMillis ( ) - begin ) + "s." ) ; } return report ;


signature:
public class ApiController { /** * Handles { @ link ServiceException } generated by the underlying layer .
 * @ param exception of type { @ link ServiceException }
 * @ return A { @ link ResponseEntity } with the { @ link HttpStatus # INTERNAL _ SERVER _ ERROR }
 * code and a message describing the error itself . */
@ ExceptionHandler ( ServiceException . class ) @ ResponseBody public ResponseEntity < String > handleServiceException ( ServiceException exception ) { } }

implementation: HttpHeaders headers = new HttpHeaders ( ) ; headers . setContentType ( MediaType . TEXT_PLAIN ) ; return new ResponseEntity < String > ( exception . getMessage ( ) , headers , HttpStatus . INTERNAL_SERVER_ERROR ) ;


signature:
public class ApiController { /** * Handles { @ link InvalidParameterException } generated by the controller
 * itself when receives an invalid parameter .
 * @ param exception of type { @ link InvalidParameterException }
 * @ return A { @ link ResponseEntity } with the { @ link HttpStatus # BAD _ REQUEST }
 * code and a message describing the error itself . */
@ ExceptionHandler ( InvalidParameterException . class ) @ ResponseBody public ResponseEntity < String > handleControllerException ( InvalidParameterException exception ) { } }

implementation: HttpHeaders headers = new HttpHeaders ( ) ; headers . setContentType ( MediaType . TEXT_PLAIN ) ; return new ResponseEntity < String > ( exception . getMessage ( ) , headers , HttpStatus . BAD_REQUEST ) ;


signature:
public class ApiController { /** * Handles { @ link InvalidSchemaException } generated by the controller itself
 * when receives a request to a non existing schema configuration .
 * @ param exception of type { @ link InvalidSchemaException }
 * @ return A { @ link ResponseEntity } with the { @ link HttpStatus # NOT _ FOUND }
 * code and a message describing the error itself . */
@ ExceptionHandler ( InvalidSchemaException . class ) @ ResponseBody public ResponseEntity < String > handleInvalidSchemaException ( InvalidSchemaException exception ) { } }

implementation: HttpHeaders headers = new HttpHeaders ( ) ; headers . setContentType ( MediaType . TEXT_PLAIN ) ; return new ResponseEntity < String > ( exception . getMessage ( ) , headers , HttpStatus . NOT_FOUND ) ;


signature:
public class ApiController { /** * Creates a { @ link Pair } composed of Dimension and Information , required by
 * the { @ link GenericSchemaService } .
 * @ param key
 * @ return */
private static Pair < String , String > splitKey ( String key ) { } }

implementation: String dimension = null ; String info = null ; if ( ! key . contains ( "." ) ) { dimension = key ; } else { dimension = key . substring ( 0 , key . indexOf ( '.' ) ) ; info = key . substring ( key . indexOf ( '.' ) + 1 , key . length ( ) ) ; } return Pair . of ( dimension , info ) ;


signature:
public class ApiController { /** * TODO to be removed
 * @ param recordList
 * @ param queryParameterEnvelope
 * @ return */
private List < ReportRecord > inMemoryPagination ( final List < ReportRecord > recordList , QueryParameterEnvelope queryParameterEnvelope ) { } }

implementation: final QueryParameterAware pageSize = queryParameterEnvelope . getPageSize ( ) ; final QueryParameterAware pageNumber = queryParameterEnvelope . getPageNumber ( ) ; if ( pageSize != null && pageNumber != null ) { final Integer pageSizeValue = ( ( PageSizeConstraint ) pageSize ) . getPageSizeValue ( ) ; final Integer pageValue = ( ( PageNumberConstraint ) pageNumber ) . getPageNumberValue ( ) - 1 ; int offset = pageValue * pageSizeValue ; return recordList . subList ( offset > recordList . size ( ) ? recordList . size ( ) : offset , offset + pageSizeValue > recordList . size ( ) ? recordList . size ( ) : offset + pageSizeValue ) ; } return recordList ;


signature:
public class UndoStackBase { /** * { @ inheritDoc } */
public void restore ( ) { } }

implementation: boolean foundSavePoint = false ; while ( ! foundSavePoint && ! undoStack . isEmpty ( ) ) { Undoable undoable = undoStack . poll ( ) ; undoable . undo ( ) ; foundSavePoint = ( undoable instanceof SavePoint ) ; }


signature:
public class SqlTable { /** * Checks if the give column exist ( by name )
 * @ param columnName The name of the { @ link AbstractSqlColumn SqlColumn } */
public final boolean containsColumn ( String columnName ) { } }

implementation: if ( StringUtils . isNotBlank ( columnName ) ) { return sqlTableColumns . containsKey ( columnName ) ; } return false ;


signature:
public class UnoptimizedLabelPrinter { /** * { @ inheritDoc } */
protected void enterClause ( Clause clause ) { } }

implementation: if ( clause instanceof WAMCompiledQuery ) { WAMOptimizeableListing query = ( WAMCompiledQuery ) clause ; for ( WAMInstruction instruction : query . getUnoptimizedInstructions ( ) ) { WAMLabel label = instruction . getLabel ( ) ; addLineToRow ( ( label != null ) ? ( label . toPrettyString ( ) + ":" ) : "" ) ; nextRow ( ) ; } }


signature:
public class UnoptimizedLabelPrinter { /** * { @ inheritDoc } */
protected void enterPredicate ( Predicate predicate ) { } }

implementation: if ( predicate instanceof WAMCompiledPredicate ) { WAMOptimizeableListing compiledPredicate = ( WAMCompiledPredicate ) predicate ; for ( WAMInstruction instruction : compiledPredicate . getUnoptimizedInstructions ( ) ) { WAMLabel label = instruction . getLabel ( ) ; addLineToRow ( ( label != null ) ? ( label . toPrettyString ( ) + ":" ) : "" ) ; nextRow ( ) ; } }


signature:
public class PostFixSearch { /** * Allows different queue search algorithms to replace the default one . This overidden method ensures that the peek
 * at head flag is always set on the search algorithm and that it expands it successor nodes in reverse , as for
 * depth first searches .
 * @ param algorithm The search algorithm to use . */
protected void setQueueSearchAlgorithm ( QueueSearchAlgorithm < O , T > algorithm ) { } }

implementation: algorithm . setPeekAtHead ( true ) ; algorithm . setReverseEnqueueOrder ( true ) ; super . setQueueSearchAlgorithm ( algorithm ) ;


signature:
public class IterativeBoundAlgorithm { /** * Search iteratively on increasing maximum bound limits until the search space is exhausted or a goal state is
 * found .
 * @ param initSearch The algorithm to turn the start states into the intial set of search nodes , of the correct
 * type to begin the search with .
 * @ param startStates The set of start states to begin the search with .
 * @ param maxSteps The maximum number of steps to search for before giving up . If this is 0 or less then no
 * maximum number is enforced .
 * @ param searchSteps The number of steps taken so far . This may be greater than 0 if this search is run
 * iteratively and previous iterations of it have already been run .
 * @ return The first { @ link SearchNode } corresponding to a goal state that is found or null if none can be found
 * after exhaustive searching .
 * @ throws SearchNotExhaustiveException SearchNotExhaustiveException If the search terminates prematurely because
 * the maximum number of steps is reached . */
public SearchNode search ( QueueSearchState < O , T > initSearch , Collection < T > startStates , int maxSteps , int searchSteps ) throws SearchNotExhaustiveException { } }

implementation:
// Iteratively increase the bound until a search succeeds .
for ( float bound = startBound ; ; ) { // Set up the maximum bound for this iteration .
maxBound = bound ; // Use a try block as the depth bounded search will throw a MaxBoundException if it fails but there
// are successors states known to exist beyond the current max depth fringe .
try { // Get the number of search steps taken so far and pass this into the underlying depth bounded search
// so that the step count limit carries over between successive iterations .
int numStepsSoFar = initSearch . getStepsTaken ( ) ; // Call the super class search method to perform a depth bounded search on this maximum bound starting
// from the initial search state .
initSearch . resetEnqueuedOnceFlag ( ) ; SearchNode node = super . search ( initSearch , startStates , maxSteps , numStepsSoFar ) ; // Check if the current depth found a goal node
if ( node != null ) { return node ; } // The depth bounded search returned null , so it has exhausted the search space . Return with null .
else { return null ; } } // The depth bounded search failed but it knows that there are more successor states at deeper levels .
catch ( MaxBoundException e ) { // Do nothing , no node found at this depth so continue at the next depth level
e = null ; } // Check if the bound should be increased by epsilon or to the next smallest bound property value
// beyond the fringe and update the bound for the next iteration .
if ( useEpsilon ) { bound = bound + epsilon ; } else { bound = getMinBeyondBound ( ) ; } }


signature:
public class MemoryLayoutMonitorController { /** * { @ inheritDoc }
 * < p / > Creates the register monitor component and hooks it up to the register set . */
public void open ( ) { } }

implementation:
// Build a text grid panel in the left position .
grid = componentFactory . createTextGrid ( ) ; grid . insertVerticalSeparator ( 9 , 10 ) ; grid . insertVerticalSeparator ( 17 , 10 ) ; grid . insertVerticalSeparator ( 26 , 10 ) ; mainWindow . showConsole ( componentFactory . createTextGridPanel ( grid ) ) ; // Build a table model on the text grid , and construct a register monitor on the table .
table = ( EnhancedTextTable ) grid . createTable ( 0 , 0 , 20 , 20 ) ; monitor = new MemoryLayoutMonitor ( table ) ; // Attach a listener for updates to the register table .
table . addTextTableListener ( new TableUpdateHandler ( ) ) ;


signature: public class LinkTck { @ Test public void getRelWhenAnchorReturnsRelationship ( ) { } }

implementation: server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "" + "" ) ) ; String actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( "x" ) . getRel ( ) ; assertThat ( "link rel" , actual , is ( "x" ) ) ;


signature: public class LinkTck { @ Test public void getHrefWhenAnchorAndAbsoluteHrefReturnsUrl ( ) throws MalformedURLException { } }

implementation: server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "" + "" ) ) ; URL actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( "r" ) . getHref ( ) ; assertThat ( "link href" , actual , is ( new URL ( "http://x/" ) ) ) ;


signature: public class LinkTck { @ Test public void followWhenAnchorSubmitsRequest ( ) throws InterruptedException { } }

implementation: server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "a" + "" ) ) ; server ( ) . enqueue ( new MockResponse ( ) ) ; newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( "r" ) . follow ( ) ; server ( ) . takeRequest ( ) ; assertThat ( "request" , takeRequest ( server ( ) ) . getPath ( ) , is ( "/x" ) ) ;


signature: public class LinkTck { @ Test public void unwrapWithUnknownTypeThrowsException ( ) { } }

implementation: server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "" + "" ) ) ; Link link = newBrowser ( ) . get ( url ( server ( ) ) ) . getLink ( "x" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( "Cannot unwrap to: class java.lang.Void" ) ; link . unwrap ( Void . class ) ;


signature:
public class MaxStepsAlgorithm { /** * Search until a goal state is found or the maximum allowed number of steps is reached .
 * @ param initSearch The algorithm to turn the start states into the intial set of search nodes , of the correct
 * type to begin the search with .
 * @ param startStates The set of start states to begin the search with .
 * @ param maxSteps The maximum number of steps to search for before giving up . If this is 0 or less then no
 * maximum number is enforced .
 * @ param searchSteps The number of steps taken so far . This may be greater than 0 if this search is run
 * iteratively and previous iterations of it have already been run .
 * @ return The first { @ link SearchNode } corresponding to a goal state that is found or null if none can be found
 * after exhaustive searching .
 * @ throws SearchNotExhaustiveException SearchNotExhaustiveException If the search terminates prematurely because
 * the maximum number of steps is reached . */
public SearchNode search ( QueueSearchState < O , T > initSearch , Collection < T > startStates , int maxSteps , int searchSteps ) throws SearchNotExhaustiveException { } }

implementation:
// Initialize the queue with the start states set up in search nodes if this has not already been done .
// This will only be done on the first call to this method , as enqueueStartStates sets a flag when it is
// done . Subsequent searches continue from where the previous search left off . Have to call reset on
// the search method to really start the search again from the start states .
Queue < SearchNode < O , T > > queue = initSearch . enqueueStartStates ( startStates ) ; // Get the goal predicate configured as part of the enqueueing start states process .
UnaryPredicate < T > goalPredicate = initSearch . getGoalPredicate ( ) ; // Keep running until the queue becomes empty or a goal state is found .
while ( ! queue . isEmpty ( ) ) { // Extract or peek at the head element from the queue .
SearchNode < O , T > headNode = peekAtHead ? queue . peek ( ) : queue . remove ( ) ; // Expand the successors into the queue whether the current node is a goal state or not .
// This prepares the queue for subsequent searches , ensuring that goal states do not block
// subsequent goal states that exist beyond them .
if ( ! headNode . isExpanded ( ) ) { headNode . expandSuccessors ( queue , reverseEnqueue ) ; } // Get the node to be goal checked , either the head node or the new top of queue , depending on the
// peek at head flag . Again this is only a peek , the node is only to be removed if it is to be
// goal checked .
SearchNode < O , T > currentNode = peekAtHead ? queue . peek ( ) : headNode ; // Only goal check leaves , or nodes already expanded . ( The expanded flag will be set on leaves anyway ) .
if ( currentNode . isExpanded ( ) ) { // If required , remove the node to goal check from the queue .
currentNode = peekAtHead ? queue . remove ( ) : headNode ; // Check if the current node is a goal state .
if ( goalPredicate . evaluate ( currentNode . getState ( ) ) ) { return currentNode ; } } // Check if there is a maximum number of steps limit and increase the step count and check the limit if so .
if ( maxSteps > 0 ) { searchSteps ++ ; // Update the search state with the number of steps taken so far .
initSearch . setStepsTaken ( searchSteps ) ; if ( searchSteps >= maxSteps ) { // The maximum number of steps has been reached , however if the queue is now empty then the search
// has just completed within the maximum . Check if the queue is empty and return null if so .
if ( queue . isEmpty ( ) ) { return null ; } // Quit without a solution as the max number of steps has been reached but because there are still
// more states in the queue then raise a search failure exception .
else { throw new SearchNotExhaustiveException ( "Maximum number of steps reached." , null ) ; } } } } // No goal state was found so return null
return null ;


signature:
public class WAMEngine { /** * { @ inheritDoc }
 * < p / > Loads the built - in library resource specified by { @ link # BUILT _ IN _ LIB } . */
public void reset ( ) { } }

implementation:
// Reset the resolver to completely clear out its domain .
resolver . reset ( ) ; // Create a token source to load the model rules from .
Source < Token > tokenSource = TokenSource . getTokenSourceForInputStream ( WAMEngine . class . getClassLoader ( ) . getResourceAsStream ( BUILT_IN_LIB ) ) ; // Set up a parser on the token source .
Parser < Clause , Token > libParser = new SentenceParser ( interner ) ; libParser . setTokenSource ( tokenSource ) ; // Load the built - ins into the domain .
try { while ( true ) { Sentence < Clause > sentence = libParser . parse ( ) ; if ( sentence == null ) { break ; } compiler . compile ( sentence ) ; } compiler . endScope ( ) ; } catch ( SourceCodeException e ) { // There should not be any errors in the built in library , if there are then the prolog engine just
// isn ' t going to work , so report this as a bug .
throw new IllegalStateException ( "Got an exception whilst loading the built-in library." , e ) ; }


signature:
public class PrologParser { /** * Parses statements and print the parse tree to the console for quick interactive testing of the parser .
 * @ param args The command line arguments . */
public static void main ( String [ ] args ) { } }

implementation:
try { SimpleCharStream inputStream = new SimpleCharStream ( System . in , null , 1 , 1 ) ; PrologParserTokenManager tokenManager = new PrologParserTokenManager ( inputStream ) ; Source < Token > tokenSource = new TokenSource ( tokenManager ) ; PrologParser parser = new PrologParser ( tokenSource , new VariableAndFunctorInternerImpl ( "Prolog_Variable_Namespace" , "Prolog_Functor_Namespace" ) ) ; while ( true ) { // Parse the next sentence or directive .
Object nextParsing = parser . clause ( ) ; console . info ( nextParsing . toString ( ) ) ; } } catch ( Exception e ) { console . log ( Level . SEVERE , e . getMessage ( ) , e ) ; System . exit ( 1 ) ; }


signature:
public class PrologParser { /** * Parses many consecutive sentences , until an < EOF > is reached . This method is intended to aid with consulting
 * files .
 * @ return A list of parsed clauses .
 * @ throws SourceCodeException If the token sequence does not parse into a sequence of clauses terminted by < EOF > . */
public List < Clause > sentences ( ) throws SourceCodeException { } }

implementation:
List < Clause > results = new LinkedList < Clause > ( ) ; // Loop consuming clauses until end of file is encounterd .
while ( true ) { if ( peekAndConsumeEof ( ) ) { break ; } else { results . add ( sentence ( ) ) ; } } return results ;


signature:
public class PrologParser { /** * Parses a single sentence in first order logic . A sentence consists of a term followed by a full stop .
 * @ return A sentence in first order logic .
 * @ throws SourceCodeException If the token sequence does not parse into a valid sentence . */
public Clause clause ( ) throws SourceCodeException { } }

implementation:
// Each new sentence provides a new scope in which to make variables unique .
variableContext . clear ( ) ; Term term = term ( ) ; Clause clause = TermUtils . convertToClause ( term , interner ) ; if ( clause == null ) { throw new SourceCodeException ( "Only queries and clauses are valid sentences in Prolog, not " + term + "." , null , null , null , term . getSourceCodePosition ( ) ) ; } return clause ;


signature:
public class PrologParser { /** * Parses multiple sequential terms , and if more than one is encountered then the flat list of terms encountered
 * must contain operators in order to be valid Prolog syntax . In that case the flat list of terms is passed to the
 * { @ link DynamicOperatorParser # parseOperators ( Term [ ] ) } method for ' deferred decision parsing ' of dynamic operators .
 * @ return A single first order logic term .
 * @ throws SourceCodeException If the sequence of tokens does not form a valid syntactical construction as a first
 * order logic term . */
public Term term ( ) throws SourceCodeException { } }

implementation:
List < Term > terms ; terms = terms ( new LinkedList < Term > ( ) ) ; Term [ ] flatTerms = terms . toArray ( new Term [ terms . size ( ) ] ) ; if ( flatTerms . length > 1 ) { return operatorParser . parseOperators ( flatTerms ) ; } else { Term result = flatTerms [ 0 ] ; // If a single candidate op symbol has been parsed , promote it to a constant .
if ( result instanceof CandidateOpSymbol ) { CandidateOpSymbol candidate = ( CandidateOpSymbol ) result ; int nameId = interner . internFunctorName ( candidate . getTextName ( ) , 0 ) ; result = new Functor ( nameId , null ) ; } return result ; }


signature:
public class PrologParser { /** * Recursively parses terms , which may be functors , atoms , variables , literals or operators , into a flat list in the
 * order in which they are encountered .
 * @ param terms A list of terms to accumulate in .
 * @ return The list of terms encountered in order .
 * @ throws SourceCodeException If the sequence of tokens does not form a valid syntactical construction as a list of
 * first order logic terms . */
public List < Term > terms ( List < Term > terms ) throws SourceCodeException { } }

implementation:
Term term ; Token nextToken = tokenSource . peek ( ) ; switch ( nextToken . kind ) { case FUNCTOR : term = functor ( ) ; break ; case LSQPAREN : term = listFunctor ( ) ; break ; case VAR : term = variable ( ) ; break ; case INTEGER_LITERAL : term = intLiteral ( ) ; break ; case FLOATING_POINT_LITERAL : term = doubleLiteral ( ) ; break ; case STRING_LITERAL : term = stringLiteral ( ) ; break ; case ATOM : term = atom ( ) ; break ; case LPAREN : consumeToken ( LPAREN ) ; term = term ( ) ; // Mark the term as bracketed to ensure that this is its final parsed form . In particular the
// # arglist method will not break it up if it contains commas .
term . setBracketed ( true ) ; consumeToken ( RPAREN ) ; break ; default : throw new SourceCodeException ( "Was expecting one of " + BEGIN_TERM_TOKENS + " but got " + tokenImage [ nextToken . kind ] + "." , null , null , null , new SourceCodePositionImpl ( nextToken . beginLine , nextToken . beginColumn , nextToken . endLine , nextToken . endColumn ) ) ; } terms . add ( term ) ; switch ( tokenSource . peek ( ) . kind ) { case LPAREN : case LSQPAREN : case INTEGER_LITERAL : case FLOATING_POINT_LITERAL : case STRING_LITERAL : case VAR : case FUNCTOR : case ATOM : terms ( terms ) ; break ; default : } return terms ;


signature:
public class PrologParser { /** * Parses a single atom in first order logic . If the operator has been set up which has the same name as the atom
 * then the atom may actually be a functor expressed as a prefix , postfix or infix operator . If this is the case the
 * value returned by this method will be a { @ link CandidateOpSymbol } . Otherwise it will be a { @ link Functor } of
 * arity zero .
 * @ return A { @ link CandidateOpSymbol } or a { @ link Functor } or arity zero .
 * @ throws SourceCodeException If the token sequence does not parse as a valid atom . */
public Term atom ( ) throws SourceCodeException { } }

implementation:
Token name = consumeToken ( ATOM ) ; Term result ; // Used to build the possible set of operators that this symbol could be parsed as .
EnumMap < OpSymbol . Fixity , OpSymbol > possibleOperators = operatorTable . getOperatorsMatchingNameByFixity ( name . image ) ; // Check if the symbol mapped onto any candidate operators and if not create a constant for it .
if ( ( possibleOperators == null ) || possibleOperators . isEmpty ( ) ) { int nameId = interner . internFunctorName ( name . image , 0 ) ; result = new Functor ( nameId , null ) ; } else { // Set the possible associativities of the operator on the candidate .
result = new CandidateOpSymbol ( name . image , possibleOperators ) ; } // Set the position that the name was parsed from .
SourceCodePosition position = new SourceCodePositionImpl ( name . beginLine , name . beginColumn , name . endLine , name . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ;


signature:
public class PrologParser { /** * Parses a single functor in first order logic with its arguments .
 * @ return A single functor in first order logic with its arguments .
 * @ throws SourceCodeException If the token sequence does not parse as a valid functor . */
public Term functor ( ) throws SourceCodeException { } }

implementation: Token name = consumeToken ( FUNCTOR ) ; Term [ ] args = arglist ( ) ; consumeToken ( RPAREN ) ; int nameId = interner . internFunctorName ( ( args == null ) ? name . image : name . image . substring ( 0 , name . image . length ( ) - 1 ) , ( args == null ) ? 0 : args . length ) ; Functor result = new Functor ( nameId , args ) ; SourceCodePosition position = new SourceCodePositionImpl ( name . beginLine , name . beginColumn , name . endLine , name . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ;


signature:
public class PrologParser { /** * Parses a list expressed as a sequence of functors in first order logic . The empty list consists of the atom ' nil '
 * and a non - empty list consists of the functor ' cons ' with arguments the head of the list and the remainder of the
 * list .
 * < p / > A list can be empty ' [ ] ' , contains a sequence of terms seperated by commas ' [ a , . . . ] ' , contain a sequence of
 * terms seperated by commas consed onto another term ' [ a , . . . | T ] ' . In the case where a term is consed onto the end ,
 * if the term is itself a list the whole will form a list with a cons nil terminator , otherwise the term will be
 * consed onto the end as the list terminal .
 * @ return A list expressed as a sequence of functors in first order .
 * @ throws SourceCodeException If the token sequence does not parse as a valid list . */
public Term listFunctor ( ) throws SourceCodeException { } }

implementation:
// Get the interned names of the nil and cons functors .
int nilId = interner . internFunctorName ( "nil" , 0 ) ; int consId = interner . internFunctorName ( "cons" , 2 ) ; // A list always starts with a ' [ ' .
Token leftDelim = consumeToken ( LSQPAREN ) ; // Check if the list contains any arguments and parse them if so .
Term [ ] args = null ; Token nextToken = tokenSource . peek ( ) ; switch ( nextToken . kind ) { case LPAREN : case LSQPAREN : case INTEGER_LITERAL : case FLOATING_POINT_LITERAL : case STRING_LITERAL : case VAR : case FUNCTOR : case ATOM : args = arglist ( ) ; break ; default : } // Work out what the terminal element in the list is . It will be ' nil ' unless an explicit cons ' | ' has
// been used to specify a different terminal element . In the case where cons is used explciitly , the
// list prior to the cons must not be empty .
Term accumulator ; if ( tokenSource . peek ( ) . kind == CONS ) { if ( args == null ) { throw new SourceCodeException ( "Was expecting one of " + BEGIN_TERM_TOKENS + " but got " + tokenImage [ nextToken . kind ] + "." , null , null , null , new SourceCodePositionImpl ( nextToken . beginLine , nextToken . beginColumn , nextToken . endLine , nextToken . endColumn ) ) ; } consumeToken ( CONS ) ; accumulator = term ( ) ; } else { accumulator = new Nil ( nilId , null ) ; } // A list is always terminated with a ' ] ' .
Token rightDelim = consumeToken ( RSQPAREN ) ; // Walk down all of the lists arguments joining them together with cons / 2 functors .
if ( args != null ) // ' args ' will contain one or more elements if not null .
{ for ( int i = args . length - 1 ; i >= 0 ; i -- ) { Term previousAccumulator = accumulator ; // accumulator = new Functor ( consId . ordinal ( ) , new Term [ ] { args [ i ] , previousAccumulator } ) ;
accumulator = new Cons ( consId , new Term [ ] { args [ i ] , previousAccumulator } ) ; } } // Set the position that the list was parsed from , as being the region between the ' [ ' and ' ] ' brackets .
SourceCodePosition position = new SourceCodePositionImpl ( leftDelim . beginLine , leftDelim . beginColumn , rightDelim . endLine , rightDelim . endColumn ) ; accumulator . setSourceCodePosition ( position ) ; // The cast must succeed because arglist must return at least one argument , therefore the cons generating
// loop must have been run at least once . If arglist is not called at all because an empty list was
// encountered , then the accumulator will contain the ' nil ' constant which is a functor of arity zero .
return ( Functor ) accumulator ;


signature:
public class PrologParser { /** * Parses a sequence of terms as a comma seperated argument list . The ' , ' operator in prolog can be used as an
 * operator , when it behaves as a functor of arity 2 , or it can be used to separate a sequence of terms that are
 * arguments to a functor or list . The sequence of functors must first be parsed as a term , using the operator
 * precedence of " , " to form the term . This method takes such a term and flattens it back into a list of terms ,
 * breaking it only on a sequence of commas . Terms that have been parsed as a bracketed expression will not be
 * broken up .
 * < p / > For example , ' a , b , c ' is broken into the list { a , b , c } . The example , ' a , ( b , c ) , d ' is broken into the
 * list { a , ( b , c ) , d } and so on .
 * @ return A sequence of terms parsed as a term , then flattened back into a list seperated on commas .
 * @ throws SourceCodeException If the token sequence is not a valid term . */
public Term [ ] arglist ( ) throws SourceCodeException { } }

implementation: Term term = term ( ) ; List < Term > result = TermUtils . flattenTerm ( term , Term . class , "," , interner ) ; return result . toArray ( new Term [ result . size ( ) ] ) ;


signature:
public class PrologParser { /** * Parses a variable in first order logic . Variables are scoped within the current sentence being parsed , so if the
 * variable has been seen previously in the sentence it is returned rather than a new one being created .
 * @ return A variable .
 * @ throws SourceCodeException If the next token in the sequence is not a variable . */
public Term variable ( ) throws SourceCodeException { } }

implementation:
Token name = consumeToken ( VAR ) ; // Intern the variables name .
int nameId = interner . internVariableName ( name . image ) ; // Check if the variable already exists in this scope , or create a new one if it does not .
// If the variable is the unidentified anonymous variable ' _ ' , a fresh one will always be created .
Variable var = null ; if ( ! "_" . equals ( name . image ) ) { var = variableContext . get ( nameId ) ; } if ( var != null ) { return var ; } else { var = new Variable ( nameId , null , name . image . equals ( "_" ) ) ; variableContext . put ( nameId , var ) ; return var ; }


signature:
public class PrologParser { /** * Parses an integer literal .
 * @ return An integer literal .
 * @ throws SourceCodeException If the next token in the sequence is not an integer literal . */
public Term intLiteral ( ) throws SourceCodeException { } }

implementation:
Token valToken = consumeToken ( INTEGER_LITERAL ) ; NumericType result = new IntLiteral ( Integer . parseInt ( valToken . image ) ) ; // Set the position that the literal was parsed from .
SourceCodePosition position = new SourceCodePositionImpl ( valToken . beginLine , valToken . beginColumn , valToken . endLine , valToken . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ;


signature:
public class PrologParser { /** * Parses a real number literal .
 * @ return A real number literal .
 * @ throws SourceCodeException If the next token in the sequence is not a real number literal . */
public Term doubleLiteral ( ) throws SourceCodeException { } }

implementation:
Token valToken = consumeToken ( FLOATING_POINT_LITERAL ) ; NumericType result = new DoubleLiteral ( Double . parseDouble ( valToken . image ) ) ; // Set the position that the literal was parsed from .
SourceCodePosition position = new SourceCodePositionImpl ( valToken . beginLine , valToken . beginColumn , valToken . endLine , valToken . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ;


signature:
public class PrologParser { /** * Parses a string literal .
 * @ return A string literal .
 * @ throws SourceCodeException If the next token in the sequence is not a string literal . */
public Term stringLiteral ( ) throws SourceCodeException { } }

implementation:
Token valToken = consumeToken ( STRING_LITERAL ) ; String valWithQuotes = valToken . image ; StringLiteral result = new StringLiteral ( valWithQuotes . substring ( 1 , valWithQuotes . length ( ) - 1 ) ) ; // Set the position that the literal was parsed from .
SourceCodePosition position = new SourceCodePositionImpl ( valToken . beginLine , valToken . beginColumn , valToken . endLine , valToken . endColumn ) ; result . setSourceCodePosition ( position ) ; return result ;


signature:
public class PrologParser { /** * Peeks at the next token to see if it is an { @ link # ATOM } which is equal to " ; " and if it is consumes it . If the
 * symbol is consumed then the return value indicates that this has happened . This is intended to be usefull for
 * interactive interpreters when querying the user to see if they want more solutions to be found .
 * @ return < tt > true < / tt > if the next token is " ; " and it is consumed . */
public boolean peekAndConsumeMore ( ) { } }

implementation:
Token nextToken = tokenSource . peek ( ) ; if ( ( nextToken . kind == ATOM ) && ";" . equals ( nextToken . image ) ) { try { consumeToken ( ATOM ) ; } catch ( SourceCodeException e ) { // If the peek ahead kind can not be consumed then something strange has gone wrong so report this
// as a bug rather than try to recover from it .
throw new IllegalStateException ( e ) ; } return true ; } else { return false ; }


signature:
public class PrologParser { /** * Peeks and consumes the next interactive system directive .
 * @ return The directive , or < tt > null < / tt > if none is found .
 * @ throws SourceCodeException If the source being parsed does not match the grammar . */
public Directive peekAndConsumeDirective ( ) throws SourceCodeException { } }

implementation: if ( peekAndConsumeTrace ( ) ) { return Directive . Trace ; } if ( peekAndConsumeInfo ( ) ) { return Directive . Info ; } if ( peekAndConsumeUser ( ) ) { return Directive . User ; } return null ;


signature:
public class PrologParser { /** * Interns an operators name as a functor of appropriate arity for the operators fixity , and sets the operator in
 * the operator table .
 * @ param operatorName The name of the operator to create .
 * @ param priority The priority of the operator , zero unsets it .
 * @ param associativity The operators associativity . */
public void internOperator ( String operatorName , int priority , OpSymbol . Associativity associativity ) { } }

implementation: int arity ; if ( ( associativity == XFY ) | ( associativity == YFX ) | ( associativity == XFX ) ) { arity = 2 ; } else { arity = 1 ; } int name = interner . internFunctorName ( operatorName , arity ) ; operatorTable . setOperator ( name , operatorName , priority , associativity ) ;


signature:
public class PrologParser { /** * Interns and inserts into the operator table all of the built in operators and functors in Prolog . */
protected void initializeBuiltIns ( ) { } }

implementation:
// Initializes the operator table with the standard ISO prolog built - in operators .
internOperator ( ":-" , 1200 , XFX ) ; internOperator ( ":-" , 1200 , FX ) ; internOperator ( "-->" , 1200 , XFX ) ; internOperator ( "?-" , 1200 , FX ) ; internOperator ( ";" , 1100 , XFY ) ; internOperator ( "->" , 1050 , XFY ) ; internOperator ( "," , 1000 , XFY ) ; internOperator ( "\\+" , 900 , FY ) ; internOperator ( "=" , 700 , XFX ) ; internOperator ( "\\=" , 700 , XFX ) ; internOperator ( "==" , 700 , XFX ) ; internOperator ( "\\==" , 700 , XFX ) ; internOperator ( "@<" , 700 , XFX ) ; internOperator ( "@=<" , 700 , XFX ) ; internOperator ( "@>" , 700 , XFX ) ; internOperator ( "@>=" , 700 , XFX ) ; internOperator ( "=.." , 700 , XFX ) ; internOperator ( "is" , 700 , XFX ) ; internOperator ( "=:=" , 700 , XFX ) ; internOperator ( "=\\=" , 700 , XFX ) ; internOperator ( "<" , 700 , XFX ) ; internOperator ( "=<" , 700 , XFX ) ; internOperator ( ">" , 700 , XFX ) ; internOperator ( ">=" , 700 , XFX ) ; internOperator ( "+" , 500 , YFX ) ; internOperator ( "-" , 500 , YFX ) ; internOperator ( "\\/" , 500 , YFX ) ; internOperator ( "/\\" , 500 , YFX ) ; internOperator ( "/" , 400 , YFX ) ; internOperator ( "//" , 400 , YFX ) ; internOperator ( "*" , 400 , YFX ) ; internOperator ( ">>" , 400 , YFX ) ; internOperator ( "<<" , 400 , YFX ) ; internOperator ( "rem" , 400 , YFX ) ; internOperator ( "mod" , 400 , YFX ) ; internOperator ( "-" , 200 , FY ) ; internOperator ( "^" , 200 , YFX ) ; internOperator ( "**" , 200 , YFX ) ; internOperator ( "\\" , 200 , FY ) ; // Intern all built in functors .
interner . internFunctorName ( "nil" , 0 ) ; interner . internFunctorName ( "cons" , 2 ) ; interner . internFunctorName ( "true" , 0 ) ; interner . internFunctorName ( "fail" , 0 ) ; interner . internFunctorName ( "!" , 0 ) ;


signature:
public class PrologParser { /** * Consumes a token of the expected kind from the token sequence . If the next token in the sequence is not of the
 * expected kind an error will be raised .
 * @ param kind The kind of token to consume .
 * @ return The consumed token of the expected kind .
 * @ throws SourceCodeException If the next token in the sequence is not of the expected kind . */
protected Token consumeToken ( int kind ) throws SourceCodeException { } }

implementation: Token nextToken = tokenSource . peek ( ) ; if ( nextToken . kind != kind ) { throw new SourceCodeException ( "Was expecting " + tokenImage [ kind ] + " but got " + tokenImage [ nextToken . kind ] + "." , null , null , null , new SourceCodePositionImpl ( nextToken . beginLine , nextToken . beginColumn , nextToken . endLine , nextToken . endColumn ) ) ; } else { nextToken = tokenSource . poll ( ) ; return nextToken ; }


signature:
public class PrologParser { /** * Peeks ahead for the given token type , and if one is foudn with that type , it is consumed .
 * @ param kind The token kind to look for .
 * @ return < tt > true < / tt > iff the token was found and consumed . */
private boolean peekAndConsume ( int kind ) { } }

implementation:
Token nextToken = tokenSource . peek ( ) ; if ( nextToken . kind == kind ) { try { consumeToken ( kind ) ; } catch ( SourceCodeException e ) { // If the peek ahead kind can not be consumed then something strange has gone wrong so report this
// as a bug rather than try to recover from it .
throw new IllegalStateException ( e ) ; } return true ; } else { return false ; }


signature:
public class TxSessionImpl { /** * Binds the session as a transactional context to the current thread , if it is not already bound . */
public void bind ( ) { } }

implementation:
// If necessary create a fresh transaction id .
if ( ( txId == null ) || ! txId . isValid ( ) ) { txId = TxManager . createTxId ( ) ; } // Bind the transaction to the current thread .
TxManager . assignTxIdToThread ( txId ) ; // Bind this session to the current thread .
threadSession . set ( this ) ;


signature:
public class TxSessionImpl { /** * Forgets pending operations . */
public void rollback ( ) { } }

implementation:
// Rollback all soft resources .
for ( Transactional enlist : enlists ) { enlist . rollback ( ) ; } // Clear all of the rolled back resources .
enlists . clear ( ) ; // Invalidate the transaction id , so that a fresh transaction is begun .
txId = TxManager . removeTxIdFromThread ( ) ; TxManager . invalidateTxId ( txId ) ; bind ( ) ;


signature:
public class Filterators { /** * Extracts all elements from an iterator , usually created from a filterator , and adds them into the target
 * collection , returning that collection as the result .
 * @ param < T > The type of the iterator and collection to add to .
 * @ param iterator The iterator to extract from .
 * @ param targetCollection The collection to add to .
 * @ return The collection added to . */
public static < T > Collection < T > collectIterator ( Iterator < T > iterator , Collection < T > targetCollection ) { } }

implementation: while ( iterator . hasNext ( ) ) { targetCollection . add ( iterator . next ( ) ) ; } return targetCollection ;