public static long timeOfDayToTicks(int hour, int minute, int second, int millisecond)
    {
        return millisecond + (MILLIS_PER_SECOND * second) + (MILLIS_PER_MINUTE * minute) + (MILLIS_PER_HOUR * hour);
    }

public static long timeOfDayToTicks ( int hour , int minute , int second , int millisecond ) { return millisecond + ( MILLIS_PER_SECOND * second ) + ( MILLIS_PER_MINUTE * minute ) + ( MILLIS_PER_HOUR * hour ) ; }

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.

Converts a field by field time of day into millisecond ticks .


public static int ticksToYears(long ticks)
    {
        // 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;
    }

Extracts the years component of a time in millisecond ticks.

@param  ticks The time in ticks.

@return The years component of the time.

Extracts the years component of a time in millisecond ticks .


public static long ticksWithHoursSetTo(long ticks, int hours)
    {
        long oldHours = ticksToHours(ticks);

        return ticks - (oldHours * MILLIS_PER_HOUR) + (hours * MILLIS_PER_HOUR);
    }

public static long ticksWithHoursSetTo ( long ticks , int hours ) { long oldHours = ticksToHours ( ticks ) ; return ticks - ( oldHours * MILLIS_PER_HOUR ) + ( hours * MILLIS_PER_HOUR ) ; }

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.

Sets the component of the timestamp returning the new timestamp with updated component .


public static long ticksWithMinutesSetTo(long ticks, int minutes)
    {
        long oldMinutes = ticksToMinutes(ticks);

        return ticks - (oldMinutes * MILLIS_PER_MINUTE) + (minutes * MILLIS_PER_MINUTE);
    }

public static long ticksWithMinutesSetTo ( long ticks , int minutes ) { long oldMinutes = ticksToMinutes ( ticks ) ; return ticks - ( oldMinutes * MILLIS_PER_MINUTE ) + ( minutes * MILLIS_PER_MINUTE ) ; }

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.

Sets the minutes component of the timestamp returning the new timestamp with updated component .


public static long ticksWithSecondsSetTo(long ticks, int seconds)
    {
        long oldSeconds = ticksToSeconds(ticks);

        return ticks - (oldSeconds * MILLIS_PER_SECOND) + (seconds * MILLIS_PER_SECOND);
    }

public static long ticksWithSecondsSetTo ( long ticks , int seconds ) { long oldSeconds = ticksToSeconds ( ticks ) ; return ticks - ( oldSeconds * MILLIS_PER_SECOND ) + ( seconds * MILLIS_PER_SECOND ) ; }

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.

Sets the seconds component of the timestamp returning the new timestamp with updated component .


public static long ticksWithYearSetTo(long ticks, int year)
    {
        int oldYear = ticksToYears(ticks);

        return ticks - millisToYearStart(oldYear) + millisToYearStart(year);
    }

public static long ticksWithYearSetTo ( long ticks , int year ) { int oldYear = ticksToYears ( ticks ) ; return ticks - millisToYearStart ( oldYear ) + millisToYearStart ( year ) ; }

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.

Sets the year component of the timestamp returning the new timestamp with updated component .


public static long ticksWithMonthSetTo(long ticks, int month)
    {
        int year = ticksToYears(ticks);
        boolean isLeapYear = isLeapYear(year);
        int oldMonth = ticksToMonths(ticks);

        return ticks - millisToStartOfMonth(oldMonth, isLeapYear) + millisToStartOfMonth(month, isLeapYear);
    }

public static long ticksWithMonthSetTo ( long ticks , int month ) { int year = ticksToYears ( ticks ) ; boolean isLeapYear = isLeapYear ( year ) ; int oldMonth = ticksToMonths ( ticks ) ; return ticks - millisToStartOfMonth ( oldMonth , isLeapYear ) + millisToStartOfMonth ( month , isLeapYear ) ; }

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.

Sets the month component of the timestamp returning the new timestamp with updated component .


public static long ticksWithDateSetTo(long ticks, int date)
    {
        int oldDays = ticksToDate(ticks);

        return ticks - (oldDays * MILLIS_PER_DAY) + (date * MILLIS_PER_DAY);
    }

public static long ticksWithDateSetTo ( long ticks , int date ) { int oldDays = ticksToDate ( ticks ) ; return ticks - ( oldDays * MILLIS_PER_DAY ) + ( date * MILLIS_PER_DAY ) ; }

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.

Sets the date component of the timestamp returning the new timestamp with updated component .


public static long millisToYearStart(int year)
    {
        // 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;
    }

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.

Calculates the number of milliseconds to the start of the specified year taking 1970 as zero .


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.

Given a millisecond timestamp that lands in a specified year calculate what month the timestamp corresponds to .


public ByteBlock read(byte[] b) throws IOException
    {
        int count = source.read(b);

        return new ByteBlock(b, count);
    }

public ByteBlock read ( byte [ ] b ) throws IOException { int count = source . read ( b ) ; return new ByteBlock ( b , count ) ; }

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.

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 .


private Integer applyWithEntry(K key, Entry<K> entry, boolean tryRehashing)
    {
        // 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;
    }

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.

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 .


private Entry<K> entryForKey(K key)
    {
        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;
    }

private Entry < K > entryForKey ( K key ) { 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 ; }

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.

Checks if the specified key can be found in the set and returns its entry if so .


private Entry<K> cuckoo(Entry<K> entry)
    {
        // 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;
    }

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.

Adds a new entry to a hash table using the cuckoo algorithm .


private void rehash()
    {
        // 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);
    }

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.

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 .


public void actionPerformed(ActionEvent event)
    {
        /*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();
            }
        }
    }

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".

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 .


public void setNextAvailable(boolean avail)
    {
        // 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));
        }
    }

Sets the state of the next available flag and notifies any listeners of this change.

@param avail The next page available state.

Sets the state of the next available flag and notifies any listeners of this change .


public void setPrevAvailable(boolean avail)
    {
        // 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));
        }
    }

Sets the state of the previous available flag and notifies any listeners of this change.

@param avail The previous page available state.

Sets the state of the previous available flag and notifies any listeners of this change .


public void setFinished(boolean avail)
    {
        /*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");*/
        }
    }

Sets the state of the finished and notifies any listeners of this change.

@param avail The work flow completed state.

Sets the state of the finished and notifies any listeners of this change .


public static WAMResolvingNativeMachine getInstance(SymbolTableImpl<Integer, String, Object> symbolTable)
        throws ImplementationUnavailableException
    {
        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);
        }
    }

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.

Creates an instance of this machine loading and checking for availability of the native implementation library as required .


public Iterator<Set<Variable>> iterator()
    {
        return new SequenceIterator<Set<Variable>>()
            {
                public Set<Variable> nextInSequence()
                {
                    return resolve();
                }
            };
    }

public Iterator < Set < Variable > > iterator ( ) { return new SequenceIterator < Set < Variable > > ( ) { public Set < Variable > nextInSequence ( ) { return resolve ( ) ; } } ; }

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.

Provides an iterator that generates all solutions on demand as a sequence of variable bindings .


public static double expectedI(double[] probabilities)
    {
        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;
    }

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.

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 .


public static double[] pForDistribution(int[] counts)
    {
        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;
    }

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.

Estimates probabilities given a set of counts of occurrences of symbols .


void setTicks(long ticks)
    {
        year = TimeUtils.ticksToYears(ticks);
        month = TimeUtils.ticksToMonths(ticks);
        day = TimeUtils.ticksToDate(ticks);
    }

void setTicks ( long ticks ) { year = TimeUtils . ticksToYears ( ticks ) ; month = TimeUtils . ticksToMonths ( ticks ) ; day = TimeUtils . ticksToDate ( ticks ) ; }

Sets this date from a milliseconds timestamp.

@param ticks The timestamp.

Sets this date from a milliseconds timestamp .


public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException
    {
        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"));
    }

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 static URL newUrl(String spec)
	{
		try
		{
			return new URL(spec);
		}
		catch (MalformedURLException exception)
		{
			throw new IllegalArgumentException("Invalid URL: " + spec);
		}
	}

public
static
URL
newUrl
(
String
spec
)
{
try
{
return
new
URL
(
spec
)
;
}
catch
(
MalformedURLException
exception
)
{
throw
new
IllegalArgumentException
(
"Invalid URL: "
+
spec
)
;
}
}

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

Creates a URL for the specified string representation .


public String getRequestInfo()
    {
        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);
    }

public
String
getRequestInfo
(
)
{
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
)
;
}

Returns a String with all basic request information in an HTML table.

@return A String with all basic request information in an HTML table.

Returns a String with all basic request information in an HTML table .


public String getHeaders()
    {
        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);
    }

public
String
getHeaders
(
)
{
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
)
;
}

Returns a String with all header information as an HTML table.

@return A String with all header information as an HTML table.

Returns a String with all header information as an HTML table .


public String getCookies()
    {
        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);
    }

Returns a String with all cookie information as an HTML table.

@return A String with all cookie information as an HTML table.

Returns a String with all cookie information as an HTML table .


public String getParameters()
    {
        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);
    }

public
String
getParameters
(
)
{
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
)
;
}

Returns a String with all request parameter information.

@return A String with all request parameter information.

Returns a String with all request parameter information .


public String getRequestScope()
    {
        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);
    }

public
String
getRequestScope
(
)
{
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
)
;
}

Returns a String with all request scope variables.

@return A String with all request scope variables.

Returns a String with all request scope variables .


public String getPageScope()
    {
        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);
    }

public
String
getPageScope
(
)
{
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
)
;
}

Returns a String with all page scope variables.

@return A String with all page scope variables.

Returns a String with all page scope variables .


public String getSessionScope()
    {
        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);
    }

public
String
getSessionScope
(
)
{
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
)
;
}

Returns a String with all session scope variables.

@return A String with all session scope variables.

Returns a String with all session scope variables .


public String getApplicationScope()
    {
        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);
    }

public
String
getApplicationScope
(
)
{
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
)
;
}

Returns a String with all application scope variables.

@return A String with all application scope variables.

Returns a String with all application scope variables .


public String getUserPrincipal()
    {
        // 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);
    }

Returns the user principal name.

@return The user principal name.


public int doStartTag() throws JspException
    {
        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);
    }

"<table class=\"debug\" width=\"100%\" border=\"1\">"

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.


private String toHTMLTable(String propName, Map values)
    {
        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();
    }

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.

Returns an HTML table with all the values of the specified property .


public SearchNode search(QueueSearchState<O, T> initSearch, Collection<T> startStates, int maxSteps,
        int searchSteps) throws SearchNotExhaustiveException
    {
        // 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;
        }
    }

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.

Searches all SearchNodes less than the maximum bound for some property of the nodes .


public void setCurrentScreenState(WorkFlowScreenState state)
    {
        /*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));
    }

Sets the new current screen state and notifies all listeners of the change in screen state.

@param state The current screen state.

Sets the new current screen state and notifies all listeners of the change in screen state .


public void walk(Term term)
    {
        // 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);
    }

Walks over the supplied term.

@param term The term to walk over.


public int compare(SearchNode object1, SearchNode object2)
    {
        float f1 = ((HeuristicSearchNode) object1).getF();
        float f2 = ((HeuristicSearchNode) object2).getF();

        return (f1 > f2) ? 1 : ((f1 < f2) ? -1 : 0);
    }

public int compare ( SearchNode object1 , SearchNode object2 ) { float f1 = ( ( HeuristicSearchNode ) object1 ) . getF ( ) ; float f2 = ( ( HeuristicSearchNode ) object2 ) . getF ( ) ; return ( f1 > f2 ) ? 1 : ( ( f1 < f2 ) ? - 1 : 0 ) ; }

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.

Compares two heuristic search nodes by their f values .


public void updateRegisters(WAMInternalRegisters registers)
    {
        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);
    }

public void updateRegisters ( WAMInternalRegisters registers ) { 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 ) ; }

Updates the register file, with a new set of registers.

@param registers The new register values.

Updates the register file with a new set of registers .


private void notifyChanges(Iterable<PropertyChangeEvent> changes)
    {
        List<PropertyChangeListener> activeListeners = listeners.getActiveListeners();

        if (activeListeners != null)
        {
            for (PropertyChangeListener listener : activeListeners)
            {
                for (PropertyChangeEvent event : changes)
                {
                    listener.propertyChange(event);
                }
            }
        }
    }

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

Fires off a list of property change events to any interested listeners.

@param changes The list of property changes to fire off.

Fires off a list of property change events to any interested listeners .


protected void leaveClause(Clause clause)
    {
        // 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);
            }
        }
    }

Upon leaving the clause, sets the nonArgPosition flag on any constants that need it.

@param clause The clause being left.

Upon leaving the clause sets the nonArgPosition flag on any constants that need it .


private boolean inTopLevelFunctor(PositionalContext context)
    {
        PositionalContext parentContext = context.getParentContext();

        return parentContext.isTopLevel() || isTopLevel(parentContext);
    }

private boolean inTopLevelFunctor ( PositionalContext context ) { PositionalContext parentContext = context . getParentContext ( ) ; return parentContext . isTopLevel ( ) || isTopLevel ( parentContext ) ; }

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.

Checks if the current position is immediately within a top - level functor .


public <T> T[] toArray(T[] a)
    {
        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;
    }

public < T > T [ ] toArray ( T [ ] a ) { 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 ; }

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.

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 only if the caller knows that the collection
does not contain any <tt>null</tt> elements.)

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.

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.

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 .


public void setArguments(Term[] arguments)
    {
        // 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;
    }

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.

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 .


public Fixity getFixity()
    {
        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.");
        }
    }

public
Fixity
getFixity
(
)
{
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."
)
;
}
}

Provides the symbols fixity, derived from its associativity.

@return The symbols fixity.

Provides the symbols fixity derived from its associativity .


public boolean isInfix()
    {
        return ((associativity == Associativity.XFY) || (associativity == Associativity.YFX) ||
            (associativity == Associativity.XFX));
    }

public boolean isInfix ( ) { return ( ( associativity == Associativity . XFY ) || ( associativity == Associativity . YFX ) || ( associativity == Associativity . XFX ) ) ; }

Reports whether this operator is an infix operator.

@return <tt>true <tt>if this operator is an infix operator.

Reports whether this operator is an infix operator .


public int compareTo(Object o)
    {
        OpSymbol opSymbol = (OpSymbol) o;

        return (priority < opSymbol.priority) ? -1 : ((priority > opSymbol.priority) ? 1 : 0);
    }

public int compareTo ( Object o ) { OpSymbol opSymbol = ( OpSymbol ) o ; return ( priority < opSymbol . priority ) ? - 1 : ( ( priority > opSymbol . priority ) ? 1 : 0 ) ; }

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.

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 .


public void propertyChange(PropertyChangeEvent event)
    {
        /*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);
            }
        }
    }

Called when a property in the work flow state is changed.

@param event The property change event.

Called when a property in the work flow state is changed .


public void registerWorkFlowController(WorkFlowController controller)
    {
        // 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);
        }
    }

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.

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 .


public static EnumAttributeFactory getFactoryForClass(Class cls)
    {
        // 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);
    }

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.

Generates a factory for building enum attributes of the specified enum class .


public static ComponentFactory createComponentFactory(String className)
    {
        return (ComponentFactory) ReflectionUtils.newInstance(ReflectionUtils.forName(className));
    }

public static ComponentFactory createComponentFactory ( String className ) { return ( ComponentFactory ) ReflectionUtils . newInstance ( ReflectionUtils . forName ( className ) ) ; }

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.

Creates an instance of the named component factory .


public Variable getStorageCell(Variable variable)
    {
        VariableBindingContext<Variable> context = getBindingContext();

        if (context == null)
        {
            return null;
        }
        else
        {
            return context.getStorageCell(this);
        }
    }

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

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.

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 .


public boolean isBound()
    {
        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();
    }

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.

Reports whether or not this variable is bound to a value .


private void setColumnAttribute(AttributeSet attributes, int c)
    {
        if (c >= columnAttributes.size())
        {
            for (int i = columnAttributes.size(); i <= c; i++)
            {
                columnAttributes.add(null);
            }
        }

        columnAttributes.set(c, attributes);
    }

private void setColumnAttribute ( AttributeSet attributes , int c ) { if ( c >= columnAttributes . size ( ) ) { for ( int i = columnAttributes . size ( ) ; i <= c ; i ++ ) { columnAttributes . add ( null ) ; } } columnAttributes . set ( c , attributes ) ; }

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.

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 .


private void setRowAttribute(AttributeSet attributes, int r)
    {
        if (r >= rowAttributes.size())
        {
            for (int i = rowAttributes.size(); i <= r; i++)
            {
                rowAttributes.add(null);
            }
        }

        rowAttributes.set(r, attributes);
    }

private void setRowAttribute ( AttributeSet attributes , int r ) { if ( r >= rowAttributes . size ( ) ) { for ( int i = rowAttributes . size ( ) ; i <= r ; i ++ ) { rowAttributes . add ( null ) ; } } rowAttributes . set ( r , attributes ) ; }

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.

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 .


private AttributeSet getColumnAttributeOrNull(int c)
    {
        if ((c >= 0) && (c < columnAttributes.size()))
        {
            return columnAttributes.get(c);
        }
        else
        {
            return null;
        }
    }

private AttributeSet getColumnAttributeOrNull ( int c ) { if ( ( c >= 0 ) && ( c < columnAttributes . size ( ) ) ) { return columnAttributes . get ( c ) ; } else { return null ; } }

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.

Gets a columns attribute if possible without overflowing the underlying array .


private AttributeSet getRowAttributeOrNull(int r)
    {
        if ((r >= 0) && (r < rowAttributes.size()))
        {
            return rowAttributes.get(r);
        }
        else
        {
            return null;
        }
    }

private AttributeSet getRowAttributeOrNull ( int r ) { if ( ( r >= 0 ) && ( r < rowAttributes . size ( ) ) ) { return rowAttributes . get ( r ) ; } else { return null ; } }

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.

Gets a rows attribute if possible without overflowing the underlying array .


private void internalInsert(AttributeSet attributes, int c, int r)
    {
        cellAttributes.put((long) c, (long) r, attributes);
    }

private void internalInsert ( AttributeSet attributes , int c , int r ) { cellAttributes . put ( ( long ) c , ( long ) r , attributes ) ; }

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.

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 .


public static Type createInstance(String name, TimeOnly min, TimeOnly max)
    {
        // Ensure that min is less than or equal to max.
        if ((min != null) && (max != null) && (min.compareTo(max) > 0))
        {
            throw new IllegalArgumentException("'min' must be less than or equal to 'max'.");
        }

        synchronized (INT_RANGE_TYPES)
        {
            // Add the newly created type to the map of all types.
            TimeRangeType newType = new TimeRangeType(name, min, max);

            // Ensure that the named type does not already exist, unless it has an identical definition already, in which
            // case the old definition can be re-used and the new one discarded.
            TimeRangeType oldType = INT_RANGE_TYPES.get(name);

            if ((oldType != null) && !oldType.equals(newType))
            {
                throw new IllegalArgumentException("The type '" + name + "' already exists and cannot be redefined.");
            }
            else if ((oldType != null) && oldType.equals(newType))
            {
                return oldType;
            }
            else
            {
                INT_RANGE_TYPES.put(name, newType);

                return newType;
            }
        }
    }

Creates a new time range type with the specified name, if it does not already exist.

@param  name The name of the time range type to create.
@param  min  The minimum value that an instance of the type can take.
@param  max  The maximum value that an instance of teh type can take.

@return A new time range type.

@throws IllegalArgumentException If min is not less than or equal to max, or the named type already exists.

Creates a new time range type with the specified name if it does not already exist .


public static Type createInstance(String name, int maxLength, String pattern)
    {
        synchronized (STRING_PATTERN_TYPES)
        {
            StringPatternType newType = new StringPatternType(name, maxLength, pattern);

            // Ensure that the named type does not already exist.
            StringPatternType oldType = STRING_PATTERN_TYPES.get(name);

            if ((oldType != null) && !oldType.equals(newType))
            {
                throw new IllegalArgumentException("The type '" + name + "' already exists and cannot be redefined.");
            }
            else if ((oldType != null) && oldType.equals(newType))
            {
                return oldType;
            }
            else
            {
                // Add the newly created type to the map of all types.
                STRING_PATTERN_TYPES.put(name, newType);

                return newType;
            }
        }
    }

Creates a new string pattern type with the specified name, if it does not already exist.

@param  name      The name of the string pattern type to create.
@param  maxLength The maximum length of instances of the type, may be zero or less for no maximum.
@param  pattern   A regular expression that instances must match, or <tt>null</tt> for no pattern.

@return A new string pattern type.

@throws IllegalArgumentException If min is not less than or equal to max, or the named type already exists.

Creates a new string pattern type with the specified name if it does not already exist .


public boolean isInstance(CharSequence value)
    {
        // Check the value is under the maximum if one is set.
        // Check the value matches the pattern if one is set.
        return ((maxLength <= 0) || (value.length() <= maxLength)) && compiledPattern.matcher(value).matches();
    }

Checks a string value against this type to see if it is a valid instance of the type.

@param  value The value to type check.

@return <tt>true</tt> if the string is a valid instance of this type.

Checks a string value against this type to see if it is a valid instance of the type .


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

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

Sets up the initial context once, at the start of a traversal.

@param term The term to establish the initial positional traversal context for.

Sets up the initial context once at the start of a traversal .


public void updateRegisters(WAMMemoryLayout layout)
    {
        List<PropertyChangeEvent> changes = delta(this, layout);

        regBase = layout.regBase;
        regSize = layout.regSize;
        heapBase = layout.heapBase;
        heapSize = layout.heapSize;
        stackBase = layout.stackBase;
        stackSize = layout.stackSize;
        trailBase = layout.trailBase;
        trailSize = layout.trailSize;
        pdlBase = layout.pdlBase;
        pdlSize = layout.pdlSize;

        notifyChanges(changes);
    }

public void updateRegisters ( WAMMemoryLayout layout ) { List < PropertyChangeEvent > changes = delta ( this , layout ) ; regBase = layout . regBase ; regSize = layout . regSize ; heapBase = layout . heapBase ; heapSize = layout . heapSize ; stackBase = layout . stackBase ; stackSize = layout . stackSize ; trailBase = layout . trailBase ; trailSize = layout . trailSize ; pdlBase = layout . pdlBase ; pdlSize = layout . pdlSize ; notifyChanges ( changes ) ; }

Updates the layout register file, with a new set of layout registers.

@param layout The new layout register values.

Updates the layout register file with a new set of layout registers .


public String getValue() {
        for (ScopeNode scope = NodeTreeUtils.getParentScope(this); scope != null; scope = NodeTreeUtils.getParentScope(scope)) {
            ExpressionGroupNode value = scope.getVariable(_name);
            if (value == null) {
                continue;
            }

            return value.toString();
        }

        return _name; // Unable to find the variable's value, return the name for now (helpful for debugging)
    }

Search up the scope tree to locate the variable's value. The parser has already verified that
the variable is defined.

Search up the scope tree to locate the variable s value . The parser has already verified that the variable is defined .


public SearchNode<O, T> findGoalPath() throws SearchNotExhaustiveException
    {
        // Keep running until the queue becomes empty or a goal state is found
        while (!forwardQueue.isEmpty() || !reverseQueue.isEmpty())
        {
            // Only run the forward step of the search if the forward queue is not empty
            if (!forwardQueue.isEmpty())
            {
                // Extract the next node from the forward queue
                SearchNode<O, T> currentForwardNode = forwardQueue.remove();

                // Remove this node from the forward fringe map as it will soon be replaced by more fringe members
                forwardFringe.remove(currentForwardNode.getState());

                // Check the reverse fringe against the next forward node for a match.
                if (reverseFringe.containsKey(currentForwardNode.getState()))
                {
                    // A path from start to the goal has been found. Walk backwards along the reverse path adding all
                    // nodes encountered to the forward path until the goal is reached.
                    return joinBothPaths(currentForwardNode, reverseFringe.get(currentForwardNode.getState()));
                }

                // There was no match so a path to the goal has not been found
                else
                {
                    // Get all of the successor states to the current node
                    Queue<SearchNode<O, T>> newStates = new LinkedList<SearchNode<O, T>>();

                    currentForwardNode.expandSuccessors(newStates, false);

                    // Expand all the successors to the current forward node into the buffer to be searched.
                    forwardQueue.addAll(newStates);

                    // Also add all the successors to the current forward fringe map.
                    for (SearchNode<O, T> nextSearchNode : newStates)
                    {
                        forwardFringe.put(nextSearchNode.getState(), nextSearchNode);
                    }
                }
            }

            // Only run the reverse step of the search if the reverse queue is not empty
            if (!reverseQueue.isEmpty())
            {
                // Extract the next node from the reverse queue
                SearchNode<O, T> currentReverseNode = reverseQueue.remove();

                // Remove this node from the reverse fringe set as it will soon be replaced by more fringe members
                reverseFringe.remove(currentReverseNode.getState());

                // Check the forward fringe against the next reverse node for a match.
                if (forwardFringe.containsKey(currentReverseNode.getState()))
                {
                    // A path from start to goal has been found.
                    // Walk backwards along the reverse path adding all nodes encountered to the foward path until the
                    // goal is reached.
                    return joinBothPaths(forwardFringe.get(currentReverseNode.getState()), currentReverseNode);
                }

                // There was no match so a path to the goal has not been found
                else
                {
                    // Get all of the successor states to the current node (really predecessor state)
                    Queue<SearchNode<O, T>> newStates = new LinkedList<SearchNode<O, T>>();

                    currentReverseNode.expandSuccessors(newStates, false);

                    // Expand all the successors to the current reverse node into the reverse buffer to be searched.
                    reverseQueue.addAll(newStates);

                    // Add all the successors to the current reverse fringe set
                    for (SearchNode<O, T> nextSearchNode : newStates)
                    {
                        reverseFringe.put(nextSearchNode.getState(), nextSearchNode);
                    }
                }
            }
        }

        // No goal state was found so return null
        return null;
    }

Implementation of the general bi-dircetional search. The search alternated between taking a forward and a reverse
step.

@return The first {@link SearchNode} corresponding to a goal state that is found or null if none can be found
after exhaustive searching.

@throws SearchNotExhaustiveException If the search stops before finding a solution or exhausting the search
space. Different search algorithms may fail for different reasons but in
particular it it is worth noting that if the maximum number of steps is
reached without exhausting the search space this will cause an exception to
be thrown rather than for this method to return null.

Implementation of the general bi - dircetional search . The search alternated between taking a forward and a reverse step .


private SearchNode<O, T> joinBothPaths(SearchNode<O, T> forwardPath, SearchNode<O, T> reversePath)
        throws SearchNotExhaustiveException
    {
        // Check if an alternative path join algorithm has been set and delegate to it if so
        if (pathJoiner != null)
        {
            return pathJoiner.joinBothPaths(forwardPath, reversePath);
        }

        // No alternative path join algorithm has been supplied so use this default one
        else
        {
            // Used to hold the current position along the reverse path of search nodes
            SearchNode<O, T> currentReverseNode = reversePath;

            // Used to hold the current position along the forward path of search nodes
            SearchNode<O, T> currentForwardNode = forwardPath;

            // Loop over all nodes in the reverse path checking if the current reverse node is the
            // goal state to terminate on.
            while (!goalPredicate.evaluate(currentReverseNode.getState()))
            {
                // Create a new forward node from the parent state of the current reverse node, the current reverse
                // nodes applied operation and cost, and an increment of one to the path depth
                SearchNode<O, T> reverseParentNode = currentReverseNode.getParent();
                T state = currentReverseNode.getParent().getState();
                Operator<O> operation = currentReverseNode.getAppliedOp();
                float cost = currentReverseNode.getPathCost() - reverseParentNode.getPathCost();

                currentForwardNode = currentForwardNode.makeNode(new Successor<O>(state, operation, cost));

                // Move one step up the reverse path
                currentReverseNode = reverseParentNode;
            }

            // Return the last forward search node found
            return currentForwardNode;
        }
    }

Once a match has been found between the forward and reverse fringes of the search a path is known to exist from
the start to the goal. The path is not complete at this stage because it remains to reverse all of the steps in
the backward half of the path and add them to the forward half of the path to produce the complete forward path
from start to the goal.

This method implements a standard algorithm for doing this. It assumes that the state space being searched by
both halfs of the search is over the same states. It also assumes that the applied operations in the reverse
search node have already been reverse. For example, if the search space was the eight tiles game then the moves
stored in the reverse half of the search would have to be stored in the reverse direction to that in which they
are applied when really playing the game backwards. This means that two implementations of
{@link com.thesett.aima.search.TraversableState} are needed, one that gives its operators reversed.

It is possible to supply an alternative path joining algorithm that does know how to reverse the operators.
Set this in this search algorithm by calling the {@link #setPathJoinAlgorithm} method. This is an alternative to
writing two implementatios of {@link com.thesett.aima.search.TraversableState}

@param  forwardPath a search node for the forward portion of the goal path
@param  reversePath a search node for the reverse portion of the goal path

@return a search node corresponding to the path right from start to goal

@throws SearchNotExhaustiveException If the node implementation does not allow new nodes to be created from old.
See the {@link SearchNode#makeNode} method for more information.

Once a match has been found between the forward and reverse fringes of the search a path is known to exist from the start to the goal . The path is not complete at this stage because it remains to reverse all of the steps in the backward half of the path and add them to the forward half of the path to produce the complete forward path from start to the goal .


public List<T> cacheBlock(int block)
    {
        /*log.fine("public List<T> cacheBlock(int block): called");*/

        // Get the new block.
        List<T> blockList = getBlock(block * blockSize, blockSize);

        // Cache it.
        blockMap.put(block, blockList);
        /*log.fine("Cached block " + block + " with list of size " + blockList.size());*/

        return blockList;
    }

Fetches and caches the specified block.

@param  block The block to cache.

@return The contents of the cached block.

Fetches and caches the specified block .


public static synchronized Properties getProperties(String resourceName)
    {
        /*log.fine("public static synchronized Properties getProperties(String resourceName): called");*/
        /*log.fine("resourceName = " + resourceName);*/

        // Try to find an already created singleton property reader for the resource
        PropertyReaderBase propertyReader = (PropertyReaderBase) propertyReaders.get(resourceName);

        if (propertyReader != null)
        {
            /*log.fine("found property reader in the cache for resource: " + resourceName);*/

            return propertyReader.getProperties();
        }

        /*log.fine("did not find property reader in the cache for resource: " + resourceName);*/

        // There is not already a singleton for the named resource so create a new one
        propertyReader = new DefaultPropertyReader(resourceName);

        // Keep the newly created singleton for next time
        propertyReaders.put(resourceName, propertyReader);

        return propertyReader.getProperties();
    }

Static factory method that locates an existing instance or creates a new property reader for a named resource.

@param  resourceName The name of the property file resource.

@return The properties found under that resource name.

Static factory method that locates an existing instance or creates a new property reader for a named resource .


public void setRate(float hertz)
    {
        // Pass the rate unaltered down to the base implementation, for the check method.
        super.setRate(hertz);

        // Log base 10 over 2 is used here to get a feel for what power of 100 the total rate is.
        // As the total rate goes up the powers of 100 the batch size goes up by powers of 100 to keep the
        // throttle rate in the range 1 to 100.
        int x = (int) (Math.log10(hertz) / 2);
        batchSize = (int) Math.pow(100, x);

        float throttleRate = hertz / batchSize;

        // Reset the call count.
        callCount = 0;

        // Set the sleep throttle wrapped implementation at a rate within its abilities.
        batchRateThrottle.setRate(throttleRate);
    }

Specifies the throttling rate in operations per second.

@param hertz The throttling rate in cycles per second.

Specifies the throttling rate in operations per second .


public int read(byte[] b) throws IOException
    {
        try
        {
            ByteBlock block = source.read(b);

            System.arraycopy(block.data, 0, b, 0, block.count);

            return block.count;
        }
        catch (RemoteException e)
        {
            throw new IOException("There was a Remote Exception.", e);
        }
    }

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

Reads some number of bytes from the input stream and stores them into the buffer array b.

@param  b The buffer into which the data is read.

@return The total number of bytes read into the buffer, or -1 is there is no more data because the end of the
stream has been reached.

@throws IOException If an I/O error occurs when accessing the stream or a remote exception occurs.

Reads some number of bytes from the input stream and stores them into the buffer array b .


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

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

Skips over and discards n bytes of data from this input stream.

@param  n The number of bytes to skip.

@return The actual number of bytes skipped.

@throws IOException If an IOException occurs in the wrapped distributed input stream or a remote exception
occurs.

Skips over and discards n bytes of data from this input stream .


private void gatherDisjunctions(Disjunction disjunction, List<Term> expressions)
    {
        // Left argument.
        gatherDisjunctionsExploreArgument(disjunction.getArguments()[0], expressions);

        // Right argument.
        gatherDisjunctionsExploreArgument(disjunction.getArguments()[1], expressions);
    }

private
void
gatherDisjunctions
(
Disjunction
disjunction
,
List
<
Term
>
expressions
)
{
// Left argument.
gatherDisjunctionsExploreArgument
(
disjunction
.
getArguments
(
)
[
0
]
,
expressions
)
;
// Right argument.
gatherDisjunctionsExploreArgument
(
disjunction
.
getArguments
(
)
[
1
]
,
expressions
)
;
}

Gathers the functors to compile as a sequence of choice points. These exist as the arguments to disjunctions
recursively below the supplied disjunction. They are flattened into a list, by performing a left-to-right depth
first traversal over the disjunctions, and adding their arguments into a list.

@param disjunction The disjunction to explore the arguments of.
@param expressions The flattened list of disjunctive terms.

Gathers the functors to compile as a sequence of choice points . These exist as the arguments to disjunctions recursively below the supplied disjunction . They are flattened into a list by performing a left - to - right depth first traversal over the disjunctions and adding their arguments into a list .


public static int getIntFromBytes(byte[] buf, int offset)
    {
        int result = 0;

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

        return result;
    }

public static int getIntFromBytes ( byte [ ] buf , int offset ) { int result = 0 ; result += buf [ offset ++ ] & 0xFF ; result += ( ( buf [ offset ++ ] & 0xFF ) << 8 ) ; result += ( ( buf [ offset ++ ] & 0xFF ) << 16 ) ; result += ( ( buf [ offset ] ) << 24 ) ; return result ; }

Extracts an int from an array of bytes.

@param  buf    The array of bytes to extract the int from.
@param  offset The offset of the start of the int in the byte array.

@return An integer extracted from the 4 bytes of data.

Extracts an int from an array of bytes .


public static void writeIntToByteArray(byte[] buf, int offset, int value)
    {
        buf[offset++] = (byte) (value & 0x000000ff);
        buf[offset++] = (byte) ((value & 0x0000ff00) >> 8);
        buf[offset++] = (byte) ((value & 0x00ff0000) >> 16);
        buf[offset] = (byte) ((value & 0xff000000) >> 24);
    }

public static void writeIntToByteArray ( byte [ ] buf , int offset , int value ) { buf [ offset ++ ] = ( byte ) ( value & 0x000000ff ) ; buf [ offset ++ ] = ( byte ) ( ( value & 0x0000ff00 ) >> 8 ) ; buf [ offset ++ ] = ( byte ) ( ( value & 0x00ff0000 ) >> 16 ) ; buf [ offset ] = ( byte ) ( ( value & 0xff000000 ) >> 24 ) ; }

Outputs an int into a byte array.

@param buf    The byte array to write to.
@param offset The offset within the byte array to output the int.
@param value  The int value to write into the array.


public static void write24BitIntToByteArray(byte[] buf, int offset, int value)
    {
        buf[offset++] = (byte) (value & 0x000000ff);
        buf[offset++] = (byte) ((value & 0x0000ff00) >> 8);
        buf[offset] = (byte) ((value & 0x00ff0000) >> 16);
    }

public static void write24BitIntToByteArray ( byte [ ] buf , int offset , int value ) { buf [ offset ++ ] = ( byte ) ( value & 0x000000ff ) ; buf [ offset ++ ] = ( byte ) ( ( value & 0x0000ff00 ) >> 8 ) ; buf [ offset ] = ( byte ) ( ( value & 0x00ff0000 ) >> 16 ) ; }

Outputs an int into a byte array, copying only the bottom 24 bits of the integer. The top, sign bit, is lost by
this operation, so this only works on positive ints below 2^24.

@param buf    The byte array to write to.
@param offset The offset within the byte array to output the int.
@param value  The int value to write into the array.

Outputs an int into a byte array copying only the bottom 24 bits of the integer . The top sign bit is lost by this operation so this only works on positive ints below 2^24 .