signature:
public class SwingComponentFactory { /** * { @ inheritDoc } */
public JComponent createBlankPanel ( ) { } }

implementation: JPanel vbar = new JPanel ( ) ; vbar . setBackground ( colorScheme . getBackground ( ) ) ; vbar . setForeground ( colorScheme . getDisabledText ( ) ) ; return vbar ;


signature:
public class TimeRangeType { /** * Creates a new time range type with the specified name , if it does not already exist .
 * @ param name The name of the time range type to create .
 * @ param min The minimum value that an instance of the type can take .
 * @ param max The maximum value that an instance of teh type can take .
 * @ return A new time range type .
 * @ throws IllegalArgumentException If min is not less than or equal to max , or the named type already exists . */
public static Type createInstance ( String name , TimeOnly min , TimeOnly max ) { } }

implementation:
// Ensure that min is less than or equal to max .
if ( ( min != null ) && ( max != null ) && ( min . compareTo ( max ) > 0 ) ) { throw new IllegalArgumentException ( "'min' must be less than or equal to 'max'." ) ; } synchronized ( INT_RANGE_TYPES ) { // Add the newly created type to the map of all types .
TimeRangeType newType = new TimeRangeType ( name , min , max ) ; // Ensure that the named type does not already exist , unless it has an identical definition already , in which
// case the old definition can be re - used and the new one discarded .
TimeRangeType oldType = INT_RANGE_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( "The type '" + name + "' already exists and cannot be redefined." ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { INT_RANGE_TYPES . put ( name , newType ) ; return newType ; } }


signature:
public class TimeRangeType { /** * { @ inheritDoc }
 * < p / > A random value of this type lies between ' min ' and ' max ' . */
public TimeOnly createRandomInstance ( ) { } }

implementation: int start = minValue . getMilliseconds ( ) ; int end = maxValue . getMilliseconds ( ) ; return new TimeOnly ( ( long ) ( start + random . nextInt ( end - start ) ) ) ;


signature:
public class TimeRangeType { /** * { @ inheritDoc } */
public void acceptVisitor ( TypeVisitor visitor ) { } }

implementation: if ( visitor instanceof TimeRangeTypeVisitor ) { ( ( TimeRangeTypeVisitor ) visitor ) . visit ( this ) ; } else { super . acceptVisitor ( visitor ) ; }


signature:
public class StringPatternType { /** * Creates a new string pattern type with the specified name , if it does not already exist .
 * @ param name The name of the string pattern type to create .
 * @ param maxLength The maximum length of instances of the type , may be zero or less for no maximum .
 * @ param pattern A regular expression that instances must match , or < tt > null < / tt > for no pattern .
 * @ return A new string pattern type .
 * @ throws IllegalArgumentException If min is not less than or equal to max , or the named type already exists . */
public static Type createInstance ( String name , int maxLength , String pattern ) { } }

implementation:
synchronized ( STRING_PATTERN_TYPES ) { StringPatternType newType = new StringPatternType ( name , maxLength , pattern ) ; // Ensure that the named type does not already exist .
StringPatternType oldType = STRING_PATTERN_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( "The type '" + name + "' already exists and cannot be redefined." ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { // Add the newly created type to the map of all types .
STRING_PATTERN_TYPES . put ( name , newType ) ; return newType ; } }


signature:
public class StringPatternType { /** * Checks a string value against this type to see if it is a valid instance of the type .
 * @ param value The value to type check .
 * @ return < tt > true < / tt > if the string is a valid instance of this type . */
public boolean isInstance ( CharSequence value ) { } }

implementation:
// Check the value is under the maximum if one is set .
// Check the value matches the pattern if one is set .
return ( ( maxLength <= 0 ) || ( value . length ( ) <= maxLength ) ) && compiledPattern . matcher ( value ) . matches ( ) ;


signature:
public class PositionalTermTraverserImpl { /** * { @ inheritDoc } */
public boolean isTopLevel ( ) { } }

implementation: PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) && position . isTopLevel ( ) ;


signature:
public class PositionalTermTraverserImpl { /** * { @ inheritDoc } */
public boolean isInHead ( ) { } }

implementation: PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) && position . isInHead ( ) ;


signature:
public class PositionalTermTraverserImpl { /** * { @ inheritDoc } */
public boolean isLastBodyFunctor ( ) { } }

implementation: PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) && position . isLastBodyFunctor ( ) ;


signature:
public class PositionalTermTraverserImpl { /** * { @ inheritDoc } */
public Term getTerm ( ) { } }

implementation: PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) ? position . getTerm ( ) : null ;


signature:
public class PositionalTermTraverserImpl { /** * { @ inheritDoc } */
public int getPosition ( ) { } }

implementation: PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) ? position . getPosition ( ) : - 1 ;


signature:
public class PositionalTermTraverserImpl { /** * { @ inheritDoc } */
public PositionalContext getParentContext ( ) { } }

implementation: PositionalTermTraverserImpl . PositionalContextOperator position = contextStack . peek ( ) ; return ( position != null ) ? position . getParentContext ( ) : null ;


signature:
public class PositionalTermTraverserImpl { /** * { @ inheritDoc } */
protected StackableOperator createHeadOperator ( Functor head , Clause clause ) { } }

implementation: return new PositionalContextOperator ( head , - 1 , true , true , false , null , contextStack . peek ( ) ) ;


signature:
public class PositionalTermTraverserImpl { /** * { @ inheritDoc } */
protected StackableOperator createBodyOperator ( Functor bodyFunctor , int pos , Functor [ ] body , Clause clause ) { } }

implementation: return new PositionalContextOperator ( bodyFunctor , pos , true , false , pos == ( body . length - 1 ) , null , contextStack . peek ( ) ) ;


signature:
public class PositionalTermTraverserImpl { /** * { @ inheritDoc } */
protected StackableOperator createTermOperator ( Term argument , int pos , Functor functor ) { } }

implementation: return new PositionalContextOperator ( argument , pos , false , null , false , null , contextStack . peek ( ) ) ;


signature:
public class PositionalTermTraverserImpl { /** * { @ inheritDoc } */
protected StackableOperator createClauseOperator ( Clause bodyClause , int pos , Clause [ ] body , Predicate predicate ) { } }

implementation: return new PositionalContextOperator ( bodyClause , pos , false , false , false , null , contextStack . peek ( ) ) ;


signature:
public class PositionalTermTraverserImpl { /** * Sets up the initial context once , at the start of a traversal .
 * @ param term The term to establish the initial positional traversal context for . */
private void createInitialContext ( Term term ) { } }

implementation: if ( ! initialContextCreated ) { PositionalContextOperator initialContext = new PositionalContextOperator ( term , - 1 , false , false , false , null , contextStack . peek ( ) ) ; contextStack . offer ( initialContext ) ; term . setReversable ( initialContext ) ; initialContextCreated = true ; }


signature:
public class InternalMemoryLayoutBean { /** * Updates the layout register file , with a new set of layout registers .
 * @ param layout The new layout register values . */
public void updateRegisters ( WAMMemoryLayout layout ) { } }

implementation: List < PropertyChangeEvent > changes = delta ( this , layout ) ; regBase = layout . regBase ; regSize = layout . regSize ; heapBase = layout . heapBase ; heapSize = layout . heapSize ; stackBase = layout . stackBase ; stackSize = layout . stackSize ; trailBase = layout . trailBase ; trailSize = layout . trailSize ; pdlBase = layout . pdlBase ; pdlSize = layout . pdlSize ; notifyChanges ( changes ) ;


signature:
public class InternalMemoryLayoutBean { /** * Compares the current register file , with a new set , and creates a list property change notifications for any that
 * have changed value .
 * @ param newRegisters The new register values . */
private List < PropertyChangeEvent > delta ( WAMMemoryLayout oldRegisters , WAMMemoryLayout newRegisters ) { } }

implementation: List < PropertyChangeEvent > result = new LinkedList < PropertyChangeEvent > ( ) ; if ( oldRegisters . regBase != newRegisters . regBase ) { result . add ( new PropertyChangeEvent ( this , "regBase" , oldRegisters . regBase , newRegisters . regBase ) ) ; } if ( oldRegisters . regSize != newRegisters . regSize ) { result . add ( new PropertyChangeEvent ( this , "regSize" , oldRegisters . regSize , newRegisters . regSize ) ) ; } if ( oldRegisters . heapBase != newRegisters . heapBase ) { result . add ( new PropertyChangeEvent ( this , "heapBase" , oldRegisters . heapBase , newRegisters . heapBase ) ) ; } if ( oldRegisters . heapSize != newRegisters . heapSize ) { result . add ( new PropertyChangeEvent ( this , "heapSize" , oldRegisters . heapSize , newRegisters . heapSize ) ) ; } if ( oldRegisters . stackBase != newRegisters . stackBase ) { result . add ( new PropertyChangeEvent ( this , "stackBase" , oldRegisters . stackBase , newRegisters . stackBase ) ) ; } if ( oldRegisters . stackSize != newRegisters . stackSize ) { result . add ( new PropertyChangeEvent ( this , "stackSize" , oldRegisters . stackSize , newRegisters . stackSize ) ) ; } if ( oldRegisters . trailBase != newRegisters . trailBase ) { result . add ( new PropertyChangeEvent ( this , "trailBase" , oldRegisters . trailBase , newRegisters . trailBase ) ) ; } if ( oldRegisters . trailSize != newRegisters . trailSize ) { result . add ( new PropertyChangeEvent ( this , "trailSize" , oldRegisters . trailSize , newRegisters . trailSize ) ) ; } if ( oldRegisters . pdlBase != newRegisters . pdlBase ) { result . add ( new PropertyChangeEvent ( this , "pdlBase" , oldRegisters . pdlBase , newRegisters . pdlBase ) ) ; } if ( oldRegisters . pdlSize != newRegisters . pdlSize ) { result . add ( new PropertyChangeEvent ( this , "pdlSize" , oldRegisters . pdlSize , newRegisters . pdlSize ) ) ; } return result ;


signature:
public class VariableReferenceNode { /** * Search up the scope tree to locate the variable ' s value . The parser has already verified that
 * the variable is defined . */
public String getValue ( ) { } }

implementation: for ( ScopeNode scope = NodeTreeUtils . getParentScope ( this ) ; scope != null ; scope = NodeTreeUtils . getParentScope ( scope ) ) { ExpressionGroupNode value = scope . getVariable ( _name ) ; if ( value == null ) { continue ; } return value . toString ( ) ; } return _name ; // Unable to find the variable ' s value , return the name for now ( helpful for debugging )


signature:
public class BaseBiDirectionalQueueSearch { /** * Implementation of the general bi - dircetional search . The search alternated between taking a forward and a reverse
 * step .
 * @ 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 If the search stops before finding a solution or exhausting the search
 * space . Different search algorithms may fail for different reasons but in
 * particular it it is worth noting that if the maximum number of steps is
 * reached without exhausting the search space this will cause an exception to
 * be thrown rather than for this method to return null . */
public SearchNode < O , T > findGoalPath ( ) throws SearchNotExhaustiveException { } }

implementation:
// Keep running until the queue becomes empty or a goal state is found
while ( ! forwardQueue . isEmpty ( ) || ! reverseQueue . isEmpty ( ) ) { // Only run the forward step of the search if the forward queue is not empty
if ( ! forwardQueue . isEmpty ( ) ) { // Extract the next node from the forward queue
SearchNode < O , T > currentForwardNode = forwardQueue . remove ( ) ; // Remove this node from the forward fringe map as it will soon be replaced by more fringe members
forwardFringe . remove ( currentForwardNode . getState ( ) ) ; // Check the reverse fringe against the next forward node for a match .
if ( reverseFringe . containsKey ( currentForwardNode . getState ( ) ) ) { // A path from start to the goal has been found . Walk backwards along the reverse path adding all
// nodes encountered to the forward path until the goal is reached .
return joinBothPaths ( currentForwardNode , reverseFringe . get ( currentForwardNode . getState ( ) ) ) ; } // There was no match so a path to the goal has not been found
else { // Get all of the successor states to the current node
Queue < SearchNode < O , T > > newStates = new LinkedList < SearchNode < O , T > > ( ) ; currentForwardNode . expandSuccessors ( newStates , false ) ; // Expand all the successors to the current forward node into the buffer to be searched .
forwardQueue . addAll ( newStates ) ; // Also add all the successors to the current forward fringe map .
for ( SearchNode < O , T > nextSearchNode : newStates ) { forwardFringe . put ( nextSearchNode . getState ( ) , nextSearchNode ) ; } } } // Only run the reverse step of the search if the reverse queue is not empty
if ( ! reverseQueue . isEmpty ( ) ) { // Extract the next node from the reverse queue
SearchNode < O , T > currentReverseNode = reverseQueue . remove ( ) ; // Remove this node from the reverse fringe set as it will soon be replaced by more fringe members
reverseFringe . remove ( currentReverseNode . getState ( ) ) ; // Check the forward fringe against the next reverse node for a match .
if ( forwardFringe . containsKey ( currentReverseNode . getState ( ) ) ) { // A path from start to goal has been found .
// Walk backwards along the reverse path adding all nodes encountered to the foward path until the
// goal is reached .
return joinBothPaths ( forwardFringe . get ( currentReverseNode . getState ( ) ) , currentReverseNode ) ; } // There was no match so a path to the goal has not been found
else { // Get all of the successor states to the current node ( really predecessor state )
Queue < SearchNode < O , T > > newStates = new LinkedList < SearchNode < O , T > > ( ) ; currentReverseNode . expandSuccessors ( newStates , false ) ; // Expand all the successors to the current reverse node into the reverse buffer to be searched .
reverseQueue . addAll ( newStates ) ; // Add all the successors to the current reverse fringe set
for ( SearchNode < O , T > nextSearchNode : newStates ) { reverseFringe . put ( nextSearchNode . getState ( ) , nextSearchNode ) ; } } } } // No goal state was found so return null
return null ;


signature:
public class BaseBiDirectionalQueueSearch { /** * Once a match has been found between the forward and reverse fringes of the search a path is known to exist from
 * the start to the goal . The path is not complete at this stage because it remains to reverse all of the steps in
 * the backward half of the path and add them to the forward half of the path to produce the complete forward path
 * from start to the goal .
 * < p > This method implements a standard algorithm for doing this . It assumes that the state space being searched by
 * both halfs of the search is over the same states . It also assumes that the applied operations in the reverse
 * search node have already been reverse . For example , if the search space was the eight tiles game then the moves
 * stored in the reverse half of the search would have to be stored in the reverse direction to that in which they
 * are applied when really playing the game backwards . This means that two implementations of
 * { @ link com . thesett . aima . search . TraversableState } are needed , one that gives its operators reversed .
 * < p > It is possible to supply an alternative path joining algorithm that does know how to reverse the operators .
 * Set this in this search algorithm by calling the { @ link # setPathJoinAlgorithm } method . This is an alternative to
 * writing two implementatios of { @ link com . thesett . aima . search . TraversableState }
 * @ param forwardPath a search node for the forward portion of the goal path
 * @ param reversePath a search node for the reverse portion of the goal path
 * @ return a search node corresponding to the path right from start to goal
 * @ throws SearchNotExhaustiveException If the node implementation does not allow new nodes to be created from old .
 * See the { @ link SearchNode # makeNode } method for more information . */
private SearchNode < O , T > joinBothPaths ( SearchNode < O , T > forwardPath , SearchNode < O , T > reversePath ) throws SearchNotExhaustiveException { } }

implementation:
// Check if an alternative path join algorithm has been set and delegate to it if so
if ( pathJoiner != null ) { return pathJoiner . joinBothPaths ( forwardPath , reversePath ) ; } // No alternative path join algorithm has been supplied so use this default one
else { // Used to hold the current position along the reverse path of search nodes
SearchNode < O , T > currentReverseNode = reversePath ; // Used to hold the current position along the forward path of search nodes
SearchNode < O , T > currentForwardNode = forwardPath ; // Loop over all nodes in the reverse path checking if the current reverse node is the
// goal state to terminate on .
while ( ! goalPredicate . evaluate ( currentReverseNode . getState ( ) ) ) { // Create a new forward node from the parent state of the current reverse node , the current reverse
// nodes applied operation and cost , and an increment of one to the path depth
SearchNode < O , T > reverseParentNode = currentReverseNode . getParent ( ) ; T state = currentReverseNode . getParent ( ) . getState ( ) ; Operator < O > operation = currentReverseNode . getAppliedOp ( ) ; float cost = currentReverseNode . getPathCost ( ) - reverseParentNode . getPathCost ( ) ; currentForwardNode = currentForwardNode . makeNode ( new Successor < O > ( state , operation , cost ) ) ; // Move one step up the reverse path
currentReverseNode = reverseParentNode ; } // Return the last forward search node found
return currentForwardNode ; }


signature:
public class StackVariableTransform { /** * { @ inheritDoc }
 * < p / > Replaces all of the free variables in the clause with stack variables . */
public Variable transform ( Variable variable ) { } }

implementation:
StackVariable stackVar = varMapping . get ( variable ) ; // Check if a stack variable for the variable has not been created yet , and if so create a new stack variable ,
// setting the clause that it is in as its binding context supplier .
if ( stackVar == null ) { stackVar = new StackVariable ( variable . getName ( ) , null , variable . isAnonymous ( ) , offset ++ , context ) ; varMapping . put ( variable , stackVar ) ; } return stackVar ;


signature:
public class LazyPagingList { /** * Gets the element from the list at the specified index . If the indexes block is not currently cached then a call
 * is made to the { @ link # getBlock } method to fetch it .
 * @ param index The offset into the list to retrieve .
 * @ return The element at the specified index . */
public T get ( int index ) { } }

implementation:
/* log . fine ( " public T get ( int index ) : called " ) ; */
/* log . fine ( " index = " + index ) ; */
// Turn the absolute index into a block and offset .
int block = index / blockSize ; int offset = index % blockSize ; /* log . fine ( " block = " + block ) ; */
/* log . fine ( " offset = " + offset ) ; */
// Check if the desired block is already cached .
List < T > blockList = blockMap . get ( block ) ; // Fetch the block if it is not already cached and cache it .
if ( blockList == null ) { blockList = cacheBlock ( block ) ; } // Get the element from the offset within the cached block .
return blockList . get ( offset ) ;


signature:
public class LazyPagingList { /** * Fetches and caches the specified block .
 * @ param block The block to cache .
 * @ return The contents of the cached block . */
public List < T > cacheBlock ( int block ) { } }

implementation:
/* log . fine ( " public List < T > cacheBlock ( int block ) : called " ) ; */
// Get the new block .
List < T > blockList = getBlock ( block * blockSize , blockSize ) ; // Cache it .
blockMap . put ( block , blockList ) ; /* log . fine ( " Cached block " + block + " with list of size " + blockList . size ( ) ) ; */
return blockList ;


signature:
public class DefaultPropertyReader { /** * Static factory method that locates an existing instance or creates a new property reader for a named resource .
 * @ param resourceName The name of the property file resource .
 * @ return The properties found under that resource name . */
public static synchronized Properties getProperties ( String resourceName ) { } }

implementation:
/* log . fine ( " public static synchronized Properties getProperties ( String resourceName ) : called " ) ; */
/* log . fine ( " resourceName = " + resourceName ) ; */
// Try to find an already created singleton property reader for the resource
PropertyReaderBase propertyReader = ( PropertyReaderBase ) propertyReaders . get ( resourceName ) ; if ( propertyReader != null ) { /* log . fine ( " found property reader in the cache for resource : " + resourceName ) ; */
return propertyReader . getProperties ( ) ; } /* log . fine ( " did not find property reader in the cache for resource : " + resourceName ) ; */
// There is not already a singleton for the named resource so create a new one
propertyReader = new DefaultPropertyReader ( resourceName ) ; // Keep the newly created singleton for next time
propertyReaders . put ( resourceName , propertyReader ) ; return propertyReader . getProperties ( ) ;


signature:
public class BatchedThrottle { /** * Specifies the throttling rate in operations per second .
 * @ param hertz The throttling rate in cycles per second . */
public void setRate ( float hertz ) { } }

implementation:
// Pass the rate unaltered down to the base implementation , for the check method .
super . setRate ( hertz ) ; // Log base 10 over 2 is used here to get a feel for what power of 100 the total rate is .
// As the total rate goes up the powers of 100 the batch size goes up by powers of 100 to keep the
// throttle rate in the range 1 to 100.
int x = ( int ) ( Math . log10 ( hertz ) / 2 ) ; batchSize = ( int ) Math . pow ( 100 , x ) ; float throttleRate = hertz / batchSize ; // Reset the call count .
callCount = 0 ; // Set the sleep throttle wrapped implementation at a rate within its abilities .
batchRateThrottle . setRate ( throttleRate ) ;


signature:
public class ClientInputStream { /** * Reads some number of bytes from the input stream and stores them into the buffer array b .
 * @ param b The buffer into which the data is read .
 * @ return The total number of bytes read into the buffer , or - 1 is there is no more data because the end of the
 * stream has been reached .
 * @ throws IOException If an I / O error occurs when accessing the stream or a remote exception occurs . */
public int read ( byte [ ] b ) throws IOException { } }

implementation: try { ByteBlock block = source . read ( b ) ; System . arraycopy ( block . data , 0 , b , 0 , block . count ) ; return block . count ; } catch ( RemoteException e ) { throw new IOException ( "There was a Remote Exception." , e ) ; }


signature:
public class ClientInputStream { /** * Reads up to len bytes of data from the input stream into an array of bytes .
 * @ param b The buffer into which the data is read .
 * @ param off The start offset in array b at which the data is written .
 * @ param len The maximum number of bytes to read .
 * @ return The total number of bytes read into the buffer , or - 1 is there is no more data because the end of the
 * stream has been reached .
 * @ throws IOException If an IOException occurs in the wrapped distributed input stream or a remote exception
 * occurs . */
public int read ( byte [ ] b , int off , int len ) throws IOException { } }

implementation: try { ByteBlock block = source . read ( b , off , len ) ; System . arraycopy ( block . data , off , b , off , len ) ; return block . count ; } catch ( RemoteException e ) { throw new IOException ( "There was a Remote Exception." , e ) ; }


signature:
public class ClientInputStream { /** * Skips over and discards n bytes of data from this input stream .
 * @ param n The number of bytes to skip .
 * @ return The actual number of bytes skipped .
 * @ throws IOException If an IOException occurs in the wrapped distributed input stream or a remote exception
 * occurs . */
public long skip ( long n ) throws IOException { } }

implementation: try { return source . skip ( n ) ; } catch ( RemoteException e ) { throw new IOException ( "There was a Remote Exception." , e ) ; }


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

implementation:
SizeableLinkedList < WAMInstruction > result = new SizeableLinkedList < WAMInstruction > ( ) ; SizeableLinkedList < WAMInstruction > instructions ; // Invent some unique names for choice points within a clause .
clauseName = new FunctorName ( clauseName . getName ( ) + "_" + bodyNumber , 0 ) ; FunctorName choicePointRootName = new FunctorName ( clauseName . getName ( ) + "_ilc" , 0 ) ; FunctorName continuationPointName = new FunctorName ( clauseName . getName ( ) + "_cnt" , 0 ) ; // Labels the continuation point to jump to , when a choice point succeeds .
WAMLabel continueLabel = new WAMLabel ( continuationPointName , 0 ) ; // Do a loop over the children of this disjunction , and any child disjunctions encountered . This could be a
// search ? or just recursive exploration . I think it will need to be a DFS .
List < Term > expressions = new ArrayList < Term > ( ) ; gatherDisjunctions ( ( Disjunction ) functor , expressions ) ; for ( int i = 0 ; i < expressions . size ( ) ; i ++ ) { Functor expression = ( Functor ) expressions . get ( i ) ; boolean isFirst = i == 0 ; boolean isLast = i == ( expressions . size ( ) - 1 ) ; // Labels the entry point to each choice point .
WAMLabel entryLabel = new WAMLabel ( choicePointRootName , i ) ; // Label for the entry point to the next choice point , to backtrack to .
WAMLabel retryLabel = new WAMLabel ( choicePointRootName , i + 1 ) ; if ( isFirst && ! isLast ) { // try me else .
result . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TryMeElse , retryLabel ) ) ; } else if ( ! isFirst && ! isLast ) { // retry me else .
result . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . RetryMeElse , retryLabel ) ) ; } else if ( isLast ) { // trust me .
result . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TrustMe ) ) ; } Integer permVarsRemaining = ( Integer ) defaultBuiltIn . getSymbolTable ( ) . get ( expression . getSymbolKey ( ) , SYMKEY_PERM_VARS_REMAINING ) ; // Select a non - default built - in implementation to compile the functor with , if it is a built - in .
BuiltIn builtIn ; if ( expression instanceof BuiltIn ) { builtIn = ( BuiltIn ) expression ; } else { builtIn = defaultBuiltIn ; } // The ' isFirstBody ' parameter is only set to true , when this is the first functor of a rule .
instructions = builtIn . compileBodyArguments ( expression , false , clauseName , i ) ; result . addAll ( instructions ) ; // Call the body . The number of permanent variables remaining is specified for environment trimming .
instructions = builtIn . compileBodyCall ( expression , false , false , false , 0 /* permVarsRemaining */
) ; result . addAll ( instructions ) ; // Proceed if this disjunctive branch completes successfully . This does not need to be done for the last
// branch , as the continuation point will come immediately after .
if ( ! isLast ) { result . add ( new WAMInstruction ( null , WAMInstruction . WAMInstructionSet . Continue , continueLabel ) ) ; } } result . add ( new WAMInstruction ( continueLabel , WAMInstruction . WAMInstructionSet . NoOp ) ) ; return result ;


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

implementation: return new SizeableLinkedList < WAMInstruction > ( ) ;


signature:
public class Disjunction { /** * Gathers the functors to compile as a sequence of choice points . These exist as the arguments to disjunctions
 * recursively below the supplied disjunction . They are flattened into a list , by performing a left - to - right depth
 * first traversal over the disjunctions , and adding their arguments into a list .
 * @ param disjunction The disjunction to explore the arguments of .
 * @ param expressions The flattened list of disjunctive terms . */
private void gatherDisjunctions ( Disjunction disjunction , List < Term > expressions ) { } }

implementation:
// Left argument .
gatherDisjunctionsExploreArgument ( disjunction . getArguments ( ) [ 0 ] , expressions ) ; // Right argument .
gatherDisjunctionsExploreArgument ( disjunction . getArguments ( ) [ 1 ] , expressions ) ;


signature:
public class Disjunction { /** * Explores one argument of a disjunction as part of the { @ link # gatherDisjunctions ( Disjunction , List ) } function .
 * @ param term The argument to explore .
 * @ param expressions The flattened list of disjunctive terms . */
private void gatherDisjunctionsExploreArgument ( Term term , List < Term > expressions ) { } }

implementation: if ( term instanceof Disjunction ) { gatherDisjunctions ( ( Disjunction ) term , expressions ) ; } else { expressions . add ( term ) ; }


signature:
public class BinaryArithmeticComparison { /** * { @ inheritDoc } */
public boolean proofStep ( ResolutionState state ) { } }

implementation:
Functor isOp = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; // Evaluate both sides of the comparison , checking that they are fully instantiated numbers .
NumericType n1 = BuiltInUtils . evaluateAsNumeric ( isOp . getArgument ( 0 ) ) ; NumericType n2 = BuiltInUtils . evaluateAsNumeric ( isOp . getArgument ( 1 ) ) ; // Evaluate the comparison operator .
return evaluate ( n1 , n2 ) ;


signature:
public class WAMCompiledQueryPrintingVisitor { /** * { @ inheritDoc } */
public void visit ( Clause clause ) { } }

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


signature:
public class BucketedPriorityMap { /** * Returns the first ( lowest ) key currently in this priority map .
 * @ return The first ( lowest ) key currently in this priority map , or < tt > null < / tt > if there is no first key . */
public K pollKey ( ) { } }

implementation:
// Scan through the buckets until a non empty one is found .
int i = 0 ; for ( ; i < n ; i ++ ) { if ( ! maps [ i ] . isEmpty ( ) ) { break ; } // If all maps are empty then the whole data structure is emtpy .
if ( i == ( n - 1 ) ) { return null ; } } return maps [ i ] . keySet ( ) . iterator ( ) . next ( ) ;


signature:
public class BucketedPriorityMap { /** * Returns the value of the first ( lowest ) key currently in this priority map .
 * @ return The value of the first ( lowest ) key currently in this priority map .
 * @ throws java . util . NoSuchElementException If there are no keys in the map . This is thrown to distinguish from the
 * case where the first key has a null value . */
public V pollValue ( ) { } }

implementation: K lowestKey = pollKey ( ) ; if ( lowestKey == null ) { return null ; } else { return maps [ p . apply ( lowestKey ) ] . get ( lowestKey ) ; }


signature:
public class ByteBufferUtils { /** * Extracts an int from an array of bytes .
 * @ param buf The array of bytes to extract the int from .
 * @ param offset The offset of the start of the int in the byte array .
 * @ return An integer extracted from the 4 bytes of data . */
public static int getIntFromBytes ( byte [ ] buf , int offset ) { } }

implementation: int result = 0 ; result += buf [ offset ++ ] & 0xFF ; result += ( ( buf [ offset ++ ] & 0xFF ) << 8 ) ; result += ( ( buf [ offset ++ ] & 0xFF ) << 16 ) ; result += ( ( buf [ offset ] ) << 24 ) ; return result ;


signature:
public class ByteBufferUtils { /** * Outputs an int into a byte array .
 * @ param buf The byte array to write to .
 * @ param offset The offset within the byte array to output the int .
 * @ param value The int value to write into the array . */
public static void writeIntToByteArray ( byte [ ] buf , int offset , int value ) { } }


signature:
public class ByteBufferUtils { /** * Outputs an int into a byte array , copying only the bottom 24 bits of the integer . The top , sign bit , is lost by
 * this operation , so this only works on positive ints below 2 ^ 24.
 * @ param buf The byte array to write to .
 * @ param offset The offset within the byte array to output the int .
 * @ param value The int value to write into the array . */
public static void write24BitIntToByteArray ( byte [ ] buf , int offset , int value ) { } }

implementation: buf [ offset ++ ] = ( byte ) ( value & 0x000000ff ) ; buf [ offset ++ ] = ( byte ) ( ( value & 0x0000ff00 ) >> 8 ) ; buf [ offset ] = ( byte ) ( ( value & 0x00ff0000 ) >> 16 ) ;


signature:
public class ByteBufferUtils { /** * Extracts an int from an array of bytes . Only three bytes are pulled together from the array to make a 24 bit
 * integer , albeit returned as a java 32 bit int .
 * @ param buf The array of bytes to extract the int from .
 * @ param offset The offset of the start of the int in the byte array .
 * @ return An integer extracted from the 4 bytes of data . */
public static int get24BitIntFromBytes ( byte [ ] buf , int offset ) { } }

implementation: int i = 0 ; offset ++ ; i += buf [ offset ++ ] & 0xFF ; i += ( ( buf [ offset ++ ] & 0xFF ) << 8 ) ; i += ( ( buf [ offset ] & 0xFF ) << 16 ) ; return i ;


signature:
public class ByteBufferUtils { /** * Extracts a short from an array of bytes .
 * @ param buf The array of bytes to extract the short from .
 * @ param offset The offset of the start of the short in the byte array .
 * @ return A short extracted from the 2 bytes of data . */
public static short getShortFromBytes ( byte [ ] buf , int offset ) { } }

implementation: short result = 0 ; result += buf [ offset ++ ] & 0xFF ; result += ( ( buf [ offset ] ) << 8 ) ; return result ;


signature:
public class ByteBufferUtils { /** * Outputs a short into a byte array .
 * @ param buf The byte array to write to .
 * @ param offset The offset within the byte array to output the short .
 * @ param value The short value to write into the array . */
public static void writeShortToByteArray ( byte [ ] buf , int offset , short value ) { } }

implementation: buf [ offset ++ ] = ( byte ) ( value & 0x000000ff ) ; buf [ offset ] = ( byte ) ( ( value & 0x0000ff00 ) >> 8 ) ;


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

implementation: SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; instructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Execute , new FunctorName ( "__fail__" , 0 ) ) ) ; return instructions ;


signature:
public class IDAStarSearch { /** * Provides an implementation of the { @ link BoundProperty } interface to extract the cost as the bound property .
 * @ param searchNode The search node to extract the bound property for .
 * @ return The f value of the supplied heuristic search node . The bound property to control the iterative deepening
 * algorithm is f . */
public float getBoundProperty ( SearchNode < O , T > searchNode ) { } }

implementation: return ( ( HeuristicSearchNode < O , T > ) searchNode ) . getF ( ) ;


signature:
public class TreeSearchState { /** * Returns the state obtained by applying the specified operation . If the operation is not valid then this should
 * return null .
 * @ param op The operator to apply to the traversable state .
 * @ return The new traversable state generated by applying the specified operator . */
public TreeSearchState < E > getChildStateForOperator ( Operator < Tree < E > > op ) { } }

implementation:
/* log . fine ( " public Traversable getChildStateForOperator ( Operator op ) : called " ) ; */
// Extract the child tree from the operator and create a new tree search state from it .
return new TreeSearchState < E > ( op . getOp ( ) ) ;


signature:
public class TreeSearchState { /** * Gets all operators valid from this state . If the current tree to search has any children these are encoded as
 * operators to access those child trees as tree search states . If the current tree is a leaf then an empty iterator
 * is returned .
 * @ param reverse < tt > true < / tt > if the operators are to be presented in reverse order .
 * @ return An iterator over all the operators that may be applied to this state . */
public Iterator < Operator < Tree < E > > > validOperators ( boolean reverse ) { } }

implementation:
/* log . fine ( " public Iterator < Operator > validOperators ( ) : called " ) ; */
// Check if the tree is a leaf and return an empty iterator if so .
if ( tree . isLeaf ( ) ) { /* log . fine ( " is leaf " ) ; */
return new ArrayList < Operator < Tree < E > > > ( ) . iterator ( ) ; } // Generate an iterator over the child trees of the current node , encapsulating them as operators .
else { /* log . fine ( " is node " ) ; */
Tree . Node < E > node = tree . getAsNode ( ) ; return new TreeSearchOperatorIterator < E > ( node . getChildIterator ( ) ) ; }


signature:
public class IdAttribute { /** * Returns the integer id of the attribute .
 * @ return The integer id of the attribute . */
public long getId ( ) { } }

implementation:
// Check if the attribute class has been finalized yet .
if ( attributeClass . finalized ) { // Fetch the object value from the attribute class array of finalized values .
return attributeClass . lookupValue [ value ] . id ; } // The attribute class has not been finalized yet .
else { // Fetch the object value from the attribute class list of unfinalized values .
return attributeClass . lookupValueList . get ( value ) . id ; }


signature:
public class IdAttribute { /** * Gets the object value of a object attribute .
 * @ return The underlying object value of this attribute . */
public T getValue ( ) { } }

implementation:
// Check if the attribute class has been finalized yet .
if ( attributeClass . finalized ) { // Fetch the object value from the attribute class .
return attributeClass . lookupValue [ value ] . label ; } else { return attributeClass . lookupValueList . get ( value ) . label ; }


signature:
public class IdAttribute { /** * Sets the specified object as the value of this attribute . The value to set must be a legitimate member of this
 * attributes type , when the type has been finalized . If the type has yet to be finalized then the new value is
 * added to the set of possible values for the type .
 * @ param value The new value to set .
 * @ throws IllegalArgumentException If the type has been finalized and the new value is not a member of the type . */
public void setValue ( T value ) throws IllegalArgumentException { } }

implementation:
Integer b = attributeClass . lookupInt . get ( value ) ; // Check if the value is not already a memeber of the attribute class .
if ( b == null ) { // Check if the attribute class has been finalized yet .
if ( attributeClass . finalized ) { throw new IllegalArgumentException ( "The value to set, " + value + ", is not already a member of the finalized IdType, " + attributeClass . attributeClassName + "." ) ; } else { // Add the new value to the attribute class . Delegate to the factory to do this so that strings are
// interned and so on .
IdAttribute newAttribute = attributeClass . createIdAttribute ( value ) ; b = newAttribute . value ; } } // Set the new value as the value of this attribute .
this . value = b ;


signature:
public class StringUtils { /** * Converts a string listing sub - strings seperated by a delimeter into an array of strings .
 * < p / > For example , suppose the string , " one , two , three " is presented with the delimter " , " , then this will be
 * converted into the string array { " one " , " two " , " three " } .
 * @ param value The string to convert .
 * @ param delim The delimeter .
 * @ return The string converted into an array of strings . */
public static String [ ] listToArray ( String value , String delim ) { } }

implementation: List < String > result = new ArrayList < String > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( value , delim ) ; while ( tokenizer . hasMoreTokens ( ) ) { result . add ( tokenizer . nextToken ( ) ) ; } return result . toArray ( new String [ result . size ( ) ] ) ;


signature:
public class StringUtils { /** * Converts an array of strings into a delimeter seperated string .
 * @ param array The array to convert .
 * @ param delim The delimeter to use .
 * @ return The array of strings converted into a delimeter seperated string . */
public static String arrayToList ( String [ ] array , String delim ) { } }

implementation: String result = "" ; for ( int i = 0 ; i < array . length ; i ++ ) { result += array [ i ] + ( ( i == ( array . length - 1 ) ) ? "" : delim ) ; } return result ;


signature:
public class StringUtils { /** * Converts a string to camel case .
 * @ param name The string to convert to camel case .
 * @ return The string in camel case . */
public static String toCamelCase ( String name ) { } }

implementation: String [ ] parts = name . split ( "_" ) ; String result = parts [ 0 ] ; for ( int i = 1 ; i < parts . length ; i ++ ) { if ( parts [ i ] . length ( ) > 0 ) { result += upperFirstChar ( parts [ i ] ) ; } } return result ;


signature:
public class StringUtils { /** * Converts string between various case forms such as camel case , snake case or kebab case .
 * < p / > Characters in the string are characterized as whitespace , upper case , or other by the following rules .
 * < ol >
 * < li > An upper case letter is marked as upper case ( U ) . < / li >
 * < li > A lower case letter or digit is marked as lower case ( L ) . < / li >
 * < li > Any other character is marked as whitespace ( W ) . < / li >
 * < / ol >
 * < p / > The string is processed into words by these rules .
 * < ol >
 * < li > W at the start is discarded . < / li >
 * < li > U or L begins a word . < / li >
 * < li > U after the initial character of a word continues the same word , so long as no W or L is encountered . < / li >
 * < li > L after U or L continues the word , so long as no W is encountered . < / li >
 * < li > U after L begins a new word . < / li >
 * < li > W after U or L is discarded and ends the current word . < / li >
 * < / ol >
 * @ param value The string to convert .
 * @ param separator The separator to place between words .
 * @ param firstLetterUpper < tt > true < / tt > iff the first letter should be in capitals .
 * @ param firstLetterOfWordUpper < tt > true < / tt > iff the first letter of subsequent words should be in capitals .
 * @ return The input converted to lower case words separated by spaces , as per the rules described above . */
public static String convertCase ( String value , String separator , boolean firstLetterUpper , boolean firstLetterOfWordUpper ) { } }

implementation: final StringBuffer result = new StringBuffer ( ) ; boolean firstWord = true ; boolean firstLetter = true ; boolean upper = false ; WordMachineState state = WordMachineState . Initial ; Function2 < Character , Boolean , StringBuffer > writeChar = new Function2 < Character , Boolean , StringBuffer > ( ) { public StringBuffer apply ( Character nextChar , Boolean upper ) { if ( upper ) result . append ( Character . toUpperCase ( nextChar ) ) ; else result . append ( Character . toLowerCase ( nextChar ) ) ; return result ; } } ; for ( int i = 0 ; i < value . length ( ) ; i ++ ) { char nextChar = value . charAt ( i ) ; if ( Character . isUpperCase ( nextChar ) ) { switch ( state ) { case Initial : state = WordMachineState . StartWord ; upper = firstLetterOfWordUpper ; if ( ! firstWord ) { result . append ( separator ) ; } firstWord = false ; break ; case StartWord : case ContinueWordCaps : state = WordMachineState . ContinueWordCaps ; upper = false ; break ; case ContinueWordLower : state = WordMachineState . StartWord ; upper = firstLetterOfWordUpper ; result . append ( separator ) ; break ; } writeChar . apply ( nextChar , ( ! firstLetter && upper ) || ( firstLetter & firstLetterUpper ) ) ; firstLetter = false ; } else if ( Character . isLetterOrDigit ( nextChar ) ) { switch ( state ) { case Initial : state = WordMachineState . StartWord ; upper = firstLetterOfWordUpper ; if ( ! firstWord ) { result . append ( separator ) ; } firstWord = false ; break ; case StartWord : case ContinueWordLower : case ContinueWordCaps : state = WordMachineState . ContinueWordLower ; upper = false ; break ; } writeChar . apply ( nextChar , ( ! firstLetter && upper ) || ( firstLetter & firstLetterUpper ) ) ; firstLetter = false ; } else { switch ( state ) { case Initial : state = WordMachineState . Initial ; break ; case StartWord : case ContinueWordCaps : case ContinueWordLower : state = WordMachineState . Initial ; break ; } upper = false ; } } return result . toString ( ) ;


signature: public class SeleniumMicrodataDocument { public List < MicrodataItem > getItems ( String type ) { } }

implementation: List < WebElement > elements = driver . findElements ( byItemType ( newUrl ( type ) ) ) ; return Lists . transform ( elements , new Function < WebElement , MicrodataItem > ( ) { public MicrodataItem apply ( WebElement element ) { return new SeleniumMicrodataItem ( driver , element ) ; } } ) ;


signature: public class SeleniumMicrodataDocument { public < T > T unwrap ( Class < T > type ) { } }

implementation: checkArgument ( WebDriver . class . equals ( type ) , "Cannot unwrap to: %s" , type ) ; return type . cast ( driver ) ;


signature:
public class LoggingDiagnostic { /** * Provides a string containing information about the configured logging set up .
 * @ return A string containing information about the configured logging set up . */
public static String currentConfiguration ( ) { } }

implementation: StringBuffer rtn = new StringBuffer ( 1024 ) ; String loggingConfigClass = System . getProperty ( "java.util.logging.config.class" ) ; String loggingConfigFile = System . getProperty ( "java.util.logging.config.file" ) ; boolean configClassOK = false ; if ( loggingConfigClass == null ) { rtn . append ( "No java.util.logging.config.class class is set.\n" ) ; } else { rtn . append ( "java.util.logging.config.class is set to '" ) . append ( loggingConfigClass ) . append ( "'\n" ) ; try { Class c = Class . forName ( loggingConfigClass ) ; c . newInstance ( ) ; rtn . append ( "This class was loaded and a new instance was sucessfully created.\n" ) ; configClassOK = true ; } catch ( ClassNotFoundException e ) { e = null ; rtn . append ( loggingConfigClass ) . append ( " could not be found." ) ; } catch ( InstantiationException e ) { e = null ; rtn . append ( loggingConfigClass ) . append ( " could not be instantiated." ) ; } catch ( IllegalAccessException e ) { e = null ; rtn . append ( loggingConfigClass ) . append ( " could not be accessed." ) ; } } if ( loggingConfigFile == null ) { rtn . append ( "No java.util.logging.config.file file is set.\n" ) ; } else { rtn . append ( "java.util.logging.config.file is set to '" ) . append ( loggingConfigFile ) . append ( "'\n" ) ; File loggingFile = new File ( loggingConfigFile ) ; rtn . append ( loggingFile . getAbsolutePath ( ) ) . append ( "\n" ) ; if ( ! loggingFile . exists ( ) || ! loggingFile . isFile ( ) ) { rtn . append ( "This file does NOT EXIST.\n" ) ; } if ( loggingConfigClass != null ) { if ( configClassOK ) { rtn . append ( "This file is ignored because java.util.logging.config.class is set.\n" ) ; } } } Handler [ ] handlers = Logger . getLogger ( "" ) . getHandlers ( ) ; listHandlers ( handlers , rtn ) ; return rtn . toString ( ) ;


signature:
public class LoggingDiagnostic { /** * Lists information about logging handlers .
 * @ param handlers The handlers .
 * @ param buffer A string buffer to build up the listing in .
 * @ return The string buffer to build up the listing in . */
private static StringBuffer listHandlers ( Handler [ ] handlers , StringBuffer buffer ) { } }

implementation: for ( Handler handler : handlers ) { Class < ? extends Handler > handlerClass = handler . getClass ( ) ; Formatter formatter = handler . getFormatter ( ) ; buffer . append ( "Handler:" ) . append ( handlerClass . getName ( ) ) . append ( "\n" ) ; buffer . append ( "Level:" ) . append ( handler . getLevel ( ) . toString ( ) ) . append ( "\n" ) ; if ( formatter != null ) { buffer . append ( "Formatter:" ) . append ( formatter . getClass ( ) . getName ( ) ) . append ( "\n" ) ; } } return buffer ;


signature: public class ControlTck { @ Test public void setValueWhenHiddenControlThrowsException ( ) { } }

implementation: server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "<form name='f'>" + "<input type='hidden' name='c' value='x'/>" + "</form>" + "" ) ) ; Control control = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( "f" ) . getControl ( "c" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( "Cannot set hidden control value: c" ) ; control . setValue ( "y" ) ;


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

implementation: server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "<form name='f'>" + "<input type='text' name='x'/>" + "</form>" + "" ) ) ; Control control = newBrowser ( ) . get ( url ( server ( ) ) ) . getForm ( "f" ) . getControl ( "x" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( "Cannot unwrap to: class java.lang.Void" ) ; control . unwrap ( Void . class ) ;


signature:
public class BasePositionalVisitor { /** * { @ inheritDoc } */
public void visit ( Term term ) { } }

implementation: if ( traverser . isEnteringContext ( ) ) { enterTerm ( term ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveTerm ( term ) ; term . setTermTraverser ( null ) ; }


signature:
public class BasePositionalVisitor { /** * { @ inheritDoc } */
public void visit ( Functor functor ) { } }

implementation: if ( traverser . isEnteringContext ( ) ) { enterFunctor ( functor ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveFunctor ( functor ) ; functor . setTermTraverser ( null ) ; }


signature:
public class BasePositionalVisitor { /** * { @ inheritDoc } */
public void visit ( Variable variable ) { } }

implementation: if ( traverser . isEnteringContext ( ) ) { enterVariable ( variable ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveVariable ( variable ) ; variable . setTermTraverser ( null ) ; }


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

implementation: if ( traverser . isEnteringContext ( ) ) { enterPredicate ( predicate ) ; } else if ( traverser . isLeavingContext ( ) ) { leavePredicate ( predicate ) ; predicate . setTermTraverser ( null ) ; }


signature:
public class BasePositionalVisitor { /** * { @ inheritDoc } */
public void visit ( Clause clause ) { } }

implementation: if ( traverser . isEnteringContext ( ) ) { enterClause ( clause ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveClause ( clause ) ; clause . setTermTraverser ( null ) ; }


signature:
public class BasePositionalVisitor { /** * { @ inheritDoc } */
public void visit ( IntegerType literal ) { } }

implementation: if ( traverser . isEnteringContext ( ) ) { enterIntLiteral ( literal ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveIntLiteral ( literal ) ; literal . setTermTraverser ( null ) ; }


signature:
public class BasePositionalVisitor { /** * { @ inheritDoc } */
public void visit ( LiteralType literal ) { } }

implementation: if ( traverser . isEnteringContext ( ) ) { enterLiteral ( literal ) ; } else if ( traverser . isLeavingContext ( ) ) { leaveLiteral ( literal ) ; literal . setTermTraverser ( null ) ; }


signature:
public class WAMBaseMachine { /** * Looks up the offset of the start of the code for the named functor .
 * @ param functorName The interned name of the functor to find the start address of the code for .
 * @ return The call table entry of the functors code within the code area of the machine , or an invalid address if
 * the functor is not known to the machine . */
public WAMCallPoint resolveCallPoint ( int functorName ) { } }

implementation:
/* log . fine ( " public WAMCallPoint resolveCallPoint ( int functorName ) : called " ) ; */
WAMCallPoint result = ( WAMCallPoint ) symbolTable . get ( functorName , SYMKEY_CALLPOINTS ) ; if ( result == null ) { result = new WAMCallPoint ( - 1 , 0 , functorName ) ; } return result ;


signature:
public class WAMBaseMachine { /** * { @ inheritDoc } */
public void reserveReferenceToLabel ( int labelName , int offset ) { } }

implementation:
// Create call point with label name if it does not already exist .
WAMReservedLabel label = ( WAMReservedLabel ) symbolTable . get ( labelName , SYMKEY_CALLPOINTS ) ; if ( label == null ) { label = new WAMReservedLabel ( labelName ) ; symbolTable . put ( labelName , SYMKEY_CALLPOINTS , label ) ; } // Add to the mapping from the label to referenced from addresses to fill in later .
label . referenceList . add ( offset ) ;


signature:
public class WAMBaseMachine { /** * { @ inheritDoc } */
public void resolveLabelPoint ( int labelName , int address ) { } }

implementation:
// Create the label with resolved address , if it does not already exist .
WAMReservedLabel label = ( WAMReservedLabel ) symbolTable . get ( labelName , SYMKEY_CALLPOINTS ) ; if ( label == null ) { label = new WAMReservedLabel ( labelName ) ; symbolTable . put ( labelName , SYMKEY_CALLPOINTS , label ) ; } label . entryPoint = address ; // Fill in all references to the label with the correct value . This does nothing if the label was just created .
for ( Integer offset : label . referenceList ) { emmitCode ( offset , label . entryPoint ) ; } // Keep a reverse lookup from address to label name .
reverseTable . put ( address , labelName ) ;


signature:
public class WAMBaseMachine { /** * Records the offset of the start of the code for the named functor .
 * @ param functorName The interned name of the functor to find the start address of the code for .
 * @ param offset The offset of the start of the functors code within the code area .
 * @ param length The size of the code to set the address for .
 * @ return The call table entry for the functors code within the code area of the machine . */
protected WAMCallPoint setCodeAddress ( int functorName , int offset , int length ) { } }

implementation:
WAMCallPoint entry = new WAMCallPoint ( offset , length , functorName ) ; symbolTable . put ( functorName , SYMKEY_CALLPOINTS , entry ) ; // Keep a reverse lookup from address to functor name .
reverseTable . put ( offset , functorName ) ; return entry ;


signature:
public class WAMBaseMachine { /** * Records the id of an internal function for the named functor . The method name uses the word ' address ' but this is
 * not really accurate , the address field is used to hold an id of the internal function to be invoked . This method
 * differs from { @ link # setCodeAddress ( int , int , int ) } , as it does not set the reverse mapping from the address to
 * the functor name , since an address is not really being used .
 * @ param functorName The interned name of the functor to find the start address of the code for .
 * @ param id The offset of the start of the functors code within the code area .
 * @ return The call table entry for the functors code within the code area of the machine . */
protected WAMCallPoint setInternalCodeAddress ( int functorName , int id ) { } }

implementation: WAMCallPoint entry = new WAMCallPoint ( id , 0 , functorName ) ; symbolTable . put ( functorName , SYMKEY_CALLPOINTS , entry ) ; return entry ;


signature:
public class HierarchyAttribute { /** * Tests if another hierarchy attribute is strict a sub - category of this one . It is a sub - category if it has the
 * same sequence of path labels as this one as a prefix of its whole path label .
 * @ param comp The hierarchy attribute to compare to .
 * @ return True if the comparator is of the same type and is a sub - category of this one . */
public boolean isSubCategory ( HierarchyAttribute comp ) { } }

implementation:
// Check that the comparator is of the same type class as this one .
if ( ! comp . attributeClass . attributeClassName . equals ( attributeClass . attributeClassName ) ) { return false ; } // Extract the path labels from this and the comparator .
List < String > otherPath = comp . getPathValue ( ) ; List < String > path = getPathValue ( ) ; // Check that the path length of the comparator is the same as this plus one or longer .
if ( otherPath . size ( ) <= path . size ( ) ) { return false ; } // Start by assuming that the paths prefixes are the same , then walk down both paths checking they are
// the same .
boolean subcat = true ; for ( int i = 0 ; i < path . size ( ) ; i ++ ) { // Check that the labels really are equal .
if ( ! otherPath . get ( i ) . equals ( path . get ( i ) ) ) { subcat = false ; break ; } } return subcat ;


signature:
public class HierarchyAttribute { /** * Returns the long id of the attribute .
 * @ return The long id of the attribute . */
public long getId ( ) { } }

implementation:
// Find the category for this hierarchy attribute value .
Tree < CategoryNode > category = attributeClass . lookup . get ( value ) ; // Extract and return the id .
return category . getElement ( ) . id ;


signature:
public class HierarchyAttribute { /** * Sets the integer id of the attribute . If the attribute class is finalized this will change the value of this
 * attribute to that of the matched id , or raise an exception if no matching id exists . If the attribute class is
 * unfinalized this will change the id value of this attribute within the attribute class to the new id , provided
 * that the id has not already been assigned to another attribute value . If it has been assigned to another
 * attribute value then an exception is raised .
 * @ param id The new id value .
 * @ throws IllegalArgumentException If the type is finalized but the id does not exist . Or if the type is
 * unfinalized if the id has already been assigned to another instance of the type . */
public void setId ( long id ) throws IllegalArgumentException { } }

implementation:
// Find the category for this hierarchy attribute value .
Tree < CategoryNode > category = attributeClass . lookup . get ( value ) ; // Extract the id .
long existingId = category . getElement ( ) . id ; // Do nothing if the new id matches the existing one .
if ( id == existingId ) { return ; } // The type is finalized .
if ( attributeClass . finalized ) { // Raise an illegal argument exception if the id is not known .
HierarchyAttribute newValue = attributeClass . getAttributeFromId ( id ) ; // Otherwise , change the value of this attribute to that of the new id .
this . value = newValue . value ; } // The type is unfinalized .
else { // Check if another instance of the type already has the id and raise an exception if so .
Tree < CategoryNode > existingNode = attributeClass . idMap . get ( id ) ; if ( existingNode != null ) { throw new IllegalArgumentException ( "The id value, " + id + ", cannot be set because another instance of this type with that " + "id already exists." ) ; } // Assign it to this instance if the type is unfinalized . Also removing the old id mapping from the id
// map and replacing it with the new one .
category . getElement ( ) . id = id ; attributeClass . idMap . remove ( existingId ) ; attributeClass . idMap . put ( id , category ) ; }


signature:
public class HierarchyAttribute { /** * Gets the label value at the named level of the hierarchy .
 * @ param level The level to get the label at .
 * @ return The label value at the specified level of the hierarchy . */
public String getValueAtLevel ( String level ) { } }

implementation:
/* log . fine ( " public String getValueAtLevel ( String level ) : called " ) ; */
/* log . fine ( " level = " + level ) ; */
int index = attributeClass . levels . indexOf ( level ) ; /* log . fine ( " index = " + index ) ; */
if ( index == - 1 ) { throw new IllegalArgumentException ( "Level name " + level + " is not known to this hierarchy attribute type." ) ; } return getValueAtLevel ( index ) ;


signature:
public class HierarchyAttribute { /** * Gets the label value at the last level of the hierarchy .
 * @ return The label value at the last level of the hierarchy . */
public String getLastValue ( ) { } }

implementation: List < String > pathValue = getPathValue ( ) ; return pathValue . get ( pathValue . size ( ) - 1 ) ;


signature:
public class HierarchyAttribute { /** * Serialized a hierarchy attribute .
 * @ param out The object output stream .
 * @ throws IOException If an IO exception occurs . */
private void writeObject ( ObjectOutputStream out ) throws IOException { } }

implementation:
// Print out some information about the serialized object .
/* log . fine ( " Serialized hierarchy attribute = " + this ) ; */
/* log . fine ( " Serialized hierarchy attribute class = " + attributeClass ) ; */
/* log . fine ( " Serialized attribute classes in static class map are : " ) ; */
for ( HierarchyClassImpl attributeClass : attributeClasses . values ( ) ) { /* log . fine ( attributeClass . toString ( ) ) ; */
} // Perform default serialization .
// out . defaultWriteObject ( ) ;
// Serialized the attribute by value , that is , its full path and the name of its attribute class .
List < String > pathValue = getPathValue ( ) ; String [ ] pathArrayValue = pathValue . toArray ( new String [ pathValue . size ( ) ] ) ; out . writeObject ( pathArrayValue ) ; out . writeObject ( attributeClass . getName ( ) ) ;


signature:
public class HierarchyAttribute { /** * Deserializes a hierarchy attribute .
 * @ param in The object input stream .
 * @ throws IOException If any IO exception occurs .
 * @ throws ClassNotFoundException If any classes to deserialize cannot be found . */
private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { } }

implementation:
// Perform default de - serialization .
// in . defaultReadObject ( ) ;
// Deserialize the attribute by value , from its attribute class and full path .
String [ ] pathArrayValue = ( String [ ] ) in . readObject ( ) ; String attributeClassName = ( String ) in . readObject ( ) ; // Re - create the attribute from its value representation .
HierarchyAttribute attr = getFactoryForClass ( attributeClassName ) . createHierarchyAttribute ( pathArrayValue ) ; // Copy the fields from the freshly constructed attribute into this one .
value = attr . value ; attributeClass = attr . attributeClass ; // Print out some information about the deserialized object .
/* log . fine ( " Deserialized hierarchy attribute = " + this ) ; */
/* log . fine ( " Deserialized hierarchy attribute class = " + attributeClass ) ; */
/* log . fine ( " Deserialized attribute classes in static class map are : " ) ; */
for ( HierarchyClassImpl attributeClass : attributeClasses . values ( ) ) { /* log . fine ( attributeClass . toString ( ) ) ; */
}


signature:
public class ManhattanHeuristic { /** * Returns heuristic evaluation of an eight puzzle board position as the manhattan distance of all tiles from their
 * correct positions .
 * @ param state The EightPuzzleState to calculate the heuristic for .
 * @ param searchNode The heuristic search node for the state in some heuristic search .
 * @ return The heuristic estimation of the cost to the goal from this board position . */
public float computeH ( EightPuzzleState state , HeuristicSearchNode searchNode ) { } }

implementation:
// Get the parent heuristic search node .
HeuristicSearchNode parentNode = ( HeuristicSearchNode ) searchNode . getParent ( ) ; // Check if there is no parent , in which case this is the start state so the complete heuristic needs
// to be calculated .
if ( parentNode == null ) { // Used to hold the running total .
int h = 0 ; // Loop over the whole board .
for ( int j = 0 ; j < 3 ; j ++ ) { for ( int i = 0 ; i < 3 ; i ++ ) { char nextTile = state . getTileAt ( i , j ) ; // Look up the board position of the tile in the solution .
int goalX = state . getGoalXForTile ( nextTile ) ; int goalY = state . getGoalYForTile ( nextTile ) ; // Compute the manhattan distance and add it to the total .
int diffX = goalX - i ; diffX = ( diffX < 0 ) ? - diffX : diffX ; int diffY = goalY - j ; diffY = ( diffY < 0 ) ? - diffY : diffY ; h += diffX + diffY ; } } // Convert the result to a float and return it
return ( float ) h ; } // There is a parent node so calculate the heuristic incrementally from it .
else { // Get the parent board state .
EightPuzzleState parentState = ( EightPuzzleState ) parentNode . getState ( ) ; // Get the parent heurstic value .
float h = parentNode . getH ( ) ; // Get the move that was played .
char playedMove = ( ( String ) searchNode . getAppliedOp ( ) . getOp ( ) ) . charAt ( 0 ) ; // Get the position of the empty tile on the parent board .
int emptyX = parentState . getEmptyX ( ) ; int emptyY = parentState . getEmptyY ( ) ; // Work out which tile has been moved , this is the tile that now sits where the empty tile was .
char movedTile = state . getTileAt ( emptyX , emptyY ) ; // The tile has either moved one step closer to its goal location or one step further away , decide which it
// is . Calculate the X or Y position that the tile moved from .
int oldX = 0 ; int oldY = 0 ; switch ( playedMove ) { case 'L' : { oldX = emptyX - 1 ; break ; } case 'R' : { oldX = emptyX + 1 ; break ; } case 'U' : { oldY = emptyY - 1 ; break ; } case 'D' : { oldY = emptyY + 1 ; break ; } default : { throw new IllegalStateException ( "Unkown operator: " + playedMove + "." ) ; } } // Calculate the change in heuristic .
int change = 0 ; switch ( playedMove ) { // Catch the case where a horizontal move was made .
case 'L' : case 'R' : { // Get the X position of the tile in the goal state and current state
int goalX = state . getGoalXForTile ( movedTile ) ; int newX = emptyX ; // Calculate the change in the heuristic
int oldDiffX = oldX - goalX ; oldDiffX = ( oldDiffX < 0 ) ? - oldDiffX : oldDiffX ; int newDiffX = newX - goalX ; newDiffX = ( newDiffX < 0 ) ? - newDiffX : newDiffX ; change = newDiffX - oldDiffX ; break ; } // Catch the case where a vertical move was made .
case 'U' : case 'D' : { // Get the Y position of the tile in the goal state and current state
int goalY = state . getGoalYForTile ( movedTile ) ; int newY = emptyY ; // Calculate the change in the heuristic
int oldDiffY = oldY - goalY ; oldDiffY = ( oldDiffY < 0 ) ? - oldDiffY : oldDiffY ; int newDiffY = newY - goalY ; newDiffY = ( newDiffY < 0 ) ? - newDiffY : newDiffY ; change = newDiffY - oldDiffY ; break ; } default : { throw new IllegalStateException ( "Unkown operator: " + playedMove + "." ) ; } } // Return the parent heuristic plus or minus one .
return ( change > 0 ) ? ( h + 1.0f ) : ( h - 1.0f ) ; }


signature:
public class KeyQueuedMap { /** * Associates the specified value with the specified key in this map .
 * @ param key The key to store against in this map .
 * @ param value The value to store against the key .
 * @ return The value that was previously stored against the key , or null if there was none . */
public V put ( K key , V value ) { } }

implementation:
// Remove any existing matching key from the data
V removedObject = remove ( key ) ; // Insert the data into the map .
dataMap . put ( key , value ) ; // If the key is fresh , enqueue it .
if ( removedObject != null ) { keys . offer ( key ) ; } // Return the replaced value if there was one
return removedObject ;


signature:
public class HashMapXY { /** * Returns < tt > true < / tt > if this map contains a mapping for the specified coordinates .
 * @ param x The X coordinate .
 * @ param y The Y coordinate .
 * @ return True if this map contains a mapping for the specified coordinate . */
public boolean containsKey ( Long x , Long y ) { } }

implementation:
// Extract the region containing the coordinates from the hash table
Bucket region = ( Bucket ) regions . get ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) ) ; // Check if the whole region is empty
if ( region == null ) { return false ; } // Check if the coordinates within the region contain data
return ( region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] != null ) ;


signature:
public class HashMapXY { /** * Associates the specified value with the specified coordinate in this map ( optional operation ) . If the map
 * previously contained a mapping for this coordinate , the old value is replaced .
 * @ param x The x coordinate .
 * @ param y The y coordinate .
 * @ param value Value to be associated with the specified coordinate .
 * @ return Previous value associated with specified coordinate , or < tt > null < / tt > if there was no mapping for
 * coordinate .
 * @ throws NullPointerException If the specified value is < tt > null < / tt > . */
public E put ( Long x , Long y , E value ) { } }

implementation:
// Check that the value is not null as this data structure does not allow nulls
if ( value == null ) { throw new IllegalArgumentException ( "Null values not allowed in HashMapXY data structure." ) ; } // Extract the region containing the coordinates from the hash table
Bucket < E > region = ( Bucket < E > ) regions . get ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) ) ; // Check if the region does not exist yet and create it if so
if ( region == null ) { region = new Bucket < E > ( bucketSize ) ; regions . put ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) , region ) ; } // Take a reference to the old value if there is one
E old = region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] ; // Insert the new value into the bucket
region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] = value ; // Increment the bucket and whole data structure item counts to reflect the true size
size ++ ; region . itemCount ++ ; // Return the replaced value
return old ;


signature:
public class HashMapXY { /** * Removes the mapping for this coordinate from this map if present ( optional operation ) .
 * @ param x The x coordinate .
 * @ param y The y coordinate .
 * @ return Previous value associated with specified coordinate , or < tt > null < / tt > if there was no mapping for
 * coordinate . */
public E remove ( Long x , Long y ) { } }

implementation:
// Extract the region containing the coordinates from the hash table
Bucket < E > region = ( Bucket < E > ) regions . get ( new Coordinates ( div ( x , bucketSize ) , div ( y , bucketSize ) ) ) ; // Check if the whole region is empty
if ( region == null ) { // Return null as nothing to remove
return null ; } // Get the coordinates within the region
E removed = ( region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] ) ; // Clear the coordinate within the region
region . array [ mod ( x , bucketSize ) ] [ mod ( y , bucketSize ) ] = null ; // Decrement the bucket and whole data strucutre item counts to reflect the true size
size -- ; region . itemCount -- ; // Return the removed data item
return removed ;


signature:
public class HashMapXY { /** * Calculates the modulo of a coordinate with the bucket size . Correctly calculates this module for negative
 * coordinates such the the first negative bucket is - 1 with element 0 corresponding to - 100 running to 99
 * corresponding to - 1.
 * @ param c The coordinate value .
 * @ param bucketSize The bucket size .
 * @ return The coordinate offset into the bucket modulo the bucket size . */
private int mod ( long c , int bucketSize ) { } }

implementation: return ( int ) ( ( c < 0 ) ? ( ( bucketSize + ( c % bucketSize ) ) % bucketSize ) : ( c % bucketSize ) ) ;


signature:
public class MultipleUserErrorException { /** * Adds another user readable error message to this exception .
 * @ param key A key to look up user readable messages with .
 * @ param userMessage The user readable message or data string . */
public void addErrorMessage ( String key , String userMessage ) { } }

implementation:
/* log . fine ( " addErrorMessage ( String key , String userMessage ) : called " ) ; */
/* log . fine ( " userMessage = " + userMessage ) ; */
errors . add ( new UserReadableErrorImpl ( key , userMessage ) ) ;


signature:
public class ErrorHandler { /** * Converts an exception into struts action errors . The exception stack trace is stored under the ' exception '
 * message key . The message resource ' error . internalerror ' is stored under the message key ' generalerror ' . The stack
 * trace is pretty printed in HTML .
 * @ param exception The exception to be converted into struts action errors .
 * @ param errors The struts action errors object into which the action errors should be placed .
 * @ todo This method can be modified to check if the exception is a user readable exception and to insert the user
 * readable message under the ' generalerror ' message key . Currently it does not handle user readable errors
 * like this . */
public static void handleErrors ( Throwable exception , ActionErrors errors ) { } }

implementation:
// Log the error .
log . log ( Level . SEVERE , exception . getMessage ( ) , exception ) ; if ( exception . getCause ( ) == null ) { log . fine ( "Exception.getCause() is null" ) ; } // Unwrap the exception if it is a WrappedStrutsServletException , which is a place holder for returning
// other throwables from struts actions .
// See BaseAction and WrappedStrutsServletException for more information .
if ( ( exception instanceof WrappedStrutsServletException ) && ( exception . getCause ( ) != null ) ) { exception = exception . getCause ( ) ; log . fine ( "Unwrapped WrappedStrutsServletException" ) ; } // Create an error called ' exception ' in the Struts errors for debugging purposes
// Debugging code can print this piece of html containing the exception stack trace at the bottom
// of the page for convenience .
Writer stackTrace = new StringWriter ( ) ; exception . printStackTrace ( new PrintWriter ( new HTMLFilter ( stackTrace ) ) ) ; errors . add ( "exception" , new ActionError ( "error.general" , stackTrace ) ) ; // Check if the exception is a user readable exception
if ( exception instanceof UserReadableError ) { UserReadableError userError = ( UserReadableError ) exception ; // Check that it contains a user readable message
if ( userError . isUserReadable ( ) ) { // Check if there is an error message key to use
if ( userError . getUserMessageKey ( ) != null ) { errors . add ( "generalerror" , new ActionError ( userError . getUserMessageKey ( ) , userError . getUserMessageKey ( ) ) ) ; } // There is no error message key to use so default to error . general and pass the error message as an
// argument so that it will be displayed
else { errors . add ( "generalerror" , new ActionError ( "error.general" , userError . getUserMessage ( ) ) ) ; } return ; } } // Not a user reable exception so print a standard error message
errors . add ( "generalerror" , new ActionError ( "error.internalerror" ) ) ;


signature:
public class HTMLFilter { /** * Writes a string of characters to the filtered writer . Any newline characters ' \ n ' are replaced with an HTML break
 * tag " & lt ; br & gt ; " .
 * @ param str The character array to write .
 * @ param off The offset into the array to begin writing from .
 * @ param len The number of characters to write .
 * @ throws IOException If the writer won ' t accept the string . */
public void write ( String str , int off , int len ) throws IOException { } }

implementation:
// Get just the portion of the input string to display
String inputString = str . substring ( off , off + len ) ; StringBuffer outputString = new StringBuffer ( ) ; // Build a string tokenizer that uses ' \ n ' as its splitting character
// Cycle through all tokens
for ( StringTokenizer tokenizer = new StringTokenizer ( inputString , "\n" , true ) ; tokenizer . hasMoreTokens ( ) ; ) { // Replace ' \ n ' token with a < br >
String nextToken = tokenizer . nextToken ( ) ; if ( "\n" . equals ( nextToken ) ) { outputString . append ( "<br>" ) ; } else { outputString . append ( nextToken ) ; } } // Write out the generated string
out . write ( outputString . toString ( ) ) ;


signature:
public class SSLReadWriteSelectorHandler { /** * Perform any handshaking processing .
 * If a SelectionKey is passed , register for selectable
 * operations .
 * In the blocking case , our caller will keep calling us until
 * we finish the handshake . Our reads / writes will block as expected .
 * In the non - blocking case , we just received the selection notification
 * that this channel is ready for whatever the operation is , so give
 * it a try .
 * return :
 * true when handshake is done .
 * false while handshake is in progress */
boolean doHandshake ( SelectionKey sk ) throws IOException { } }

implementation:
SSLEngineResult result ; if ( initialHSComplete ) { return true ; } /* * Flush out the outgoing buffer , if there ' s anything left in
 * it . */
if ( outNetBB . hasRemaining ( ) ) { if ( ! tryFlush ( outNetBB ) ) { return false ; } // See if we need to switch from write to read mode .
switch ( initialHSStatus ) { /* * Is this the last buffer ? */
case FINISHED : initialHSComplete = true ; // Fall - through to reregister need for a Read .
case NEED_UNWRAP : if ( sk != null ) { sk . interestOps ( SelectionKey . OP_READ ) ; } break ; } return initialHSComplete ; } switch ( initialHSStatus ) { case NEED_UNWRAP : if ( sc . read ( inNetBB ) == - 1 ) { sslEngine . closeInbound ( ) ; return initialHSComplete ; } needIO : while ( initialHSStatus == HandshakeStatus . NEED_UNWRAP ) { /* * Don ' t need to resize requestBB , since no app data should
 * be generated here . */
inNetBB . flip ( ) ; result = sslEngine . unwrap ( inNetBB , requestBB ) ; inNetBB . compact ( ) ; initialHSStatus = result . getHandshakeStatus ( ) ; switch ( result . getStatus ( ) ) { case OK : switch ( initialHSStatus ) { case NOT_HANDSHAKING : throw new IOException ( "Not handshaking during initial handshake" ) ; case NEED_TASK : initialHSStatus = doTasks ( ) ; break ; case FINISHED : initialHSComplete = true ; break needIO ; } break ; case BUFFER_UNDERFLOW : /* * Need to go reread the Channel for more data . */
if ( sk != null ) { sk . interestOps ( SelectionKey . OP_READ ) ; } break needIO ; default : // BUFFER _ OVERFLOW / CLOSED :
throw new IOException ( "Received" + result . getStatus ( ) + "during initial handshaking" ) ; } } // " needIO " block .
/* * Just transitioned from read to write . */
if ( initialHSStatus != HandshakeStatus . NEED_WRAP ) { break ; } // Fall through and fill the write buffers .
case NEED_WRAP : /* * The flush above guarantees the out buffer to be empty */
outNetBB . clear ( ) ; result = sslEngine . wrap ( hsBB , outNetBB ) ; outNetBB . flip ( ) ; initialHSStatus = result . getHandshakeStatus ( ) ; switch ( result . getStatus ( ) ) { case OK : if ( initialHSStatus == HandshakeStatus . NEED_TASK ) { initialHSStatus = doTasks ( ) ; } if ( sk != null ) { sk . interestOps ( SelectionKey . OP_WRITE ) ; } break ; default : // BUFFER _ OVERFLOW / BUFFER _ UNDERFLOW / CLOSED :
throw new IOException ( "Received" + result . getStatus ( ) + "during initial handshaking" ) ; } break ; default : // NOT _ HANDSHAKING / NEED _ TASK / FINISHED
throw new RuntimeException ( "Invalid Handshaking State" + initialHSStatus ) ; } // switch
return initialHSComplete ;


signature:
public class SSLReadWriteSelectorHandler { /** * Read the channel for more information , then unwrap the
 * ( hopefully application ) data we get .
 * If we run out of data , we ' ll return to our caller ( possibly using
 * a Selector ) to get notification that more is available .
 * Each call to this method will perform at most one underlying read ( ) . */
ByteBuffer read ( ) throws IOException { } }

implementation:
SSLEngineResult result ; if ( ! initialHSComplete ) { throw new IllegalStateException ( ) ; } int pos = requestBB . position ( ) ; if ( sc . read ( inNetBB ) == - 1 ) { sslEngine . closeInbound ( ) ; // probably throws exception
throw new EOFException ( ) ; } do { resizeRequestBB ( inNetBB . remaining ( ) ) ; // guarantees enough room for unwrap
inNetBB . flip ( ) ; result = sslEngine . unwrap ( inNetBB , requestBB ) ; inNetBB . compact ( ) ; /* * Could check here for a renegotation , but we ' re only
 * doing a simple read / write , and won ' t have enough state
 * transitions to do a complete handshake , so ignore that
 * possibility . */
switch ( result . getStatus ( ) ) { case BUFFER_UNDERFLOW : case OK : if ( result . getHandshakeStatus ( ) == HandshakeStatus . NEED_TASK ) { doTasks ( ) ; } break ; default : throw new IOException ( "sslEngine error during data read: " + result . getStatus ( ) ) ; } } while ( ( inNetBB . position ( ) != 0 ) && result . getStatus ( ) != Status . BUFFER_UNDERFLOW ) ; int readLength = requestBB . position ( ) - pos ; ByteBuffer byteBuffer = ByteBuffer . allocate ( readLength ) ; byteBuffer . put ( BytesUtil . subBytes ( requestBB . array ( ) , pos , readLength ) ) ; return byteBuffer ;


signature:
public class SSLReadWriteSelectorHandler { /** * Try to flush out any existing outbound data , then try to wrap
 * anything new contained in the src buffer .
 * Return the number of bytes actually consumed from the buffer ,
 * but the data may actually be still sitting in the output buffer ,
 * waiting to be flushed . */
private int doWrite ( ByteBuffer src ) throws IOException { } }

implementation:
int retValue = 0 ; if ( outNetBB . hasRemaining ( ) && ! tryFlush ( outNetBB ) ) { return retValue ; } /* * The data buffer is empty , we can reuse the entire buffer . */
outNetBB . clear ( ) ; SSLEngineResult result = sslEngine . wrap ( src , outNetBB ) ; retValue = result . bytesConsumed ( ) ; outNetBB . flip ( ) ; switch ( result . getStatus ( ) ) { case OK : if ( result . getHandshakeStatus ( ) == HandshakeStatus . NEED_TASK ) { doTasks ( ) ; } break ; default : throw new IOException ( "sslEngine error during data write: " + result . getStatus ( ) ) ; } /* * Try to flush the data , regardless of whether or not
 * it ' s been selected . Odds of a write buffer being full
 * is less than a read buffer being empty . */
tryFlush ( src ) ; if ( outNetBB . hasRemaining ( ) ) { tryFlush ( outNetBB ) ; } return retValue ;


signature:
public class SSLReadWriteSelectorHandler { /** * Flush any remaining data .
 * Return true when the fileChannelBB and outNetBB are empty . */
boolean dataFlush ( ) throws IOException { } }

implementation: boolean fileFlushed = true ; if ( ( fileChannelBB != null ) && fileChannelBB . hasRemaining ( ) ) { doWrite ( fileChannelBB ) ; fileFlushed = ! fileChannelBB . hasRemaining ( ) ; } else if ( outNetBB . hasRemaining ( ) ) { tryFlush ( outNetBB ) ; } return ( fileFlushed && ! outNetBB . hasRemaining ( ) ) ;


signature:
public class SSLReadWriteSelectorHandler { /** * Begin the shutdown process .
 * Close out the SSLEngine if not already done so , then
 * wrap our outgoing close _ notify message and try to send it on .
 * Return true when we ' re done passing the shutdown messsages . */
boolean shutdown ( ) throws IOException { } }

implementation:
if ( ! shutdown ) { sslEngine . closeOutbound ( ) ; shutdown = true ; } if ( outNetBB . hasRemaining ( ) && tryFlush ( outNetBB ) ) { return false ; } /* * By RFC 2616 , we can " fire and forget " our close _ notify
 * message , so that ' s what we ' ll do here . */
outNetBB . clear ( ) ; SSLEngineResult result = sslEngine . wrap ( hsBB , outNetBB ) ; if ( result . getStatus ( ) != Status . CLOSED ) { throw new SSLException ( "Improper close state" ) ; } outNetBB . flip ( ) ; /* * We won ' t wait for a select here , but if this doesn ' t work ,
 * we ' ll cycle back through on the next select . */
if ( outNetBB . hasRemaining ( ) ) { tryFlush ( outNetBB ) ; } return ( ! outNetBB . hasRemaining ( ) && ( result . getHandshakeStatus ( ) != HandshakeStatus . NEED_WRAP ) ) ;


signature:
public class BasicTraverser { /** * { @ inheritDoc } */
public Iterator < Operator < Term > > traverse ( Predicate predicate , boolean reverse ) { } }

implementation:
/* log . fine ( " Traversing predicate " + predicate . toString ( ) ) ; */
Clause [ ] body = predicate . getBody ( ) ; Queue < Operator < Term > > queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; // For the predicate bodies .
if ( body != null ) { for ( int i = leftToRightPredicateBodies ? 0 : ( body . length - 1 ) ; leftToRightPredicateBodies ? ( i < body . length ) : ( i >= 0 ) ; i = i + ( leftToRightPredicateBodies ? 1 : - 1 ) ) { Clause bodyClause = body [ i ] ; bodyClause . setReversable ( createClauseOperator ( bodyClause , i , body , predicate ) ) ; bodyClause . setTermTraverser ( this ) ; queue . offer ( bodyClause ) ; } } return queue . iterator ( ) ;


signature:
public class BasicTraverser { /** * { @ inheritDoc } */
public Iterator < Operator < Term > > traverse ( Clause clause , boolean reverse ) { } }

implementation:
/* log . fine ( " Traversing clause " + clause . toString ( ) ) ; */
Functor head = clause . getHead ( ) ; Functor [ ] body = clause . getBody ( ) ; Queue < Operator < Term > > queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; // For the head functor , set the top - level flag , set in head context .
if ( head != null ) { head . setReversable ( createHeadOperator ( head , clause ) ) ; head . setTermTraverser ( this ) ; queue . offer ( head ) ; } // For the body functors , set the top - level flag , clear in head context .
if ( body != null ) { for ( int i = leftToRightClauseBodies ? 0 : ( body . length - 1 ) ; leftToRightClauseBodies ? ( i < body . length ) : ( i >= 0 ) ; i = i + ( leftToRightClauseBodies ? 1 : - 1 ) ) { Functor bodyFunctor = body [ i ] ; bodyFunctor . setReversable ( createBodyOperator ( bodyFunctor , i , body , clause ) ) ; bodyFunctor . setTermTraverser ( this ) ; queue . offer ( bodyFunctor ) ; } } return queue . iterator ( ) ;


signature:
public class BasicTraverser { /** * { @ inheritDoc } */
public Iterator < Operator < Term > > traverse ( Functor functor , boolean reverse ) { } }

implementation:
/* log . fine ( " Traversing functor " + functor . toString ( ) ) ; */
Queue < Operator < Term > > queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; Term [ ] arguments = functor . getArguments ( ) ; // For a top - level functor clear top - level flag , so that child functors are not taken as top - level .
if ( arguments != null ) { for ( int i = leftToRightFunctorArgs ? 0 : ( arguments . length - 1 ) ; leftToRightFunctorArgs ? ( i < arguments . length ) : ( i >= 0 ) ; i = i + ( leftToRightFunctorArgs ? 1 : - 1 ) ) { Term argument = arguments [ i ] ; argument . setReversable ( createTermOperator ( argument , i , functor ) ) ; argument . setTermTraverser ( this ) ; queue . offer ( argument ) ; } } return queue . iterator ( ) ;


signature:
public class TopLevelCheckVisitor { /** * { @ inheritDoc }
 * < p / > Sets the top - level flag on a functor , if appropriate . */
protected void enterFunctor ( Functor functor ) { } }

implementation: if ( isTopLevel ( ) ) { symbolTable . put ( functor . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_TOP_LEVEL_FUNCTOR , true ) ; }


signature:
public class TopLevelCheckVisitor { /** * Functors are considered top - level when they appear at the top - level within a clause , or directly beneath a parent
 * conjunction or disjunction that is considered to be top - level .
 * @ return < tt > true < / tt > iff the current position is considered to be top - level . */
private boolean isTopLevel ( ) { } }

implementation: if ( traverser . isTopLevel ( ) ) { return true ; } else { PositionalContext parentContext = traverser . getParentContext ( ) ; if ( parentContext != null ) { Term parentTerm = parentContext . getTerm ( ) ; if ( ( parentTerm instanceof Conjunction ) || ( parentTerm instanceof Disjunction ) ) { Boolean isTopLevel = ( Boolean ) symbolTable . get ( parentTerm . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_TOP_LEVEL_FUNCTOR ) ; return ( isTopLevel == null ) ? false : isTopLevel ; } } } return false ;


signature:
public class EnhancedTextGridImpl { /** * { @ inheritDoc } */
public void insertAttribute ( AttributeSet attributes , int c , int r ) { } }

implementation: attributeGrid . insertAttribute ( attributes , c , r ) ; updateListeners ( ) ;


signature:
public class EnhancedTextGridImpl { /** * { @ inheritDoc } */
public void select ( int row , int col ) { } }

implementation: for ( TextGridSelectionListener listener : textGridSelectionListeners ) { listener . select ( new TextGridEvent ( this , row , col ) ) ; }


signature:
public class EnhancedTextGridImpl { /** * { @ inheritDoc }
 * < p / > Override the table creation to supply an enhanced text table . */
public EnhancedTextTable createTable ( int c , int r , int w , int h ) { } }

implementation:
// Supply a text table , with this grid set up to listen for updates to the table , and to be re - rendered as the
// table changes .
EnhancedTextTable textTable = new EnhancedTextTableImpl ( ) ; textTable . addTextTableListener ( new EnhancedTableListener ( ) ) ; return textTable ;


signature:
public class ProtoDTMachine { /** * Classifies a state using the decision tree .
 * @ param state The input data point to classify .
 * @ return A classification of the data point as an mapping from the output property that the decision tree was
 * trained on to this classifiers belief abouts its value .
 * @ throws ClassifyingFailureException If the decision tree is not completed and this classifier encounters a
 * pending node in the tree that is still to be built . */
public Map < String , OrdinalAttribute > classify ( State state ) throws ClassifyingFailureException { } }

implementation:
// Start at the root of the decision tree .
DecisionTree currentNode = dt ; // Loop down the decision tree until a leaf node is found .
while ( true ) // ! currentNode . isLeaf ( ) )
{ DecisionTreeElement element = currentNode . getElement ( ) ; // Check that the current element really is a decision .
if ( element instanceof Decision ) { Decision decision = ( Decision ) element ; // Apply the decision at the current node to the state to be classified to get a new tree .
currentNode = decision . decide ( state ) ; // , currentNode ) ;
} else if ( element instanceof Assignment ) { // Cast the element to an Assignment as this is the only type of leaf that is possible .
Assignment assignment = ( Assignment ) element ; // Return the assignment in a map .
Map < String , OrdinalAttribute > assignmentMap = new HashMap < String , OrdinalAttribute > ( ) ; assignmentMap . put ( assignment . getPropertyName ( ) , assignment . getAttribute ( ) ) ; return assignmentMap ; } // It is possible that a node may be of type Pending if an incomplete tree has been used to
// run this classification on .
else { // Throw a classification exception due to an incomplete decision tree .
throw new ClassifyingFailureException ( "A node which is not a decision was encountered." , null ) ; } // What happens if the decision could not operate on the state , either because of a missing property or
// because its property was not of the type that the decision was expecting ? Can either throw an exception ,
// return an empty assignment , or implement an algorithm for coping with missing properties .
}


signature: public class MicrodataItemTck { @ Test public void getIdReturnsId ( ) throws MalformedURLException { } }

implementation:
server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "" ) ) ; URL actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://y" ) . getId ( ) ; assertThat ( "item id" , actual , is ( new URL ( "http://x" ) ) ) ;


signature: public class MicrodataItemTck { @ Test public void getTypeReturnsType ( ) throws MalformedURLException { } }

implementation:
server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "" ) ) ; URL actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://x" ) . getType ( ) ; assertThat ( "item type" , actual , is ( new URL ( "http://x" ) ) ) ;


signature: public class MicrodataItemTck { @ Test public void getPropertyReturnsProperty ( ) { } }

implementation:
server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "
" + "
" + "" ) ) ; MicrodataProperty actual = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) . getProperty ( "x" ) ; assertThat ( "item property" , actual . getName ( ) , is ( "x" ) ) ;


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

implementation:
server ( ) . enqueue ( new MockResponse ( ) . setBody ( "" + "
" + "" ) ) ; MicrodataItem item = newBrowser ( ) . get ( url ( server ( ) ) ) . getItem ( "http://i" ) ; thrown ( ) . expect ( IllegalArgumentException . class ) ; thrown ( ) . expectMessage ( "Cannot unwrap to: class java.lang.Void" ) ; item . unwrap ( Void . class ) ;


signature:
public class PartialOrdering { /** * Translates the partial order into the + 1 , 0 , - 1 convention needed by Comparators .
 * @ param a The first item to compare .
 * @ param b The second item to compare .
 * @ return 0 if the two elements are equal under the partial ordering , 1 if aRb , and - 1 if ! aRb . */
public int compare ( T a , T b ) { } }

implementation: boolean aRb = partialOrdering . evaluate ( a , b ) ; if ( ! aRb ) { return - 1 ; } boolean bRa = partialOrdering . evaluate ( b , a ) ; return ( aRb && bRa ) ? 0 : 1 ;


signature:
public class AStarSearch { /** * Creates a priority queue with an { @ link AStarComparator } to control the search ordering of the basic queue search
 * algorithm .
 * @ return The A * priority queue . */
public Queue < SearchNode < O , T > > createQueue ( ) { } }

implementation: return new PriorityQueue < SearchNode < O , T > > ( 11 , new AStarComparator ( ) ) ;


signature:
public class SymbolKeyTraverser { /** * { @ inheritDoc } */
public Iterator < Operator < Term > > traverse ( Clause clause , boolean reverse ) { } }

implementation:
/* log . fine ( " Traversing clause " + clause . toString ( interner , true , false ) ) ; */
Functor head = clause . getHead ( ) ; Functor [ ] body = clause . getBody ( ) ; Queue < Operator < Term > > queue = ( ! reverse ) ? new StackQueue < Operator < Term > > ( ) : new LinkedList < Operator < Term > > ( ) ; // Create a nested scope in the symbol table for the clause , under its functor name / arity .
int predicateName ; int clauseIndex ; if ( clause . isQuery ( ) ) { predicateName = - 1 ; } else { predicateName = head . getName ( ) ; } Integer numberOfClauses = ( Integer ) rootSymbolTable . get ( predicateName , CLAUSE_NO_SYMBOL_FIELD ) ; if ( numberOfClauses == null ) { numberOfClauses = 0 ; } rootSymbolTable . put ( predicateName , CLAUSE_NO_SYMBOL_FIELD , numberOfClauses + 1 ) ; clauseIndex = numberOfClauses ; SymbolTable < Integer , String , Object > predicateScopedSymbolTable = rootSymbolTable . enterScope ( predicateName ) ; /* log . fine ( indenter . generateTraceIndent ( 2 ) + " Enter predicate scope " + predicateName ) ; */
clauseScopedSymbolTable = predicateScopedSymbolTable . enterScope ( clauseIndex ) ; /* log . fine ( indenter . generateTraceIndent ( 2 ) + " Enter clause scope " + clauseIndex ) ; */
// For the head functor , clear the top - level flag , set in head context .
if ( head != null ) { head . setReversable ( new ContextOperator ( clauseScopedSymbolTable , 0 , createHeadOperator ( head , clause ) ) ) ; head . setTermTraverser ( this ) ; queue . offer ( head ) ; /* log . fine ( " Set SKT as traverser on " + head . toString ( interner , true , false ) ) ; */
/* log . fine ( " Created : " + ( " head operator " + 0 + " on " + head . toString ( interner , true , false ) ) ) ; */
} // For the body functors , set the top - level flag , clear in head context .
if ( body != null ) { for ( int i = 0 ; i < body . length ; i ++ ) { Functor bodyFunctor = body [ i ] ; bodyFunctor . setReversable ( new ContextOperator ( clauseScopedSymbolTable , i + 1 , createBodyOperator ( bodyFunctor , i , body , clause ) ) ) ; bodyFunctor . setTermTraverser ( this ) ; queue . offer ( bodyFunctor ) ; /* log . fine ( " Set SKT as traverser on " + bodyFunctor . toString ( interner , true , false ) ) ; */
/* log . fine ( " Created : " +
 ( " body operator " + ( i + 1 ) + " on " + bodyFunctor . toString ( interner , true , false ) ) ) ; */
} } return queue . iterator ( ) ;