signature:
public class BaseCodeMachine { /** * { @ inheritDoc }
 * < p / > It is expected that the compiled code being written into the machine , will not have its call resolved onto
 * call - points , and that call will be made to the { @ link # resolveCallPoint ( int ) } method , during this procedure to
 * resolve them . */
public void emmitCode ( C compiled ) throws LinkageException { } }

implementation:
/* log . fine ( " public void emmitCode ( C compiled ) : called " ) ; */
SizeableList < I > instructions = compiled . getInstructions ( ) ; // Get the call point for the code to write .
CallPoint callPoint = resolveCallPoint ( compiled . getName ( ) ) ; if ( callPoint == null ) { /* log . fine ( " call point not resolved , reserving new one . " ) ; */
callPoint = reserveCallPoint ( compiled . getName ( ) , ( int ) instructions . sizeof ( ) ) ; } /* log . fine ( " insertion point = " + getCodeInsertionPoint ( ) ) ; */
// Pass a reference to a buffer set to write to the call point in the code buffer on the encoder .
instructionEncoder . setCodeBuffer ( getCodeBuffer ( callPoint ) ) ; // Loop over all instructions encoding them to byte code in the machines code buffer .
for ( I instruction : instructions ) { instruction . accept ( instructionEncoder ) ; }


signature:
public class BaseCodeMachine { /** * Reserves a call point for a block of named callable code . The size of the block of code must be known fully in
 * advance . If the named block already has a call point , this will replace it with a new one .
 * < p / > Adding code into a code machine may be a two - stage process , first reserve call - points for all blocks of code ,
 * then add the blocks of code into the machine , resolving internal call points within the code onto previously
 * reserved call points as this is done . A two - stage process is required to support recursive or mutually recursive
 * callable procedures .
 * @ param name The interned name of the procedure to create a call point for .
 * @ param length The length of the procedures code .
 * @ return A new call point for the procedure . */
public CallPoint reserveCallPoint ( int name , int length ) { } }

implementation:
// Work out where the code will go and advance the insertion point beyond its end , so that additional code
// will be added beyond the reserved space .
int address = getCodeInsertionPoint ( ) ; advanceCodeInsertionPoint ( length ) ; // Create a call point for the reserved space .
CallPoint callPoint = new CallPoint ( address , length , name ) ; // Add the call point to the symbol table under the interned name .
symbolTable . put ( name , getCallPointSymbolField ( ) , callPoint ) ; return callPoint ;


signature:
public class TimeUtils { /** * Converts a field by field timestamp into millisecond ticks .
 * @ param year The year .
 * @ param month The month .
 * @ param day The day .
 * @ param hours The hours .
 * @ param minutes The minutes .
 * @ param seconds The seconds .
 * @ param milliseconds The milliseconds .
 * @ return Millisecond ticks since midnight 01/01/1970. */
public static long timestampToTicks ( int year , int month , int day , int hours , int minutes , int seconds , int milliseconds ) { } }

implementation: boolean isLeapYear = isLeapYear ( year ) ; long dayComponent = ( long ) ( day - 1 ) * MILLIS_PER_DAY ; long monthComponent = millisToStartOfMonth ( month , isLeapYear ) ; long yearComponent = millisToYearStart ( year ) ; long hoursComponent = ( long ) hours * MILLIS_PER_HOUR ; long minutesComponent = ( long ) minutes * MILLIS_PER_MINUTE ; long secondsComponent = ( long ) seconds * MILLIS_PER_SECOND ; return dayComponent + monthComponent + yearComponent + hoursComponent + minutesComponent + secondsComponent + milliseconds ;


signature:
public class TimeUtils { /** * Converts a field by field timestamp into millisecond ticks .
 * @ param year The year .
 * @ param month The month .
 * @ param day The day .
 * @ return Millisecond ticks since midnight 01/01/1970. */
public static long timestampToTicks ( int year , int month , int day ) { } }

implementation: boolean isLeapYear = isLeapYear ( year ) ; long dayComponent = ( long ) ( day - 1 ) * MILLIS_PER_DAY ; long monthComponent = millisToStartOfMonth ( month , isLeapYear ) ; long yearComponent = millisToYearStart ( year ) ; return dayComponent + monthComponent + yearComponent ;


signature:
public class TimeUtils { /** * Converts a field by field time of day into millisecond ticks .
 * @ param hour The hours since midnight .
 * @ param minute The minutes .
 * @ param second The seconds .
 * @ param millisecond The milliseconds .
 * @ return Millisecond ticks since midnight . */
public static long timeOfDayToTicks ( int hour , int minute , int second , int millisecond ) { } }

implementation: return millisecond + ( MILLIS_PER_SECOND * second ) + ( MILLIS_PER_MINUTE * minute ) + ( MILLIS_PER_HOUR * hour ) ;


signature:
public class TimeUtils { /** * Extracts the years component of a time in millisecond ticks .
 * @ param ticks The time in ticks .
 * @ return The years component of the time . */
public static int ticksToYears ( long ticks ) { } }

implementation:
// The number of years is ticks floor divided by number of milliseconds in 365 1/4 days .
// return flooredDiv ( ticks , MILLIS _ PER _ REAL _ YEAR ) + 1970;
// return flooredDiv ( ticks + ( ( long ) DAYS _ TO _ 1970 * MILLIS _ PER _ DAY ) , MILLIS _ PER _ REAL _ YEAR ) ;
long unitMillis = MILLIS_PER_YEAR / 2 ; long i2 = ( ticks >> 1 ) + ( ( 1970L * MILLIS_PER_YEAR ) / 2 ) ; if ( i2 < 0 ) { i2 = i2 - unitMillis + 1 ; } int year = ( int ) ( i2 / unitMillis ) ; long yearStart = millisToYearStart ( year ) ; long diff = ticks - yearStart ; if ( diff < 0 ) { year -- ; } else if ( diff >= ( MILLIS_PER_DAY * 365L ) ) { // One year may need to be added to fix estimate .
long oneYear ; if ( isLeapYear ( year ) ) { oneYear = MILLIS_PER_DAY * 366L ; } else { oneYear = MILLIS_PER_DAY * 365L ; } yearStart += oneYear ; if ( yearStart <= ticks ) { year ++ ; } } return year ;


signature:
public class TimeUtils { /** * Extracts the date ( day in month ) component of a time in millisecond ticks .
 * @ param ticks The time in ticks .
 * @ return The date ( day in month ) component of the time . */
public static int ticksToDate ( long ticks ) { } }

implementation: int year = ticksToYears ( ticks ) ; int month = ticksToMonths ( ticks ) ; long dayOffset = ticks ; dayOffset -= millisToYearStart ( year ) ; dayOffset -= isLeapYear ( year ) ? ( ( long ) LEAP_DAYS_IN_YEAR_PRIOR_TO_MONTH [ month - 1 ] * MILLIS_PER_DAY ) : ( ( long ) USUAL_DAYS_IN_YEAR_PRIOR_TO_MONTH [ month - 1 ] * MILLIS_PER_DAY ) ; return ( int ) ( dayOffset / MILLIS_PER_DAY ) + 1 ;


signature:
public class TimeUtils { /** * Sets the component of the timestamp , returning the new timestamp with updated component .
 * @ param ticks The time in ticks .
 * @ param hours The new hours field .
 * @ return The new time in ticks . */
public static long ticksWithHoursSetTo ( long ticks , int hours ) { } }

implementation: long oldHours = ticksToHours ( ticks ) ; return ticks - ( oldHours * MILLIS_PER_HOUR ) + ( hours * MILLIS_PER_HOUR ) ;


signature:
public class TimeUtils { /** * Sets the minutes component of the timestamp , returning the new timestamp with updated component .
 * @ param ticks The time in ticks .
 * @ param minutes The new minutes field .
 * @ return The new time in ticks . */
public static long ticksWithMinutesSetTo ( long ticks , int minutes ) { } }

implementation: long oldMinutes = ticksToMinutes ( ticks ) ; return ticks - ( oldMinutes * MILLIS_PER_MINUTE ) + ( minutes * MILLIS_PER_MINUTE ) ;


signature:
public class TimeUtils { /** * Sets the seconds component of the timestamp , returning the new timestamp with updated component .
 * @ param ticks The time in ticks .
 * @ param seconds The new seconds field .
 * @ return The new time in ticks . */
public static long ticksWithSecondsSetTo ( long ticks , int seconds ) { } }

implementation: long oldSeconds = ticksToSeconds ( ticks ) ; return ticks - ( oldSeconds * MILLIS_PER_SECOND ) + ( seconds * MILLIS_PER_SECOND ) ;


signature:
public class TimeUtils { /** * Sets the year component of the timestamp , returning the new timestamp with updated component .
 * @ param ticks The time in ticks .
 * @ param year The new year field .
 * @ return The new time in ticks . */
public static long ticksWithYearSetTo ( long ticks , int year ) { } }

implementation: int oldYear = ticksToYears ( ticks ) ; return ticks - millisToYearStart ( oldYear ) + millisToYearStart ( year ) ;


signature:
public class TimeUtils { /** * Sets the month component of the timestamp , returning the new timestamp with updated component .
 * @ param ticks The time in ticks .
 * @ param month The new month field .
 * @ return The new time in ticks . */
public static long ticksWithMonthSetTo ( long ticks , int month ) { } }

implementation: int year = ticksToYears ( ticks ) ; boolean isLeapYear = isLeapYear ( year ) ; int oldMonth = ticksToMonths ( ticks ) ; return ticks - millisToStartOfMonth ( oldMonth , isLeapYear ) + millisToStartOfMonth ( month , isLeapYear ) ;


signature:
public class TimeUtils { /** * Sets the date component of the timestamp , returning the new timestamp with updated component .
 * @ param ticks The time in ticks .
 * @ param date The new date field .
 * @ return The new time in ticks . */
public static long ticksWithDateSetTo ( long ticks , int date ) { } }

implementation: int oldDays = ticksToDate ( ticks ) ; return ticks - ( oldDays * MILLIS_PER_DAY ) + ( date * MILLIS_PER_DAY ) ;


signature:
public class TimeUtils { /** * Calculates the number of milliseconds to the start of the specified year , taking 1970 as zero .
 * @ param year The year .
 * @ return The number of milliseconds to the start of the specified year , taking 1970 as zero . */
public static long millisToYearStart ( int year ) { } }

implementation:
// Calculate how many leap years elapsed prior to the year in question .
int leapYears = year / 100 ; if ( year < 0 ) { leapYears = ( ( year + 3 ) >> 2 ) - leapYears + ( ( leapYears + 3 ) >> 2 ) - 1 ; } else { leapYears = ( year >> 2 ) - leapYears + ( leapYears >> 2 ) ; if ( isLeapYear ( year ) ) { leapYears -- ; } } return ( ( year * 365L ) + leapYears - DAYS_TO_1970 ) * MILLIS_PER_DAY ;


signature:
public class TimeUtils { /** * Writes a time of day with milliseconds in the format HH : MM : SS [ . sss ] , into a byte buffer . The specified buffer
 * will be enlarged if necessary using the specified byte buffer pool .
 * @ param buffer The initial buffer to write to .
 * @ param value The time of day since midnight , in milliseconds .
 * @ return The buffer written to . */
public static ByteBuffer putTimeOnlyAsString ( ByteBuffer buffer , long value ) { } }

implementation: buffer = putTimeOnlyAsString ( buffer , value , true ) ; return buffer ;


signature:
public class TimeUtils { /** * Writes only the time component of a time of day timestamp to a byte array in the following format :
 * HH : MM : SS [ . sss ] . The millisecond value is optional and is only written if requested . If there is insufficient
 * space in the buffer to write the value into , then the buffer size is increased using the supplied byte buffer
 * pool .
 * @ param buffer The byte buffer to write to .
 * @ param value The value to write as a millisecond timestamp .
 * @ param includeMilliseconds < tt > true < / tt > to include milliseconds in the output .
 * @ return The byte buffer with the value written to it . This may be a different buffer to the one passed in if the
 * buffer had to be copied in order to increase its size . */
public static ByteBuffer putTimeOnlyAsString ( ByteBuffer buffer , long value , boolean includeMilliseconds ) { } }

implementation:
// Ensure there is sufficient space in the buffer for the date .
int charsRequired = includeMilliseconds ? TIME_ONLY_LENGTH_WITH_MILLISECONDS : TIME_ONLY_LENGTH_WIHTOUT_MILLISECONDS ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToHours ( value ) , 2 ) ; buffer = ByteBufferUtils . putByteAsString ( buffer , ( byte ) ':' ) ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToMinutes ( value ) , 2 ) ; buffer = ByteBufferUtils . putByteAsString ( buffer , ( byte ) ':' ) ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToSeconds ( value ) , 2 ) ; if ( includeMilliseconds ) { buffer = ByteBufferUtils . putByteAsString ( buffer , ( byte ) '.' ) ; buffer = ByteBufferUtils . putPaddedInt32AsString ( buffer , ticksToMilliseconds ( value ) , 3 ) ; } return buffer ;


signature:
public class TimeUtils { /** * Given a millisecond timestamp that lands in a specified year , calculate what month the timestamp corresponds to .
 * @ param ticks The timestamp .
 * @ param year The year that the timestamp falls in .
 * @ return The month that the timestamp falls in , in the range 1 to 12. */
private static int getMonthOfYear ( long ticks , int year ) { } }


signature:
public class DistributedInputStreamImpl { /** * Reads some number of bytes from the input stream and stores them into the buffer array b . The bytes are also
 * returned wrapped in a byte block so that they can be returnd over RMI .
 * @ param b The byte array to store the results of the read into .
 * @ return The same results but wrapped in byte block .
 * @ throws IOException If an I / O error occurs when accessing the stream .
 * @ throws RemoteException If an RMI error occurs during remote access . */
public ByteBlock read ( byte [ ] b ) throws IOException { } }

implementation: int count = source . read ( b ) ; return new ByteBlock ( b , count ) ;


signature:
public class DistributedInputStreamImpl { /** * Reads up to len bytes of data from the input stream into an array of bytes .
 * @ param b The byte array to store the results of the read into .
 * @ 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 same results as stored in parameter b but wrapped in byte block .
 * @ throws IOException If an I / O error occurs when accessing the stream .
 * @ throws RemoteException If an RMI error occurs during remote access . */
public ByteBlock read ( byte [ ] b , int off , int len ) throws IOException { } }

implementation: int count = source . read ( b , off , len ) ; return new ByteBlock ( b , count ) ;


signature:
public class SequentialCuckooFunction { /** * { @ inheritDoc } */
public boolean containsKey ( K key ) { } }

implementation: int keyHashCode = key . hashCode ( ) ; int hash1 = hash1 ( keyHashCode ) ; Entry < K > entry = hashTable [ indexFor ( hash1 ) ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { return true ; } entry = hashTable [ indexFor ( hash2 ( hash1 , keyHashCode ) ) ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { return true ; } return false ;


signature:
public class SequentialCuckooFunction { /** * { @ inheritDoc } */
public Integer remove ( Object objectKey ) { } }

implementation: K key = ( K ) objectKey ; int keyHashCode = key . hashCode ( ) ; int hash1 = hash1 ( keyHashCode ) ; int index1 = indexFor ( hash1 ) ; Entry < K > entry = hashTable [ index1 ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { hashTable [ index1 ] = null ; return entry . seq ; } int hash2 = hash2 ( hash1 , keyHashCode ) ; int index2 = indexFor ( hash2 ) ; entry = hashTable [ index2 ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { hashTable [ index2 ] = null ; return entry . seq ; } return null ;


signature:
public class SequentialCuckooFunction { /** * { @ inheritDoc } */
public void clear ( ) { } }

implementation: count = 0 ; nextSequenceNumber = 0 ; hashTable = ( Entry < K > [ ] ) new Entry [ hashTableSize ] ; length = hashTable . length ;


signature:
public class SequentialCuckooFunction { /** * Looks up the specified key in hash table , using cuckoo hashing . If the key cannot be found in the table , then the
 * next available sequence number is allocated to it , and a new entry is added to the hash table for the key , again
 * using cuckoo hashing .
 * < p / > To save creating entries that already exist , if an entry for the key already exists , because this method is
 * being called to rehash an old table into a new one , then the entry may be passed into this method . In that case ,
 * no new entry will be created and the existing one will be re - used . It is assumed that the entry passed in is the
 * correct one for the key .
 * @ param key The key to get a sequence number for .
 * @ param entry The entry for the key , or < tt > null < / tt > to create a new one .
 * @ param tryRehashing < tt > true < / tt > if rehashing should be trued , otherwise just fail .
 * @ return A sequence number for the key , or < tt > null < / tt > if this fails . */
private Integer applyWithEntry ( K key , Entry < K > entry , boolean tryRehashing ) { } }

implementation:
// Used to hold a new entry if one has to be created , or can re - use an entry passed in as a parameter .
Entry < K > uninsertedEntry = entry ; // Holds a flag to indicate that a new sequence number has been taken .
boolean createdNewEntry = false ; // Check if there is already an entry for the key , and return it if so .
Entry < K > existingEntry = entryForKey ( key ) ; Integer result = null ; if ( existingEntry != null ) { result = existingEntry . seq ; } else { // Create a new entry , if one has not already been created and cached .
if ( uninsertedEntry == null ) { uninsertedEntry = new Entry < K > ( ) ; uninsertedEntry . key = key ; uninsertedEntry . seq = nextSequenceNumber ; nextSequenceNumber ++ ; count ++ ; createdNewEntry = true ; result = uninsertedEntry . seq ; } // Attempt to insert the new entry . The sequence number is only incremented when this succeeds for a new
// entry . Existing entries that are being re - hashed into a new table will not increment the sequence
// number .
while ( true ) { // Hash the entry for the current hash functions .
int keyHashCode = uninsertedEntry . key . hashCode ( ) ; uninsertedEntry . hash1 = hash1 ( keyHashCode ) ; uninsertedEntry . hash2 = hash2 ( uninsertedEntry . hash1 , keyHashCode ) ; // Try and insert the entry , checking that no entry is left uninserted as a result .
uninsertedEntry = cuckoo ( uninsertedEntry ) ; if ( uninsertedEntry == null ) { result = createdNewEntry ? result : - 1 ; break ; } // If the cuckoo algorithm fails then change the hash function / table size and try again .
if ( tryRehashing ) { rehash ( ) ; } else { result = null ; break ; } } } return result ;


signature:
public class SequentialCuckooFunction { /** * Checks if the specified key can be found in the set , and returns its entry if so .
 * @ param key The key to check for in the entry set .
 * @ return The keys entry if it is already in the set , < tt > null < / tt > if not . */
private Entry < K > entryForKey ( K key ) { } }

implementation: int keyHashCode = key . hashCode ( ) ; int hash1 = hash1 ( keyHashCode ) ; Entry < K > entry = hashTable [ indexFor ( hash1 ) ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { return entry ; } int hash2 = hash2 ( hash1 , keyHashCode ) ; entry = hashTable [ indexFor ( hash2 ) ] ; if ( ( entry != null ) && key . equals ( entry . key ) ) { return entry ; } return null ;


signature:
public class SequentialCuckooFunction { /** * Adds a new entry to a hash table , using the cuckoo algorithm .
 * @ param entry The new key to add .
 * @ return < tt > null < / tt > if the cuckoo algorithm inserted the new entry , or the currently uninserted entry if it
 * could not complete the insertion . Note that the currently uninserted entry may not be the entry
 * originally requested to be inserted , as that may have succeeded , and a displaced entry further down the
 * chain of cuckoo insertions may be the current uninserted one , that remains to be inserted . */
private Entry < K > cuckoo ( Entry < K > entry ) { } }

implementation:
// Holds the entry currently being placed in the hash table .
Entry < K > currentEntry = entry ; // Holds the index into the hash table where the current entry will be placed .
int hash = entry . hash1 ; int index = indexFor ( hash ) ; Entry < K > nextEntry = hashTable [ index ] ; int previousFlag = 0 ; int [ ] previousIndex = new int [ 2 ] ; int [ ] previousSeq = new int [ 2 ] ; for ( int i = 0 ; i < hashTableSize ; i ++ ) { // Check the current index , to see if it is an empty slot . If it is an empty slot then the current
// entry is placed there and the algorithm completes .
if ( nextEntry == null ) { hashTable [ index ] = currentEntry ; return null ; } // If the current index does not point to an empty slot , the current entry is placed there anyway , but the
// displaced entry ( the egg displaced by the cuckoo ) becomes the current entry for placing .
hashTable [ index ] = currentEntry ; currentEntry = nextEntry ; // A new index is selected depending on whether the entry is currently at its primary or secondary hashing .
int firstPosition = indexFor ( currentEntry . hash1 ) ; hash = ( index == firstPosition ) ? currentEntry . hash2 : currentEntry . hash1 ; index = indexFor ( hash ) ; // A check for infinite loops of size 2 is made here , to circumvent the simplest and most common infinite
// looping condition .
previousIndex [ previousFlag ] = index ; previousSeq [ previousFlag ] = nextEntry . seq ; previousFlag = ( previousFlag == 1 ) ? 0 : 1 ; nextEntry = hashTable [ index ] ; if ( ( nextEntry != null ) && ( index == previousIndex [ previousFlag ] ) && ( nextEntry . seq == previousSeq [ previousFlag ] ) ) { break ; } } return currentEntry ;


signature:
public class SequentialCuckooFunction { /** * Creates a new hashtable that is twice the size of the old one , then re - hashes everything from the old table into
 * the new table .
 * @ throws IllegalStateException If the table cannot be increased in size because the maximum size limit would be
 * breached . */
private void rehash ( ) { } }

implementation:
// Increase the table size , to keep the load factory < 0.5.
int newSize = hashTableSize ; if ( hashTableSize < ( count * 2 ) ) { newSize = hashTableSize * 2 ; if ( newSize > maxSize ) { throw new IllegalStateException ( "'newSize' of " + newSize + " would put the table over the maximum size limit of " + maxSize ) ; } } // Keep hold of the old table , until a new one is succesfully buily .
Entry < K > [ ] oldTable = hashTable ; hashTableSize = newSize ; length = hashTable . length ; // Keep rehashing the table until it is succesfully rebuilt .
boolean rehashedOk ; do { // Start by assuming that this will work .
rehashedOk = true ; // Alter the hash functions .
changeHashFunctions ( ) ; // Create a new table from the old one , to rehash everything into .
hashTable = ( Entry < K > [ ] ) new Entry [ hashTableSize ] ; for ( Entry < K > entry : oldTable ) { if ( entry != null ) { // Add the entry to the new table , dropping out if this fails .
if ( applyWithEntry ( entry . key , entry , false ) == null ) { rehashedOk = false ; break ; } } } } while ( ! rehashedOk ) ;


signature:
public class SequentialCuckooFunction { /** * Implements Robert Jenkins ' 32 - bit integer hash function . < a
 * href = " http : / / www . concentric . net / ~ Ttwang / tech / inthash . htm " / > http : / / www . concentric . net / ~ Ttwang / tech / inthash . htm < / a >
 * @ param key The integer to compute a hash of .
 * @ return A hash of the integer . */
private int hash1 ( int key ) { } }


signature:
public class SequentialCuckooFunction { /** * Thomas Wang ' s 32 - bit shift hash function . < a href = " http : / / www . concentric . net / ~ Ttwang / tech / inthash . htm " / >
 * http : / / www . concentric . net / ~ Ttwang / tech / inthash . htm < / a >
 * @ param key The integer to compute a hash of .
 * @ return A hash of the integer . */
private int hash32shift ( int key ) { } }

implementation: key += hash2seed ; key = ~ key + ( key << 15 ) ; key = key ^ ( key >>> 12 ) ; key = key + ( key << 2 ) ; key = key ^ ( key >>> 4 ) ; key = key * 2057 ; key = key ^ ( key >>> 16 ) ; return key ;


signature:
public class SequentialCuckooFunction { /** * Implements a secondary hash . This uses the 32 - bit shift hash implemented by { @ link # hash32shift ( int ) } and then
 * successively applies { @ link # hash1 ( int ) } if the generated hash code is not different to the hash code generated
 * by running { @ link # hash1 ( int ) } on the key . This ensures that the hash code returned by this will be different to
 * the one generated by { @ link # hash1 ( int ) } .
 * @ param hash1 The output of the hash1 function .
 * @ param key The integer to compute a hash of .
 * @ return A hash of the integer which is different to that generated by { @ link # hash1 ( int ) } . */
private int hash2 ( int hash1 , int key ) { } }

implementation: key = hash32shift ( key ) ; while ( key == hash1 ) { key = hash32shift ( key ) ; } return key ;


signature:
public class FillViewportLayout { /** * { @ inheritDoc } */
public void layoutContainer ( Container parent ) { } }

implementation: JViewport vp = ( JViewport ) parent ; Component view = vp . getView ( ) ; if ( view == null ) { return ; } Point viewPosition = vp . getViewPosition ( ) ; Dimension viewPrefSize = view . getPreferredSize ( ) ; Dimension vpSize = vp . getSize ( ) ; Dimension viewSize = new Dimension ( viewPrefSize ) ; if ( ( viewPosition . x == 0 ) && ( vpSize . width > viewPrefSize . width ) ) { viewSize . width = vpSize . width ; } if ( ( viewPosition . y == 0 ) && ( vpSize . height > viewPrefSize . height ) ) { viewSize . height = vpSize . height ; } if ( ! viewSize . equals ( viewPrefSize ) ) { vp . setViewSize ( viewSize ) ; }


signature:
public class WorkPanel { /** * Listens for the button events Ok , Cancel and Apply . If the event is Ok or Apply the saveWork method is triggered .
 * If the event is Cancel then the discardWork method is triggered .
 * @ param event The work panel event , ignored if it is not one of " Ok " , " Cancel " or " Apply " . */
public void actionPerformed ( ActionEvent event ) { } }

implementation:
/* log . fine ( " void actionPerformed ( ActionEvent ) : called " ) ; */
/* log . fine ( " Action is " + event . getActionCommand ( ) ) ; */
// Check which action was performed
String action = event . getActionCommand ( ) ; if ( "OK" . equals ( action ) ) { // Check if the state is NOT _ SAVED
if ( state . getState ( ) . equals ( WorkPanelState . NOT_SAVED ) ) { // Save the work
saveWork ( ) ; } } else if ( "Cancel" . equals ( action ) ) { // Check if the state is NOT _ SAVED
if ( state . getState ( ) . equals ( WorkPanelState . NOT_SAVED ) ) { // Discard the work
discardWork ( ) ; } } else if ( "Apply" . equals ( action ) ) { // Check if the state is NOT _ SAVED
if ( state . getState ( ) . equals ( WorkPanelState . NOT_SAVED ) ) { // Save the work
saveWork ( ) ; } }


signature:
public class WorkFlowScreenState { /** * Sets the state of the next available flag and notifies any listeners of this change .
 * @ param avail The next page available state . */
public void setNextAvailable ( boolean avail ) { } }

implementation:
// Check if the state has changed
if ( nextAvailable != avail ) { // Keep the new state
nextAvailable = avail ; // Notify any listeners fo the change in state
firePropertyChange ( new PropertyChangeEvent ( this , "nextAvailable" , ! avail , avail ) ) ; }


signature:
public class WorkFlowScreenState { /** * Sets the state of the previous available flag and notifies any listeners of this change .
 * @ param avail The previous page available state . */
public void setPrevAvailable ( boolean avail ) { } }

implementation:
// Check if the state has changed
if ( prevAvailable != avail ) { // Keep the new state
prevAvailable = avail ; // Notify any listeners fo the change in state
firePropertyChange ( new PropertyChangeEvent ( this , "prevAvailable" , ! avail , avail ) ) ; }


signature:
public class WorkFlowScreenState { /** * Sets the state of the finished and notifies any listeners of this change .
 * @ param avail The work flow completed state . */
public void setFinished ( boolean avail ) { } }

implementation:
/* log . fine ( " void setFinished ( boolean ) : called " ) ; */
// Check if the state has changed
if ( finished != avail ) { // Keep the new state
finished = avail ; // Notify any listeners fo the change in state
firePropertyChange ( new PropertyChangeEvent ( this , "finished" , ! avail , avail ) ) ; /* log . fine ( " fired property change event " ) ; */
}


signature:
public class WAMResolvingNativeMachine { /** * Creates an instance of this machine , loading and checking for availability of the native implementation library
 * as required .
 * @ param symbolTable The symbol table for the machine .
 * @ return An instance of the native l3 machine .
 * @ throws ImplementationUnavailableException If the native library cannot be loaded and linked . */
public static WAMResolvingNativeMachine getInstance ( SymbolTableImpl < Integer , String , Object > symbolTable ) throws ImplementationUnavailableException { } }

implementation: try { if ( ! libraryLoadAttempted ) { libraryLoadAttempted = true ; System . loadLibrary ( "aima_native" ) ; libraryFound = true ; } if ( libraryFound ) { return new WAMResolvingNativeMachine ( symbolTable ) ; } else { throw new ImplementationUnavailableException ( "The native library could not be found." , null , null , null ) ; } } catch ( UnsatisfiedLinkError e ) { libraryFound = false ; throw new ImplementationUnavailableException ( "The native library could not be found." , e , null , null ) ; }


signature:
public class WAMResolvingNativeMachine { /** * Provides an iterator that generates all solutions on demand as a sequence of variable bindings .
 * @ return An iterator that generates all solutions on demand as a sequence of variable bindings . */
public Iterator < Set < Variable > > iterator ( ) { } }

implementation: return new SequenceIterator < Set < Variable > > ( ) { public Set < Variable > nextInSequence ( ) { return resolve ( ) ; } } ;


signature:
public class InformationTheory { /** * For a given set of probabilities of the occurences of symbols this function calculates the expected information
 * content of a set of symbols given its probability distribution . The answer is expressed as a positive number of
 * bits .
 * < p > The probabilities should add up to one . This method does not provide any kind of check on this condition .
 * @ param probabilities The probability distribution of the symbols . The probabilities should add to one .
 * @ return The expected information content , in bits , learned from being told a symbol drawn from the distribution . */
public static double expectedI ( double [ ] probabilities ) { } }

implementation:
double result = 0.0d ; // Loop over the probabilities for all the symbols calculating the contribution of each to the expected value .
for ( double p : probabilities ) { // Calculate the information in each symbol . I ( p ) = - ln p and weight this by its probability of occurence
// to get that symbols contribution to the expected value over all symbols .
if ( p > 0.0d ) { result -= p * Math . log ( p ) ; } } // Convert the result from nats to bits by dividing by ln 2.
return result / LN2 ;


signature:
public class InformationTheory { /** * Supposing a stream generates pairs of symbols . Let the first be A and the second be G . A ranges over a set of
 * symbols , { h1 , . . . , hv } and G ranges over a set of symbols , { g1 , . . . , gn } .
 * < p > G alone has a probability distribution which tells us what the expected information content of knowing what G
 * is , measured in bits .
 * < p > This remainder function estimates how much more information is needed , if we know A , in order to know G .
 * < p > If A and G are completely independent then this will be equal to the expected information content of G . In
 * other words A tells us nothing about G . If G is completely dependant on A then this will be equal to zero . In
 * other words as we know G already from knowing A , learning what G is will tell us nothing extra .
 * < p > Remainder ( A | G ) = Sum i from 1 to v { P ( hi ) * expectedInformation ( P ( g1 | hi ) , . . . , P ( gn | hi ) } .
 * < p > Where : p ( g | h ) = the probability of symbol g ( of G ) occuring given symbol h ( of A ) .
 * @ param pA The probability distribution of the symbols of A . This will be an array of size v .
 * @ param pGgivenA The probability distribution of the symbols of G given a particular symbol of A . This will be an
 * array of size n by v ( v arrays of size n , array is indexed as [ v ] [ n ] ) .
 * @ return The expected remaining information needed to know G from knowing A . */
public static double remainder ( double [ ] pA , double [ ] [ ] pGgivenA ) { } }

implementation:
double result = 0.0d ; // Loop over the probabilities for all the symbols of A calculating the contribution of each to
// the expected value .
for ( int v = 0 ; v < pA . length ; v ++ ) { double phv = pA [ v ] ; // Calculate the expected information content of the distribution of the symbols of G given the symbol hv
// and scale its contribution to the total by the probability of hv occuring .
result += phv * expectedI ( pGgivenA [ v ] ) ; } // There is no need to convert the result from nats to bits and the expected information function is
// already in bits .
return result ;


signature:
public class InformationTheory { /** * Estimates probabilities given a set of counts of occurrences of symbols .
 * < p > P = number of times a symbol occurs / total number of symbols .
 * @ param counts The counts of the occurrences of symbols over a data set of symbols .
 * @ return An array of the probability estimates for the occurences of the symbols . The index of the elements in
 * this array corresponds with the index of the symbol in the input array . */
public static double [ ] pForDistribution ( int [ ] counts ) { } }

implementation:
double [ ] probabilities = new double [ counts . length ] ; int total = 0 ; // Loop over the counts for all symbols adding up the total number .
for ( int c : counts ) { total += c ; } // Loop over the counts for all symbols dividing by the total number to provide a probability estimate .
for ( int i = 0 ; i < probabilities . length ; i ++ ) { if ( total > 0 ) { probabilities [ i ] = ( ( double ) counts [ i ] ) / total ; } else { probabilities [ i ] = 0.0d ; } } return probabilities ;


signature:
public class InformationTheory { /** * Supposing a stream generates pairs of symbols . Let the first be A and the second be G . A ranges over a set of
 * symbols , { h1 , . . . , hv } and G ranges over a set of symbols , { g1 , . . . , gn } .
 * < p > This function estimates p ( g | h ) , the probability of a symbol g ( of G ) occuring given a symbol h ( of A ) , over
 * all the symbols g and h from statistics gathered about the frequency of occurence of these symbols .
 * @ param counts the counts of the occurence of the symbols of G given a particular symbol of A . This will be an
 * array of size n by v ( v arrays of size n , array is indexed as [ v ] [ n ] ) .
 * @ return an estimate of the probability distribution of the symbols of G given a particular symbol of A . This will
 * be an array of size n by v ( v arrays of size n , array is indexed as [ v ] [ n ] ) . */
public static double [ ] [ ] pForJointDistribution ( int [ ] [ ] counts ) { } }

implementation:
double [ ] [ ] results = new double [ counts . length ] [ ] ; // Loop over all the symbols of A
for ( int i = 0 ; i < counts . length ; i ++ ) { // Extract the next distribution array of the symbols of G given A .
int [ ] countsGgivenA = counts [ i ] ; // Convert the frequency distribution into a probability distribution and add it to the results .
results [ i ] = pForDistribution ( countsGgivenA ) ; } return results ;


signature:
public class LiteralType { /** * { @ inheritDoc } */
public void accept ( TermVisitor visitor ) { } }

implementation: if ( visitor instanceof LiteralTypeVisitor ) { ( ( LiteralTypeVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; }


signature:
public class DateOnly { /** * { @ inheritDoc } */
public int compareTo ( DateOnly o ) { } }

implementation: if ( year < o . year ) { return - 1 ; } else if ( year > o . year ) { return 1 ; } else if ( month < o . month ) { return - 1 ; } else if ( month > o . month ) { return 1 ; } else if ( day < o . day ) { return - 1 ; } else if ( day > o . day ) { return 1 ; } else { return 0 ; }


signature:
public class DateOnly { /** * Sets this date from a milliseconds timestamp .
 * @ param ticks The timestamp . */
void setTicks ( long ticks ) { } }

implementation: year = TimeUtils . ticksToYears ( ticks ) ; month = TimeUtils . ticksToMonths ( ticks ) ; day = TimeUtils . ticksToDate ( ticks ) ;


signature:
public class SelectorNode { /** * Recreate internal state before children are cloned . */
@ Override protected void cloneChildren ( InternalNode node ) { } }

implementation:
SelectorNode selector = ( SelectorNode ) node ; // Reset internal state
selector . setAdditionVisitor ( ) ; super . cloneChildren ( node ) ;


signature:
public class SortAction { /** * Processes the action .
 * @ param mapping The ActionMapping used to select this instance
 * @ param form The optional ActionForm bean for this request ( if any )
 * @ param request The HTTP request .
 * @ param response The HTTP response .
 * @ return A struts forward to the " success " location .
 * @ exception IOException if an input / output error occurs
 * @ exception ServletException if a servlet exception occurs */
public ActionForward perform ( ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { } }

implementation:
log . fine ( "perform: called" ) ; // Reference the SortForm as a SortForm rather than the generic ActionForm
SortForm sortForm = ( SortForm ) form ; // Get a reference to the session scope
HttpSession session = request . getSession ( ) ; // Get a reference to the application scope
ServletContext application = session . getServletContext ( ) ; log . fine ( "variables in the servlet context: " ) ; for ( Enumeration e = application . getAttributeNames ( ) ; e . hasMoreElements ( ) ; ) { log . fine ( e . nextElement ( ) . toString ( ) ) ; } // Get a reference to the list to be sorted
List list = ( List ) session . getAttribute ( sortForm . getList ( ) ) ; // Get a reference to the comparator from the application scope to use to perform the sort
Comparator comparator = ( Comparator ) application . getAttribute ( sortForm . getComparator ( ) ) ; log . fine ( "comparator = " + comparator ) ; // Get a reference to the current sort state ( if there is one )
SortStateBean sortStateBean = ( SortStateBean ) session . getAttribute ( sortForm . getSortState ( ) ) ; // Check if there is no sort state bean and create one if so
if ( sortStateBean == null ) { log . fine ( "There is no sort state bean" ) ; sortStateBean = new SortStateBean ( ) ; } // Determine whether a forward or reverse sort is to be done
// If its reverse sorted , unsorted or not sorted by the current sort property then forward sort it
if ( ! sortStateBean . getState ( ) . equals ( SortStateBean . FORWARD ) || ! sortStateBean . getSortProperty ( ) . equals ( sortForm . getSortStateProperty ( ) ) ) { // Sort the list
Collections . sort ( list , comparator ) ; // Update the current sort state
sortStateBean . setState ( SortStateBean . FORWARD ) ; } // If its already forward sorted then reverse sort it
else { // Sort the list
Collections . sort ( list , comparator ) ; // Reverse the list
Collections . reverse ( list ) ; // Update the current sort state
sortStateBean . setState ( SortStateBean . REVERSE ) ; } // Store the sorted list in the variable from which the original list was taken
session . setAttribute ( sortForm . getList ( ) , list ) ; // Store the new sort state , setting the property that has been sorted by in the sort state
sortStateBean . setSortProperty ( sortForm . getSortStateProperty ( ) ) ; session . setAttribute ( sortForm . getSortState ( ) , sortStateBean ) ; // Forward to the success page
return ( mapping . findForward ( "success" ) ) ;


signature:
public class TokenBucketThrottle { /** * Checks but does not enforce the throttle rate . When this method is called , it checks if a length of time greater
 * than that equal to the inverse of the throttling rate has passed since it was last called and returned < tt >
 * true < / tt > . If the length of time still to elapse to the next throttle allow point is zero or less , this method
 * will return a negative value , if there is still time to pass until the throttle allow point , this method will
 * return a positive value indicating the amount of time still to pass . A thread can wait for that period of time
 * before rechecking the throttle condition .
 * @ return The length of time since or still to elaps to the next throttle allow point . A negative value indicates
 * that the throttle time has passed and a positive time indicates that there is still time to pass before
 * it is reached . The units are in nanoseconds . */
public long timeToThrottleNanos ( ) { } }

implementation:
// Work out how long ago the last throttle query was .
long currentTimeNanos = System . nanoTime ( ) ; long delay = currentTimeNanos - lastTimeNanos ; // Regenerate the tokens allowed since the last query .
float numTokens = ( delay * 1.0e9f ) * targetRate ; tokenCount -= numTokens ; if ( tokenCount < 0f ) { tokenCount = 0f ; } // Update the last time stamp for next time around .
lastTimeNanos = currentTimeNanos ; // Check if there are tokens available to consume , and consume one if so .
if ( tokenCount <= ( depth - 1.0 ) ) { tokenCount += 1.0 ; return 0 ; } else { // There are no tokens to consume , so return an estimate of how long it will take to generate one token .
return ( long ) ( 1.0e9 / targetRate ) ; }


signature:
public class Urls { /** * Creates a URL for the specified string representation .
 * @ param spec
 * the string representation
 * @ return the URL
 * @ throws IllegalArgumentException
 * if the specified string representation is not a valid URL */
public static URL newUrl ( String spec ) { } }

implementation: try { return new URL ( spec ) ; } catch ( MalformedURLException exception ) { throw new IllegalArgumentException ( "Invalid URL: " + spec ) ; }


signature:
public class DebugTag { /** * Returns a String with all basic request information in an HTML table .
 * @ return A String with all basic request information in an HTML table . */
public String getRequestInfo ( ) { } }

implementation: Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; info . put ( "authType" , nullToString ( req . getAuthType ( ) ) ) ; info . put ( "characterEncoding" , nullToString ( req . getCharacterEncoding ( ) ) ) ; info . put ( "contentLength" , Integer . toString ( req . getContentLength ( ) ) ) ; info . put ( "contentType" , nullToString ( req . getContentType ( ) ) ) ; info . put ( "contextPath" , nullToString ( req . getContextPath ( ) ) ) ; info . put ( "pathInfo" , nullToString ( req . getPathInfo ( ) ) ) ; info . put ( "protocol" , nullToString ( req . getProtocol ( ) ) ) ; info . put ( "queryString" , nullToString ( req . getQueryString ( ) ) ) ; info . put ( "remoteAddr" , nullToString ( req . getRemoteAddr ( ) ) ) ; info . put ( "remoteHost" , nullToString ( req . getRemoteHost ( ) ) ) ; info . put ( "remoteUser" , nullToString ( req . getRemoteUser ( ) ) ) ; info . put ( "requestURI" , nullToString ( req . getRequestURI ( ) ) ) ; info . put ( "scheme" , nullToString ( req . getScheme ( ) ) ) ; info . put ( "serverName" , nullToString ( req . getServerName ( ) ) ) ; info . put ( "serverPort" , Integer . toString ( req . getServerPort ( ) ) ) ; info . put ( "servletPath" , nullToString ( req . getServletPath ( ) ) ) ; return toHTMLTable ( "request properties" , info ) ;


signature:
public class DebugTag { /** * Returns a String with all header information as an HTML table .
 * @ return A String with all header information as an HTML table . */
public String getHeaders ( ) { } }

implementation: Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; Enumeration names = req . getHeaderNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Enumeration values = req . getHeaders ( name ) ; StringBuffer sb = new StringBuffer ( ) ; boolean first = true ; while ( values . hasMoreElements ( ) ) { if ( ! first ) { sb . append ( " | " ) ; } first = false ; sb . append ( values . nextElement ( ) ) ; } info . put ( name , sb . toString ( ) ) ; } return toHTMLTable ( "headers" , info ) ;


signature:
public class DebugTag { /** * Returns a String with all cookie information as an HTML table .
 * @ return A String with all cookie information as an HTML table . */
public String getCookies ( ) { } }

implementation:
Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; Cookie [ ] cookies = req . getCookies ( ) ; // check that cookies is not null which it may be if there are no cookies
if ( cookies != null ) { for ( int i = 0 ; i < cookies . length ; i ++ ) { Cookie cooky = cookies [ i ] ; info . put ( cooky . getName ( ) , cooky . getValue ( ) ) ; } } return toHTMLTable ( "cookies" , info ) ;


signature:
public class DebugTag { /** * Returns a String with all request parameter information .
 * @ return A String with all request parameter information . */
public String getParameters ( ) { } }

implementation: Map info = new TreeMap ( ) ; ServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; Enumeration names = req . getParameterNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; String [ ] values = req . getParameterValues ( name ) ; StringBuffer sb = new StringBuffer ( ) ; for ( int i = 0 ; i < values . length ; i ++ ) { if ( i != 0 ) { sb . append ( " | " ) ; } sb . append ( values [ i ] ) ; } info . put ( name , sb . toString ( ) ) ; } return toHTMLTable ( "request parameters" , info ) ;


signature:
public class DebugTag { /** * Returns a String with all request scope variables .
 * @ return A String with all request scope variables . */
public String getRequestScope ( ) { } }

implementation: Map info = new TreeMap ( ) ; ServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; Enumeration names = req . getAttributeNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = req . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( "request scope" , info ) ;


signature:
public class DebugTag { /** * Returns a String with all page scope variables .
 * @ return A String with all page scope variables . */
public String getPageScope ( ) { } }

implementation: Map info = new TreeMap ( ) ; Enumeration names = pageContext . getAttributeNamesInScope ( PageContext . PAGE_SCOPE ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = pageContext . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( "page scope" , info ) ;


signature:
public class DebugTag { /** * Returns a String with all session scope variables .
 * @ return A String with all session scope variables . */
public String getSessionScope ( ) { } }

implementation: Map info = new TreeMap ( ) ; HttpServletRequest req = ( HttpServletRequest ) pageContext . getRequest ( ) ; HttpSession session = req . getSession ( ) ; Enumeration names = session . getAttributeNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = session . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( "session scope" , info ) ;


signature:
public class DebugTag { /** * Returns a String with all application scope variables .
 * @ return A String with all application scope variables . */
public String getApplicationScope ( ) { } }

implementation: Map info = new TreeMap ( ) ; ServletContext context = pageContext . getServletContext ( ) ; Enumeration names = context . getAttributeNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Object value = context . getAttribute ( name ) ; info . put ( name , toStringValue ( value ) ) ; } return toHTMLTable ( "application scope" , info ) ;


signature:
public class DebugTag { /** * Returns the user principal name .
 * @ return The user principal name . */
public String getUserPrincipal ( ) { } }

implementation:
// Create a hash table to hold the results in
Map info = new TreeMap ( ) ; // Extract the request from the page context
HttpServletRequest request = ( HttpServletRequest ) pageContext . getRequest ( ) ; // Get the principal from the request
Principal principal = request . getUserPrincipal ( ) ; // Check if there is a principal
if ( principal != null ) { info . put ( "principal name" , principal . getName ( ) ) ; } else { info . put ( "principal name" , "no principal" ) ; } // Convert the results to an HTML table
return toHTMLTable ( "container security" , info ) ;


signature:
public class DebugTag { /** * Renders the debugging message .
 * @ return The tag return code . Always EVAL _ BODY _ INCLUDE .
 * @ throws JspException If the debug information cannot be written to the page . */
public int doStartTag ( ) throws JspException { } }

implementation:
log . fine ( "doStartTag: called" ) ; try { // Write out the beggining of the debug table
pageContext . getResponse ( ) . getWriter ( ) . write ( "
" ) ; // Write out the debugging info for all categories
pageContext . getResponse ( ) . getWriter ( ) . write ( getRequestInfo ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getHeaders ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getCookies ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getParameters ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getRequestScope ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getPageScope ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getSessionScope ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getApplicationScope ( ) ) ; pageContext . getResponse ( ) . getWriter ( ) . write ( getUserPrincipal ( ) ) ; // Write out the closing of the debug table
pageContext . getResponse ( ) . getWriter ( ) . write ( "
" ) ; } catch ( IOException e ) { throw new JspException ( "Got an IOException whilst writing the debug tag to the page." , e ) ; } // Continue processing the page
return ( EVAL_BODY_INCLUDE ) ;


signature:
public class DebugTag { /** * Returns an HTML table with all the values of the specified property .
 * @ param propName The header for the table .
 * @ param values The key / value paris to display in the table .
 * @ return The HTML table as a string . */
private String toHTMLTable ( String propName , Map values ) { } }

implementation:
StringBuffer tableSB = new StringBuffer ( ) ; tableSB . append ( "
" ) . append ( propName ) . append ( "
" ) ; for ( Iterator it = values . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Object o = it . next ( ) ; String key = ( String ) o ; tableSB . append ( "
" ) . append ( key ) . append ( "	" ) . append ( values . get ( key ) ) . append ( "
" ) ; } return tableSB . toString ( ) ;


signature:
public class DebugTag { /** * Returns a string representation of the specified object , in a format suitable for debug output . If the object is
 * an array all its elements are extracted and displayed seperated by commas . Other objects are converted to strings
 * by their toString methods .
 * @ param value The object value to display as a string .
 * @ return A string representation of the specified object . */
private String toStringValue ( Object value ) { } }

implementation:
// Check if the value is null
if ( value == null ) { return "null" ; } StringBuffer sb = new StringBuffer ( ) ; Class type = value . getClass ( ) ; if ( type . isArray ( ) ) { Class componentType = type . getComponentType ( ) ; sb . append ( componentType . getName ( ) ) ; sb . append ( "[]: {" ) ; if ( ! componentType . isPrimitive ( ) ) { Object [ ] arr = ( Object [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Boolean . TYPE ) { boolean [ ] arr = ( boolean [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Byte . TYPE ) { byte [ ] arr = ( byte [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Character . TYPE ) { char [ ] arr = ( char [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Double . TYPE ) { double [ ] arr = ( double [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Float . TYPE ) { float [ ] arr = ( float [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Integer . TYPE ) { int [ ] arr = ( int [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Long . TYPE ) { long [ ] arr = ( long [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } else if ( componentType == Short . TYPE ) { short [ ] arr = ( short [ ] ) value ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( i != 0 ) { sb . append ( ", " ) ; } sb . append ( arr [ i ] ) ; } } sb . append ( "}" ) ; } else { // Obtain the objects value using toString , but protect this against null pointer exceptions , to harden
// this implementation .
String stringValue = null ; try { stringValue = value . toString ( ) ; } catch ( NullPointerException e ) { stringValue = "" ; } sb . append ( value . getClass ( ) . getName ( ) ) . append ( ": " ) . append ( stringValue ) ; } return sb . toString ( ) ;


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

implementation:
// Initialize the queue with the start states set up in search nodes .
Queue < SearchNode < O , T > > queue = initSearch . enqueueStartStates ( startStates ) ; // Get the goal predicate configured as part of the enqueueing start states process .
UnaryPredicate < T > goalPredicate = initSearch . getGoalPredicate ( ) ; // Flag used to indicate whether there are unexplored successor states known to exist beyond the max depth
// fringe .
boolean beyondFringe = false ; // Reset the minimum beyond the fringe boundary value .
minBeyondBound = Float . POSITIVE_INFINITY ; // Keep running until the queue becomes empty or a goal state is found .
while ( ! queue . isEmpty ( ) ) { // Extract the head element from the queue .
SearchNode < O , T > headNode = peekAtHead ? queue . peek ( ) : queue . remove ( ) ; // Expand the successors into the queue whether the current node is a goal state or not .
// This prepares the queue for subsequent searches , ensuring that goal states do not block
// subsequent goal states that exist beyond them .
// Add the successors to the queue provided that they are below or at the maximum bounded property .
// Get all the successor states .
Queue < SearchNode < O , T > > successors = new LinkedList < SearchNode < O , T > > ( ) ; headNode . expandSuccessors ( successors , reverseEnqueue ) ; // Loop over all the successor states checking how they stand with respect to the bounded property .
for ( SearchNode < O , T > successor : successors ) { // Get the value of the bound property for the successor node .
float boundProperty = boundPropertyExtractor . getBoundProperty ( successor ) ; // Check if the successor is below or on the bound .
if ( boundProperty <= maxBound ) { // Add it to the queue to be searched .
queue . offer ( successor ) ; } // The successor state is above the bound .
else { // Set the flag to indicate that there is at least one search node known to exist beyond the
// bound .
beyondFringe = true ; // Compare to the best minimum beyond the bound property found so far to see if
// this is a new minimum and update the minimum to the new minimum if so .
minBeyondBound = ( boundProperty < minBeyondBound ) ? boundProperty : minBeyondBound ; } } // Get the node to be goal checked , either the head node or the new top of queue , depending on the
// peek at head flag .
SearchNode < O , T > currentNode = peekAtHead ? queue . remove ( ) : headNode ; // Check if the current node is a goal state .
// Only goal check leaves , or nodes already expanded . ( The expanded flag will be set on leaves anyway ) .
if ( currentNode . isExpanded ( ) && goalPredicate . evaluate ( currentNode . getState ( ) ) ) { return currentNode ; } // Check if there is a maximum number of steps limit and increase the step count and check the limit if so .
if ( maxSteps > 0 ) { // Increase the search step count because a goal test was performed .
searchSteps ++ ; // Update the search state with the number of steps taken so far .
initSearch . setStepsTaken ( searchSteps ) ; if ( searchSteps >= maxSteps ) { // The maximum number of steps has been reached , however if the queue is now empty then the search
// has just completed within the maximum . Check if the queue is empty and return null if so .
if ( queue . isEmpty ( ) ) { return null ; } // Quit without a solution as the max number of steps has been reached but because there are still
// more states in the queue then raise a search failure exception .
else { throw new SearchNotExhaustiveException ( "Maximum number of steps reached." , null ) ; } } } } // No goal state was found . Check if there known successors beyond the max depth fringe and if so throw
// a SearchNotExhaustiveException to indicate that the search failed rather than exhausted the search space .
if ( beyondFringe ) { throw new MaxBoundException ( "Max bound reached." , null ) ; } else { // The search space was exhausted so return null to indicate that no goal could be found .
return null ; }


signature:
public class WorkFlowState { /** * Sets the new current screen state and notifies all listeners of the change in screen state .
 * @ param state The current screen state . */
public void setCurrentScreenState ( WorkFlowScreenState state ) { } }

implementation:
/* log . fine ( " void setCurrentScreenState ( WorkFlowScreenState ) : called " ) ; */
WorkFlowScreenState oldState = currentScreenState ; // Keep the new state .
currentScreenState = state ; // Notify all listeners of the change of current screen .
firePropertyChange ( new PropertyChangeEvent ( this , "currentScreenState" , oldState , state ) ) ;


signature:
public class TermWalker { /** * Walks over the supplied term .
 * @ param term The term to walk over . */
public void walk ( Term term ) { } }

implementation:
// Set up the traverser on the term to walk over .
term . setTermTraverser ( traverser ) ; // Create a fresh search starting from the term .
search . reset ( ) ; if ( goalPredicate != null ) { search . setGoalPredicate ( goalPredicate ) ; } search . addStartState ( term ) ; Iterator < Term > treeWalker = Searches . allSolutions ( search ) ; // If the traverser is a term visitor , allow it to visit the top - level term in the walk to establish
// an initial context .
if ( traverser instanceof TermVisitor ) { term . accept ( ( TermVisitor ) traverser ) ; } // Visit every goal node discovered in the walk over the term .
while ( treeWalker . hasNext ( ) ) { Term nextTerm = treeWalker . next ( ) ; nextTerm . accept ( visitor ) ; } // Remote the traverser on the term to walk over .
term . setTermTraverser ( null ) ;


signature:
public class AStarComparator { /** * Compares two heuristic search nodes by their f values .
 * @ param object1 The first heuristic search node to compare .
 * @ param object2 The second heuristic search node to compare .
 * @ return 1 If the first node has a higher f value than the second , 0 if they have the same f value , - 1 if the
 * second has a higher f value than the first . */
public int compare ( SearchNode object1 , SearchNode object2 ) { } }

implementation: float f1 = ( ( HeuristicSearchNode ) object1 ) . getF ( ) ; float f2 = ( ( HeuristicSearchNode ) object2 ) . getF ( ) ; return ( f1 > f2 ) ? 1 : ( ( f1 < f2 ) ? - 1 : 0 ) ;


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

implementation: List < PropertyChangeEvent > changes = delta ( this , registers ) ; ip = registers . ip ; hp = registers . hp ; hbp = registers . hbp ; sp = registers . sp ; up = registers . up ; ep = registers . ep ; bp = registers . bp ; b0 = registers . b0 ; trp = registers . trp ; writeMode = registers . writeMode ; notifyChanges ( changes ) ;


signature:
public class InternalRegisterBean { /** * 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 ( WAMInternalRegisters oldRegisters , WAMInternalRegisters newRegisters ) { } }

implementation: List < PropertyChangeEvent > result = new LinkedList < PropertyChangeEvent > ( ) ; if ( oldRegisters . ip != newRegisters . ip ) { result . add ( new PropertyChangeEvent ( this , "IP" , oldRegisters . ip , newRegisters . ip ) ) ; } if ( oldRegisters . hp != newRegisters . hp ) { result . add ( new PropertyChangeEvent ( this , "HP" , oldRegisters . hp , newRegisters . hp ) ) ; } if ( oldRegisters . hbp != newRegisters . hbp ) { result . add ( new PropertyChangeEvent ( this , "HBP" , oldRegisters . hbp , newRegisters . hbp ) ) ; } if ( oldRegisters . sp != newRegisters . sp ) { result . add ( new PropertyChangeEvent ( this , "SP" , oldRegisters . sp , newRegisters . sp ) ) ; } if ( oldRegisters . up != newRegisters . up ) { result . add ( new PropertyChangeEvent ( this , "UP" , oldRegisters . up , newRegisters . up ) ) ; } if ( oldRegisters . ep != newRegisters . ep ) { result . add ( new PropertyChangeEvent ( this , "EP" , oldRegisters . ep , newRegisters . ep ) ) ; } if ( oldRegisters . bp != newRegisters . bp ) { result . add ( new PropertyChangeEvent ( this , "BP" , oldRegisters . bp , newRegisters . bp ) ) ; } if ( oldRegisters . b0 != newRegisters . b0 ) { result . add ( new PropertyChangeEvent ( this , "B0" , oldRegisters . b0 , newRegisters . b0 ) ) ; } if ( oldRegisters . trp != newRegisters . trp ) { result . add ( new PropertyChangeEvent ( this , "TRP" , oldRegisters . trp , newRegisters . trp ) ) ; } if ( oldRegisters . writeMode != newRegisters . writeMode ) { result . add ( new PropertyChangeEvent ( this , "writeMode" , oldRegisters . writeMode , newRegisters . writeMode ) ) ; } return result ;


signature:
public class InternalRegisterBean { /** * Fires off a list of property change events to any interested listeners .
 * @ param changes The list of property changes to fire off . */
private void notifyChanges ( Iterable < PropertyChangeEvent > changes ) { } }

implementation: List < PropertyChangeListener > activeListeners = listeners . getActiveListeners ( ) ; if ( activeListeners != null ) { for ( PropertyChangeListener listener : activeListeners ) { for ( PropertyChangeEvent event : changes ) { listener . propertyChange ( event ) ; } } }


signature:
public class NestedTextGridImpl { /** * { @ inheritDoc } */
public void insert ( char character , int c , int r ) { } }

implementation: parent . insert ( character , c + column , r + row ) ;


signature:
public class NestedTextGridImpl { /** * { @ inheritDoc } */
public void insert ( String string , int c , int r ) { } }

implementation: parent . insert ( string , c + column , r + row ) ;


signature:
public class NestedTextGridImpl { /** * { @ inheritDoc } */
public TextGridModel createInnerGrid ( int c , int r , int w , int h ) { } }

implementation: return parent . createInnerGrid ( c + column , r + row , w , h ) ;


signature:
public class NestedTextGridImpl { /** * { @ inheritDoc } */
public TextTableModel createTable ( int c , int r , int w , int h ) { } }

implementation: return parent . createTable ( c + column , r + row , w , h ) ;


signature:
public class PositionAndOccurrenceVisitor { /** * { @ inheritDoc }
 * < p / > Counts variable occurrences and detects if the variable ever appears in an argument position . */
protected void enterVariable ( Variable variable ) { } }

implementation:
// Initialize the count to one or add one to an existing count .
Integer count = ( Integer ) symbolTable . get ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_OCCURRENCE_COUNT ) ; count = ( count == null ) ? 1 : ( count + 1 ) ; symbolTable . put ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_OCCURRENCE_COUNT , count ) ; /* log . fine ( " Variable " + variable + " has count " + count + " . " ) ; */
// Get the nonArgPosition flag , or initialize it to true .
Boolean nonArgPositionOnly = ( Boolean ) symbolTable . get ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_NON_ARG ) ; nonArgPositionOnly = ( nonArgPositionOnly == null ) ? true : nonArgPositionOnly ; // Clear the nonArgPosition flag if the variable occurs in an argument position .
nonArgPositionOnly = inTopLevelFunctor ( traverser ) ? false : nonArgPositionOnly ; symbolTable . put ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_NON_ARG , nonArgPositionOnly ) ; /* log . fine ( " Variable " + variable + " nonArgPosition is " + nonArgPositionOnly + " . " ) ; */
// If in an argument position , record the parent body functor against the variable , as potentially being
// the last one it occurs in , in a purely argument position .
// If not in an argument position , clear any parent functor recorded against the variable , as this current
// last position of occurrence is not purely in argument position .
if ( inTopLevelFunctor ( traverser ) ) { symbolTable . put ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_LAST_ARG_FUNCTOR , topLevelBodyFunctor ) ; } else { symbolTable . put ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VAR_LAST_ARG_FUNCTOR , null ) ; }


signature:
public class PositionAndOccurrenceVisitor { /** * { @ inheritDoc }
 * < p / > Checks if a constant ever appears in an argument position .
 * < p / > Sets the ' inTopLevelFunctor ' flag , whenever the traversal is directly within a top - level functors arguments .
 * This is set at the end , so that subsequent calls to this will pick up the state of this flag at the point
 * immediately below a top - level functor . */
protected void enterFunctor ( Functor functor ) { } }

implementation:
/* log . fine ( " Functor : " + functor . getName ( ) + " < - " + symbolTable . getSymbolKey ( functor . getName ( ) ) ) ; */
// Only check position of occurrence for constants .
if ( functor . getArity ( ) == 0 ) { // Add the constant to the set of all constants encountered .
List < SymbolKey > constantSymKeys = constants . get ( functor . getName ( ) ) ; if ( constantSymKeys == null ) { constantSymKeys = new LinkedList < SymbolKey > ( ) ; constants . put ( functor . getName ( ) , constantSymKeys ) ; } constantSymKeys . add ( functor . getSymbolKey ( ) ) ; // If the constant ever appears in argument position , take note of this .
if ( inTopLevelFunctor ( traverser ) ) { argumentConstants . add ( functor . getName ( ) ) ; } } // Keep track of the current top - level body functor .
if ( isTopLevel ( traverser ) && ! traverser . isInHead ( ) ) { topLevelBodyFunctor = functor ; }


signature:
public class PositionAndOccurrenceVisitor { /** * Upon leaving the clause , sets the nonArgPosition flag on any constants that need it .
 * @ param clause The clause being left . */
protected void leaveClause ( Clause clause ) { } }

implementation:
// Remove the set of constants appearing in argument positions , from the set of all constants , to derive
// the set of constants that appear in non - argument positions only .
constants . keySet ( ) . removeAll ( argumentConstants ) ; // Set the nonArgPosition flag on all symbol keys for all constants that only appear in non - arg positions .
for ( List < SymbolKey > symbolKeys : constants . values ( ) ) { for ( SymbolKey symbolKey : symbolKeys ) { symbolTable . put ( symbolKey , SymbolTableKeys . SYMKEY_FUNCTOR_NON_ARG , true ) ; } }


signature:
public class PositionAndOccurrenceVisitor { /** * Checks if the current position is immediately within a top - level functor .
 * @ param context The position context to examine .
 * @ return < tt > true < / tt > iff the current position is immediately within a top - level functor . */
private boolean inTopLevelFunctor ( PositionalContext context ) { } }

implementation: PositionalContext parentContext = context . getParentContext ( ) ; return parentContext . isTopLevel ( ) || isTopLevel ( parentContext ) ;


signature:
public class PositionAndOccurrenceVisitor { /** * 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 .
 * @ param context The position context to examine .
 * @ return < tt > true < / tt > iff the current position is a top - level functor . */
private boolean isTopLevel ( PositionalContext context ) { } }

implementation: Term term = context . getTerm ( ) ; if ( term . getSymbolKey ( ) == null ) { return false ; } Boolean isTopLevel = ( Boolean ) symbolTable . get ( term . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_TOP_LEVEL_FUNCTOR ) ; return ( isTopLevel == null ) ? false : isTopLevel ;


signature:
public class AbstractHeap { /** * Adds all of the elements in the specified collection to this heap . Attempts to addAll of a queue to itself result
 * in < tt > IllegalArgumentException < / tt > . Further , the behavior of this operation is undefined if the specified
 * collection is modified while the operation is in progress .
 * < p > This implementation iterates over the specified collection , and adds each element returned by the iterator to
 * this collection , in turn . A runtime exception encountered while trying to add an element ( including , in
 * particular , a < tt > null < / tt > element ) may result in only some of the elements having been successfully added when
 * the associated exception is thrown .
 * @ param collection collection whose elements are to be added to this collection .
 * @ return < tt > true < / tt > if this collection changed as a result of the call .
 * @ throws NullPointerException if the specified collection or any of its elements are null .
 * @ throws IllegalArgumentException if collection is this queue .
 * @ see # add ( Object ) */
public boolean addAll ( Collection < ? extends E > collection ) { } }

implementation: if ( collection == null ) { throw new IllegalArgumentException ( "The 'collection' parameter may not be null." ) ; } if ( collection == this ) { throw new IllegalArgumentException ( ) ; } boolean modified = false ; for ( E aC : collection ) { if ( add ( aC ) ) { modified = true ; } } return modified ;


signature:
public class AbstractHeap { /** * Removes a single instance of the specified element from this heap , if it is present . ( optional operation ) . More
 * formally , removes an element < tt > e < / tt > such that < tt > ( o = = null ? e = = null : o . equals ( e ) ) < / tt > , if the collection
 * contains one or more such elements . Returns < tt > true < / tt > if the collection contained the specified element ( or
 * equivalently , if the collection changed as a result of the call ) .
 * < p > This implementation iterates over the collection looking for the specified element . If it finds the element ,
 * it removes the element from the collection using the iterator ' s remove method .
 * < p > Note that this implementation throws an < tt > UnsupportedOperationException < / tt > if the iterator returned by
 * this collection ' s iterator method does not implement the < tt > remove < / tt > method and this collection contains the
 * specified object .
 * @ param o element to be removed from this collection , if present .
 * @ return < tt > true < / tt > if the collection contained the specified element .
 * @ throws UnsupportedOperationException if the < tt > remove < / tt > method is not supported by this collection . */
public boolean remove ( Object o ) { } }

implementation: Iterator < E > e = iterator ( ) ; if ( o == null ) { while ( e . hasNext ( ) ) { if ( e . next ( ) == null ) { e . remove ( ) ; return true ; } } } else { while ( e . hasNext ( ) ) { if ( o . equals ( e . next ( ) ) ) { e . remove ( ) ; return true ; } } } return false ;


signature:
public class AbstractHeap { /** * Returns an array containing all of the elements in this heap . If the collection makes any guarantees as to what
 * order its elements are returned by its iterator , this method must return the elements in the same order . The
 * returned array will be " safe " in that no references to it are maintained by the collection . ( In other words , this
 * method must allocate a new array even if the collection is backed by an Array ) . The caller is thus free to modify
 * the returned array .
 * < p > This implementation allocates the array to be returned , and iterates over the elements in the collection ,
 * storing each object reference in the next consecutive element of the array , starting with element 0.
 * @ return an array containing all of the elements in this collection . */
public Object [ ] toArray ( ) { } }

implementation: Object [ ] result = new Object [ size ( ) ] ; Iterator < E > e = iterator ( ) ; for ( int i = 0 ; e . hasNext ( ) ; i ++ ) { result [ i ] = e . next ( ) ; } return result ;


signature:
public class AbstractHeap { /** * Returns an array containing all of the elements in this heap ; the runtime type of the returned array is that of
 * the specified array . If the collection fits in the specified array , it is returned therein . Otherwise , a new
 * array is allocated with the runtime type of the specified array and the size of this collection .
 * < p > If the collection fits in the specified array with room to spare ( i . e . , the array has more elements than the
 * collection ) , the element in the array immediately following the end of the collection is set to < tt > null < / tt > .
 * This is useful in determining the length of the collection < i > only < / i > if the caller knows that the collection
 * does not contain any < tt > null < / tt > elements . )
 * < p > If this collection makes any guarantees as to what order its elements are returned by its iterator , this
 * method must return the elements in the same order .
 * < p > This implementation checks if the array is large enough to contain the collection ; if not , it allocates a new
 * array of the correct size and type ( using reflection ) . Then , it iterates over the collection , storing each object
 * reference in the next consecutive element of the array , starting with element 0 . If the array is larger than the
 * collection , a < tt > null < / tt > is stored in the first location after the end of the collection .
 * @ param a The array into which the elements of the collection are to be stored , if it is big enough ; otherwise ,
 * a new array of the same runtime type is allocated for this purpose .
 * @ param < T > The type of the array .
 * @ return an array containing the elements of the collection .
 * @ throws NullPointerException if the specified array is < tt > null < / tt > .
 * @ throws ArrayStoreException if the runtime type of the specified array is not a supertype of the runtime type of
 * every element in this collection . */
public < T > T [ ] toArray ( T [ ] a ) { } }

implementation: int size = size ( ) ; if ( a . length < size ) { a = ( T [ ] ) java . lang . reflect . Array . newInstance ( a . getClass ( ) . getComponentType ( ) , size ) ; } Iterator < E > it = iterator ( ) ; Object [ ] result = a ; for ( int i = 0 ; i < size ; i ++ ) { result [ i ] = it . next ( ) ; } if ( a . length > size ) { a [ size ] = null ; } return a ;


signature:
public class LifoStack { /** * Provides a look at the last object placed on the stack , since it will be the first one out . This method does not
 * change the contents of the stack . Because this class is unsynchronized , applications using this class are
 * responsible for making sure that a < CODE > peek ( ) < / CODE > followed by a < CODE > pop ( ) < / CODE > returns the same value .
 * @ return the object on the top of the stack */
public E peek ( ) { } }

implementation: int last = size ( ) - 1 ; E ob ; if ( last == - 1 ) { return null ; } ob = get ( last ) ; return ob ;


signature: public class JsoupMicrobrowser { public MicrodataDocument get ( String url ) { } }

implementation: newUrl ( url ) ; try { Response response = Jsoup . connect ( url ) . method ( Method . GET ) . ignoreHttpErrors ( true ) . execute ( ) ; return new JsoupMicrodataDocument ( Collections . < String , String > emptyMap ( ) , response ) ; } catch ( IOException exception ) { throw new MicrobrowserException ( "Error fetching page: " + url , exception ) ; }


signature:
public class Predicate { /** * { @ inheritDoc } */
public void accept ( TermVisitor visitor ) { } }

implementation: if ( visitor instanceof PredicateVisitor ) { ( ( PredicateVisitor ) visitor ) . visit ( this ) ; } else { super . accept ( visitor ) ; }


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

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


signature:
public class OpSymbol { /** * Sets the arguments of this operator . It can be convenient to be able to set the outside of the constructor , for
 * example , when parsing may want to create the operator first and fill in its arguments later .
 * @ param arguments The arguments the operator is applied to . */
public void setArguments ( Term [ ] arguments ) { } }

implementation:
// Check that there is at least one and at most two arguments .
if ( ( arguments == null ) || ( arguments . length < 1 ) || ( arguments . length > 2 ) ) { throw new IllegalArgumentException ( "An operator has minimum 1 and maximum 2 arguments." ) ; } this . arguments = arguments ; this . arity = arguments . length ;


signature:
public class OpSymbol { /** * Provides the symbols fixity , derived from its associativity .
 * @ return The symbols fixity . */
public Fixity getFixity ( ) { } }

implementation: switch ( associativity ) { case FX : case FY : return Fixity . Pre ; case XF : case YF : return Fixity . Post ; case XFX : case XFY : case YFX : return Fixity . In ; default : throw new IllegalStateException ( "Unknown associativity." ) ; }


signature:
public class OpSymbol { /** * Reports whether this operator is an infix operator .
 * @ return < tt > true < tt > if this operator is an infix operator . */
public boolean isInfix ( ) { } }

implementation: return ( ( associativity == Associativity . XFY ) || ( associativity == Associativity . YFX ) || ( associativity == Associativity . XFX ) ) ;


signature:
public class OpSymbol { /** * Compares this object with the specified object for order , providing a negative integer , zero , or a positive
 * integer as this symbols priority is less than , equal to , or greater than the comparator . If this symbol is ' less '
 * than another that means that it has a lower priority value , which means that it binds more tightly .
 * @ param o The object to be compared with .
 * @ return A negative integer , zero , or a positive integer as this symbols priority is less than , equal to , or
 * greater than the comparator . */
public int compareTo ( Object o ) { } }

implementation: OpSymbol opSymbol = ( OpSymbol ) o ; return ( priority < opSymbol . priority ) ? - 1 : ( ( priority > opSymbol . priority ) ? 1 : 0 ) ;


signature:
public class WorkFlowButtonsPanel { /** * Called when a property in the work flow state is changed .
 * @ param event The property change event . */
public void propertyChange ( PropertyChangeEvent event ) { } }

implementation:
/* log . fine ( " void propertyChange ( PropertyChangeEvent ) : called " ) ; */
/* log . fine ( " source class = " + event . getSource ( ) . getClass ( ) ) ; */
/* log . fine ( " source object = " + event . getSource ( ) ) ; */
/* log . fine ( " property name = " + event . getPropertyName ( ) ) ; */
/* log . fine ( " new value = " + event . getNewValue ( ) ) ; */
/* log . fine ( " old value = " + event . getOldValue ( ) ) ; */
Object source = event . getSource ( ) ; Object oldValue = event . getOldValue ( ) ; String propertyName = event . getPropertyName ( ) ; // Check if the event source is an individual screen state
if ( source instanceof WorkFlowScreenState ) { WorkFlowScreenState wfsState = ( WorkFlowScreenState ) source ; // Update the buttons to reflect the change in screen state
updateButtonsForScreen ( wfsState ) ; } // Check if the event source is the whole work flow
if ( source instanceof WorkFlowState ) { WorkFlowState wfState = ( WorkFlowState ) source ; // Check if the event cause is a change in current screen
if ( "currentScreenState" . equals ( propertyName ) ) { WorkFlowScreenState newScreenState = wfState . getCurrentScreenState ( ) ; WorkFlowScreenState oldScreenState = ( WorkFlowScreenState ) oldValue ; // De - register this as a listener for the old current screen state
if ( oldScreenState != null ) { oldScreenState . removePropertyChangeListener ( this ) ; } // Register this as a listener for the new current screen state
if ( newScreenState != null ) { newScreenState . addPropertyChangeListener ( this ) ; } // Update the buttons to reflect the current screen state
updateButtonsForScreen ( newScreenState ) ; } // Check if the event cause is a change in the work flow state
else if ( "state" . equals ( propertyName ) ) { // Update the buttons to reflect the change in state
updateButtonsForWorkFlow ( wfState ) ; } }


signature:
public class WorkFlowButtonsPanel { /** * Updates the buttons enabled / disabled status to reflect the current screen state .
 * @ param state The new work flow screen state . */
public void updateButtonsForScreen ( WorkFlowScreenState state ) { } }

implementation:
// Check if it is in the READY or NOT _ SAVED state
if ( state . getState ( ) . equals ( WorkFlowScreenState . READY ) || state . getState ( ) . equals ( WorkFlowScreenState . NOT_SAVED ) ) { backButton . setEnabled ( state . isPrevAvailable ( ) ) ; nextButton . setEnabled ( state . isNextAvailable ( ) ) ; finishButton . setEnabled ( state . isFinished ( ) ) ; } // Check if it is in the NOT _ INITIALIZED state
if ( state . getState ( ) . equals ( WorkFlowScreenState . NOT_INITIALIZED ) ) { backButton . setEnabled ( false ) ; nextButton . setEnabled ( false ) ; finishButton . setEnabled ( false ) ; }


signature:
public class WorkFlowButtonsPanel { /** * Updates the buttons enabled / disabled status to reflect the current work flow state .
 * @ param state The new work flow state . */
public void updateButtonsForWorkFlow ( WorkFlowState state ) { } }

implementation:
// Check if it is in the NOT _ INITIALIZED state
if ( state . getState ( ) . equals ( WorkFlowState . NOT_INITIALIZED ) ) { backButton . setEnabled ( false ) ; nextButton . setEnabled ( false ) ; finishButton . setEnabled ( false ) ; cancelButton . setEnabled ( false ) ; } // Check if it is in the READY state
if ( state . getState ( ) . equals ( WorkFlowState . READY ) ) { finishButton . setEnabled ( false ) ; cancelButton . setEnabled ( true ) ; // Update buttons for the current screen state
updateButtonsForScreen ( state . getCurrentScreenState ( ) ) ; } // Check if it is in the NOT _ SAVED state
if ( state . getState ( ) . equals ( WorkFlowState . NOT_SAVED ) ) { finishButton . setEnabled ( true ) ; cancelButton . setEnabled ( true ) ; }


signature:
public class WorkFlowButtonsPanel { /** * Registers the work flow button panel with the specified work flow controller . This will cause the work flow
 * controller to receive button press events from the panel and register the button panel to receive state changes
 * from the underlying work flow model .
 * @ param controller The work flow controller to recieve work flow events from . */
public void registerWorkFlowController ( WorkFlowController controller ) { } }

implementation:
// Set the work flow controller to listen for button events
backButton . addActionListener ( controller ) ; nextButton . addActionListener ( controller ) ; finishButton . addActionListener ( controller ) ; cancelButton . addActionListener ( controller ) ; // Register this to listen for changes to the work flow state
controller . getWorkFlowState ( ) . addPropertyChangeListener ( this ) ; // Register this to listen for changes to the state for the current screen if it is not null
WorkFlowScreenState currentScreenState = controller . getWorkFlowState ( ) . getCurrentScreenState ( ) ; if ( currentScreenState != null ) { currentScreenState . addPropertyChangeListener ( this ) ; }


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

implementation:
Functor goalTerm = state . getGoalStack ( ) . peek ( ) . getFunctor ( ) ; Functor matchTerm = state . getCurrentClause ( ) . getHead ( ) ; // This is used to record variables bound on the domain side of the unificiation . This information seems
// like is does not need to be kept because usually all of these bindings are in the stack frame .
// However , this is not always the case as unification can capture a variable on the domain side .
// These variables need to be unbound on backtracking too .
List < Variable > domainVariables = new LinkedList < Variable > ( ) ; // This is used to record variables bound on the query goal side of the unification . This information
// must be kept so that the undo operation can unbind these variables before placing the goal back
// onto the stack when backtracking .
List < Variable > boundVariables = new LinkedList < Variable > ( ) ; // Unify the current query goal with the possibly matching clause , creating variable bindings .
boolean matched = state . getUnifier ( ) . unifyInternal ( goalTerm , matchTerm , boundVariables , domainVariables ) ; // Even if unification fails , any partial bindings created are remembered , to ensure that they are cleaned
// up when this proof steps state is undone .
for ( Variable binding : boundVariables ) { state . getVariableBindings ( ) . offer ( binding ) ; } for ( Variable binding : domainVariables ) { state . getVariableBindings ( ) . offer ( binding ) ; } // If the unification succeeded , establish a new state with the unified query removed from the goal stack , the
// body of the unified with clause added to it for resolution , and the variable binding trail extended with
// any additional bindings resulting from the unification .
if ( matched ) { if ( TRACE ) { /* trace . fine ( state . getTraceIndenter ( ) . generateTraceIndent ( ) + " Unify " +
 goalTerm . toString ( state . getInterner ( ) , true , true ) + " against " +
 matchTerm . toString ( state . getInterner ( ) , true , true ) + " , ok . " ) ; */
} // Consume the successfully unified goal from the goal stack .
state . getGoalStack ( ) . poll ( ) ; // Add all functors on the body side of the unified clause onto the goal stack for resolution .
Functor [ ] body = state . getCurrentClause ( ) . getBody ( ) ; if ( ( body != null ) && ( body . length != 0 ) ) { // The new goals are placed onto the goal stack backwards . It is a stack , hence they get
// explored first , depth first , but their insertion order is reversed for an intuitive
// left - to - right evaluation order .
for ( int i = body . length - 1 ; i >= 0 ; i -- ) { BuiltInFunctor newGoal = state . getBuiltInTransform ( ) . apply ( body [ i ] ) ; newGoal . setParentChoicePointState ( state . getLastChoicePoint ( ) ) ; state . getGoalStack ( ) . offer ( newGoal ) ; } } return true ; } else { if ( TRACE ) { /* trace . fine ( state . getTraceIndenter ( ) . generateTraceIndent ( ) + " Failed to unify " +
 goalTerm . toString ( state . getInterner ( ) , true , true ) + " against " +
 matchTerm . toString ( state . getInterner ( ) , true , true ) + " . " ) ; */
} return false ; }


signature:
public class EnumAttribute { /** * Generates a factory for building enum attributes of the specified enum class .
 * @ param cls The class type of enum to get an enum attribute factory for .
 * @ return The enum attribute factory for the enum class type specified . */
public static EnumAttributeFactory getFactoryForClass ( Class cls ) { } }

implementation:
// Check that the requested class is actually an enum .
if ( ! cls . isEnum ( ) ) { throw new IllegalArgumentException ( "Can only create enum attribute factories for classes that are enums." ) ; } return EnumClassImpl . getInstance ( cls ) ;


signature:
public class RowBackgroundColorDelta { /** * { @ inheritDoc }
 * < p / > Applies color changes to the background of a row . */
public void changeColor ( C color ) { } }

implementation: AttributeSet aset = new AttributeSet ( ) ; aset . put ( AttributeSet . BACKGROUND_COLOR , color ) ; grid . insertRowAttribute ( aset , row ) ;


signature:
public class ComponentFactoryBuilder { /** * Creates an instance of the named component factory .
 * @ param className The name of the component factory class to instantiate .
 * @ return An instance of the named component factory . */
public static ComponentFactory createComponentFactory ( String className ) { } }

implementation: return ( ComponentFactory ) ReflectionUtils . newInstance ( ReflectionUtils . forName ( className ) ) ;


signature:
public class StackVariable { /** * Provides the storage cell for the specified variable . Some types of variable may defer their storage onto a
 * storage cell other than themselves , other variable types may simply return themselves as their own storage cells .
 * @ param variable The variable to get the storage cell for .
 * @ return The storage cell where the specified variable sets its bindings , or < tt > null < / tt > if none has been
 * established . */
public Variable getStorageCell ( Variable variable ) { } }

implementation: VariableBindingContext < Variable > context = getBindingContext ( ) ; if ( context == null ) { return null ; } else { return context . getStorageCell ( this ) ; }


signature:
public class StackVariable { /** * Reports whether or not this variable is bound to a value .
 * @ return < tt > true < / tt > if this variable has been assigned a value , < tt > false < / tt > otherwise . */
public boolean isBound ( ) { } }

implementation:
VariableBindingContext < Variable > context = getBindingContext ( ) ; // The variable can only be bound if it has a binding context and is bound in that context .
return ( context != null ) && context . getStorageCell ( this ) . isBound ( ) ;


signature:
public class AttributeGridImpl { /** * { @ inheritDoc } */
public AttributeSet getAttributeAt ( int c , int r ) { } }

implementation: AttributeSet attributeSet = cellAttributes . get ( ( long ) c , ( long ) r ) ; attributeSet = ( attributeSet == null ) ? getColumnAttributeOrNull ( c ) : attributeSet ; attributeSet = ( attributeSet == null ) ? getRowAttributeOrNull ( r ) : attributeSet ; return attributeSet ;


signature:
public class AttributeGridImpl { /** * Sets a column attribute , adding padding to the underlying array as necessary to ensure it is large enough to hold
 * the attribute at the requested position .
 * @ param attributes The attribute to set .
 * @ param c The column to set it on . */
private void setColumnAttribute ( AttributeSet attributes , int c ) { } }

implementation: if ( c >= columnAttributes . size ( ) ) { for ( int i = columnAttributes . size ( ) ; i <= c ; i ++ ) { columnAttributes . add ( null ) ; } } columnAttributes . set ( c , attributes ) ;


signature:
public class AttributeGridImpl { /** * Sets a row attribute , adding padding to the underlying array as necessary to ensure it is large enough to hold
 * the attribute at the requested position .
 * @ param attributes The attribute to set .
 * @ param r The row to set it on . */
private void setRowAttribute ( AttributeSet attributes , int r ) { } }

implementation: if ( r >= rowAttributes . size ( ) ) { for ( int i = rowAttributes . size ( ) ; i <= r ; i ++ ) { rowAttributes . add ( null ) ; } } rowAttributes . set ( r , attributes ) ;


signature:
public class AttributeGridImpl { /** * Gets a columns attribute if possible , without overflowing the underlying array .
 * @ param c The column to get the attributes for .
 * @ return The column attributes or < tt > null < / tt > if none are set . */
private AttributeSet getColumnAttributeOrNull ( int c ) { } }

implementation: if ( ( c >= 0 ) && ( c < columnAttributes . size ( ) ) ) { return columnAttributes . get ( c ) ; } else { return null ; }


signature:
public class AttributeGridImpl { /** * Gets a rows attribute if possible , without overflowing the underlying array .
 * @ param r The row to get the attributes for .
 * @ return The row attributes or < tt > null < / tt > if none are set . */
private AttributeSet getRowAttributeOrNull ( int r ) { } }

implementation: if ( ( r >= 0 ) && ( r < rowAttributes . size ( ) ) ) { return rowAttributes . get ( r ) ; } else { return null ; }


signature:
public class AttributeGridImpl { /** * Inserts a set of attributes into the grid at the specified location . This is a private insert method , that does
 * not notify model listeners , so that the public insert methods can do that as a separate step .
 * @ param attributes The attribute set to insert .
 * @ param c The column position .
 * @ param r The row position . */
private void internalInsert ( AttributeSet attributes , int c , int r ) { } }

implementation: cellAttributes . put ( ( long ) c , ( long ) r , attributes ) ;


signature:
public class UnaryArithmeticOperator { /** * Gets the actual value of a term , which is a numeric type equal in value to the arithmetic operator applied to its
 * argument . This method checks that the argument produces a value which is fully instantiated and numeric when its
 * { @ link Term # getValue ( ) } methods is invoked .
 * @ return A numeric type equal in value to the the arithmetic operator applied to its argument . */
public NumericType getValue ( ) { } }

implementation:
Term firstArgValue = arguments [ 0 ] . getValue ( ) ; // Check that the argument to operate on is a numeric values .
if ( ! firstArgValue . isNumber ( ) ) { throw new IllegalStateException ( "instantiation_error, 'arithmetic/2' expects numeric arguments, but the first argument is non-numeric." ) ; } return evaluate ( ( NumericType ) firstArgValue ) ;


signature:
public class SwingComponentFactory { /** * { @ inheritDoc } */
public JComponent createTextGridPanel ( EnhancedTextGrid model ) { } }

implementation: JTextGrid textPane = new JTextGrid ( ) ; textPane . setBackground ( colorScheme . getBackground ( ) ) ; textPane . setForeground ( colorScheme . getMainText ( ) ) ; textPane . setAutoscrolls ( true ) ; Font font = new Font ( "DejaVu Sans Mono" , Font . PLAIN , 12 ) ; textPane . setFont ( font ) ; textPane . setModel ( model ) ; textPane . initializeStandardMouseHandling ( ) ; JScrollPane scrollPane = new JScrollPane ( textPane , ScrollPaneConstants . VERTICAL_SCROLLBAR_AS_NEEDED , ScrollPaneConstants . HORIZONTAL_SCROLLBAR_AS_NEEDED ) ; scrollPane . getVerticalScrollBar ( ) . setUI ( new DiscreetScrollBarUI ( toolingColorScheme ) ) ; scrollPane . getHorizontalScrollBar ( ) . setUI ( new DiscreetScrollBarUI ( toolingColorScheme ) ) ; scrollPane . setBorder ( BorderFactory . createEmptyBorder ( ) ) ; scrollPane . getViewport ( ) . setLayout ( new FillViewportLayout ( ) ) ; return scrollPane ;


signature:
public class SwingComponentFactory { /** * { @ inheritDoc } */
public JComponent createGripPanel ( MotionDelta motionDelta , boolean vertical ) { } }

implementation: JPanel vbar = new JPanel ( ) ; vbar . setBackground ( toolingColorScheme . getToolingBackground ( ) ) ; GripComponentMouseMover resizer = new GripComponentMouseMover ( vbar , motionDelta , vertical ? VERTICAL_RESIZE_CURSOR : HORIZONTAL_RESIZE_CURSOR , GRIP_CURSOR ) ; vbar . addMouseMotionListener ( resizer ) ; vbar . addMouseListener ( resizer ) ; return vbar ;