public ScopeNode callMixin(String name, ArgumentsNode arguments) {
        List<ExpressionGroupNode> argumentList = (arguments != null) ? NodeTreeUtils.getChildren(arguments, ExpressionGroupNode.class) : Collections.<ExpressionGroupNode>emptyList();
        if (argumentList.size() > _parameterDefinitions.size()) {
            throw new IllegalMixinArgumentException(name, _parameterDefinitions.size());
        }

        // Clone scope and filter out any white space
        ScopeNode mixinScope = clone();
        NodeTreeUtils.filterLineBreaks(mixinScope);

        // If arguments were passed, apply them
        for (int i = 0; i < argumentList.size(); i++) {
            ExpressionGroupNode argument = argumentList.get(i);
            // Replace the value of the definition
            VariableDefinitionNode parameter = mixinScope._parameterDefinitions.get(i);
            parameter.clearChildren();
            parameter.addChild(argument);
        }

        // Mark this scope's containing rule set as invisible since it has been used as a mixin
        getParent().setVisible(false);

        return mixinScope;
    }

Creates a clone of this scope to be attached to the tree at the site of a mixin reference. If an ArgumentsNode is passed,
each of its values override those defined by the mixin's parameters.

Creates a clone of this scope to be attached to the tree at the site of a mixin reference . If an ArgumentsNode is passed each of its values override those defined by the mixin s parameters .


private void setAdditionVisitor() {
        setAdditionVisitor(new InclusiveNodeVisitor() {
            /**
             * Add parameter set as a child for printing input, but also add each defined value to the variable map.
             */
            @Override
            public boolean add(ParametersNode node) {
                for (VariableDefinitionNode variable : NodeTreeUtils.getChildren(node, VariableDefinitionNode.class)) {
                    _parameterDefinitions.add(variable);
                    add(variable);
                }
                return super.add(node);
            }

            /**
             * Store the rule set's scope by selector group
             */
            @Override
            public boolean add(RuleSetNode node) {
                SelectorGroupNode selectorGroup = NodeTreeUtils.getFirstChild(node, SelectorGroupNode.class);
                for (SelectorNode selectorNode : NodeTreeUtils.getChildren(selectorGroup, SelectorNode.class)) {
                    StringBuilder sb = new StringBuilder();
                    for (Node selectorChild : selectorNode.getChildren()) {
                        sb.append(selectorChild.toString());
                    }
                    String selector = sb.toString();
                    // Mixins lock on first definition
                    if (!_selectorToRuleSetMap.containsKey(selector)) {
                        _selectorToRuleSetMap.put(selector, node);
                    }
                }
                return super.add(node);
            }

            /**
             * Absorb all children of the given scope. This assumes that cloning is not necessary.
             */
            @Override
            public boolean add(ScopeNode node) {
                NodeTreeUtils.moveChildren(node, ScopeNode.this);
                return false; // Don't add the original scope itself
            }

            /**
             * Store variable definitions in a map by name
             */
            @Override
            public boolean add(VariableDefinitionNode node) {
                String name = node.getName();
                // "Variables" lock on first definition
                if (!_variableNameToValueMap.containsKey(name)) {
                    _variableNameToValueMap.put(name, NodeTreeUtils.getFirstChild(node, ExpressionGroupNode.class));
                }
                return super.add(node);
            }

            /**
             * Store property nodes by name. If there are multiple properties for a given name, only retain the last one.
             */
            @Override
            public boolean add(PropertyNode node) {
                String name = node.getName();

                // If this is the IE-specific "filter" property, always add it
                if (name.equals(FILTER_PROPERTY)) {
                    return super.add(node);
                }

                // If the value of this property node is a vendor-specific keyword, always add it
                if (node.getChildren().get(0).toString().startsWith("-")) {
                    return super.add(node);
                }

                // Check if this property has been seen before
                if (_propertyNameToNodeMap.containsKey(name)) {
                    PropertyNode oldPropertyNode = _propertyNameToNodeMap.get(name);
                    int oldPropertyIndex = getChildren().indexOf(oldPropertyNode);

                    if (oldPropertyNode.isVisible()) {
                        // Hide the unneeded property
                        oldPropertyNode.setVisible(false);

                        // Attempt to hide one surrounding white space node
                        if (!hideWhiteSpaceNode(oldPropertyIndex - 1)) {
                            hideWhiteSpaceNode(oldPropertyIndex + 1);
                        }
                    }
                }

                // Store the property as the latest for this name
                _propertyNameToNodeMap.put(name, node);

                return super.add(node);
            }
        });
    }

Some nodes are captured in additional structures to aid later resolution.

Some nodes are captured in additional structures to aid later resolution .


protected void backtrack(SearchNode checkNode)
    {
        while ((checkNode != null) && (checkNode.unexaminedSuccessorCount == 0))
        {
            Reversable undoState = (ReTraversable) checkNode.getState();
            undoState.undoOperator();

            checkNode = checkNode.getParent();
        }
    }

protected void backtrack ( SearchNode checkNode ) { while ( ( checkNode != null ) && ( checkNode . unexaminedSuccessorCount == 0 ) ) { Reversable undoState = ( ReTraversable ) checkNode . getState ( ) ; undoState . undoOperator ( ) ; checkNode = checkNode . getParent ( ) ; } }

Back-tracks from the specified node, moving succesively upwards through the chain of parent nodes, until a node
is encountered that has unexamined successors. This method implements the backtracking searches reverse
direction. By checking for the presence of unexamined successors, this method only backtracks where necessary.

@param checkNode The search node to start back-tracking from.

Back - tracks from the specified node moving succesively upwards through the chain of parent nodes until a node is encountered that has unexamined successors . This method implements the backtracking searches reverse direction . By checking for the presence of unexamined successors this method only backtracks where necessary .


public byte[] retrieveCode(WAMCallPoint callPoint)
    {
        byte[] result = new byte[callPoint.length];

        codeBuffer.get(result, callPoint.entryPoint, callPoint.length);

        return result;
    }

public byte [ ] retrieveCode ( WAMCallPoint callPoint ) { byte [ ] result = new byte [ callPoint . length ] ; codeBuffer . get ( result , callPoint . entryPoint , callPoint . length ) ; return result ; }

Extracts the raw byte code from the machine for a given call table entry.

@param  callPoint The call table entry giving the location and length of the code.

@return The byte code at the specified location.

Extracts the raw byte code from the machine for a given call table entry .


protected Set<Variable> executeAndExtractBindings(WAMCompiledQuery query)
    {
        // Execute the query and program. The starting point for the execution is the first functor in the query
        // body, this will follow on to the subsequent functors and make calls to functors in the compiled programs.
        boolean success = execute(query.getCallPoint());

        // Used to collect the results in.
        Set<Variable> results = null;

        // Collect the results only if the resolution was successfull.
        if (success)
        {
            results = new HashSet<Variable>();

            // The same variable context is used accross all of the results, for common use of variables in the
            // results.
            Map<Integer, Variable> varContext = new HashMap<Integer, Variable>();

            // For each of the free variables in the query, extract its value from the location on the heap pointed to
            // by the register that holds the variable.
            /*log.fine("query.getVarNames().size() =  " + query.getVarNames().size());*/

            for (byte reg : query.getVarNames().keySet())
            {
                int varName = query.getVarNames().get(reg);

                if (query.getNonAnonymousFreeVariables().contains(varName))
                {
                    int addr = derefStack(reg);
                    Term term = decodeHeap(addr, varContext);

                    results.add(new Variable(varName, term, false));
                }
            }
        }

        return results;
    }

Runs a query, and for every non-anonymous variable in the query, decodes its binding value from the heap and
returns it in a set of variable bindings.

@param  query The query to execute.

@return A set of variable bindings resulting from the query.

Runs a query and for every non - anonymous variable in the query decodes its binding value from the heap and returns it in a set of variable bindings .


protected Term decodeHeap(int start, Map<Integer, Variable> variableContext)
    {
        /*log.fine("private Term decodeHeap(int start = " + start + ", Map<Integer, Variable> variableContext = " +
            variableContext + "): called");*/

        // Used to hold the decoded argument in.
        Term result = null;

        // Dereference the initial heap pointer.
        int addr = deref(start);
        byte tag = getDerefTag();
        int val = getDerefVal();

        /*log.fine("addr = " + addr);*/
        /*log.fine("tag = " + tag);*/
        /*log.fine("val = " + val);*/

        switch (tag)
        {
        case REF:
        {
            // Check if a variable for the address has already been created in this context, and use it if so.
            Variable var = variableContext.get(val);

            if (var == null)
            {
                var = new Variable(varNameId.decrementAndGet(), null, false);

                variableContext.put(val, var);
            }

            result = var;

            break;
        }

        case STR:
        {
            // Decode f/n from the STR data.
            int fn = getHeap(val);
            int f = fn & 0x00ffffff;

            /*log.fine("fn = " + fn);*/
            /*log.fine("f = " + f);*/

            // Look up and initialize this functor name from the symbol table.
            FunctorName functorName = getDeinternedFunctorName(f);

            // Fill in this functors name and arity and allocate storage space for its arguments.
            int arity = functorName.getArity();
            Term[] arguments = new Term[arity];

            // Loop over all of the functors arguments, recursively decoding them.
            for (int i = 0; i < arity; i++)
            {
                arguments[i] = decodeHeap(val + 1 + i, variableContext);
            }

            // Create a new functor to hold the decoded data.
            result = new Functor(f, arguments);

            break;
        }

        case WAMInstruction.CON:
        {
            //Decode f/n from the CON data.
            int f = val & 0x3fffffff;

            /*log.fine("f = " + f);*/

            // Create a new functor to hold the decoded data.
            result = new Functor(f, null);

            break;
        }

        case WAMInstruction.LIS:
        {
            FunctorName functorName = new FunctorName("cons", 2);
            int f = internFunctorName(functorName);

            // Fill in this functors name and arity and allocate storage space for its arguments.
            int arity = functorName.getArity();
            Term[] arguments = new Term[arity];

            // Loop over all of the functors arguments, recursively decoding them.
            for (int i = 0; i < arity; i++)
            {
                arguments[i] = decodeHeap(val + i, variableContext);
            }

            // Create a new functor to hold the decoded data.
            result = new Functor(f, arguments);

            break;
        }

        default:
            throw new IllegalStateException("Encountered unknown tag type on the heap.");
        }

        return result;
    }

Decodes a term from the raw byte representation on the machines heap, into an abstract syntax tree.

@param  start           The start offset of the term on the heap.
@param  variableContext The variable context for the decoded variables. This may be shared amongst all variables
decoded for a particular unifcation.

@return The term decoded from its heap representation.

Decodes a term from the raw byte representation on the machines heap into an abstract syntax tree .


public void capture()
    {
        // Get the class of the object to build a memento for.
        Class cls = ob.getClass();

        // Iterate through the classes whole inheritence chain.
        while (!cls.equals(Object.class))
        {
            // Get the classes fields.
            Field[] attrs = cls.getDeclaredFields();

            // Build a new map to put the fields in for the current class.
            HashMap map = new HashMap();

            // Cache the field values by the class name.
            values.put(cls, map);

            // Loop over all the fields in the current class.
            for (Field attr : attrs)
            {
                // Make the field accessible (it may be protected or private).
                attr.setAccessible(true);

                // Check that the field should be captured.
                if (shouldBeSaved(attr))
                {
                    // Use a try block as access to the field may fail, although this should not happen because
                    // even private, protected and package fields have been made accessible.
                    try
                    {
                        // Cache the field by its name.
                        map.put(attr.getName(), attr.get(ob));
                    }
                    catch (IllegalAccessException e)
                    {
                        // The field could not be accessed but all fields have been made accessible so this should
                        // not happen.
                        throw new IllegalStateException("Field '" + attr.getName() +
                            "' could not be accessed but the 'setAccessible(true)' method was invoked on it.", e);
                    }
                }
            }

            // Get the superclass for the next step of the iteration over the whole inheritence chain.
            cls = cls.getSuperclass();
        }
    }

Captures an objects state in this memento.

Captures an objects state in this memento .


public void restore(Object ob) throws NoSuchFieldException
    {
        /*log.fine("public void map(Object ob): called");*/
        /*log.fine("class is " + ob.getClass());*/

        // Iterate over the whole inheritence chain.
        for (Object key : values.keySet())
        {
            // Get the next class from the cache.
            Class cls = (Class) key;

            // Get the cache of field values for the class.
            Map vals = (HashMap) values.get(cls);

            // Loop over all fields in the class.
            for (Object o : vals.keySet())
            {
                // Get the next field name.
                String attr = (String) o;

                // Get the next field value.
                Object val = vals.get(attr);

                // Get a reference to the field in the object.
                Field f = cls.getDeclaredField(attr);

                // Make the field accessible (it may be protected, package or private).
                f.setAccessible(true);

                // Use a try block as writing to the field may fail.
                try
                {
                    // Write to the field.
                    f.set(ob, val);
                }
                catch (IllegalAccessException e)
                {
                    // The field could not be written to but all fields have been made accessible so this should
                    // not happen.
                    throw new IllegalStateException("Field '" + f.getName() +
                        "' could not be accessed but the 'setAccessible(true)' method was invoked on it.", e);
                }
            }
        }
    }

Restores the values currently in this memento to the specified object.

@param  ob The object to which the values from this memento should be restored.

@throws NoSuchFieldException If the object in question does not have a field for one of the memento values.

Restores the values currently in this memento to the specified object .


public Object get(Class cls, String attr)
    {
        HashMap map;

        // See if the class exists in the cache.
        if (!values.containsKey(cls))
        {
            // Class not in cache so return null.
            return null;
        }

        // Get the cache of field values for the class.
        map = (HashMap) values.get(cls);

        // Extract the specified field from the cache.
        return map.get(attr);
    }

Gets the value of the named field of the specified class.

@param  cls  The class in which the field to get is declared.
@param  attr The name of the field.

@return The object value of the attribute.

Gets the value of the named field of the specified class .


public void put(Class cls, String attr, Object val)
    {
        /*log.fine("public void put(Class cls, String attr, Object val): called");*/
        /*log.fine("class name is " + cls.getName());*/
        /*log.fine("attribute is " + attr);*/
        /*log.fine("value to set is " + val);*/

        HashMap map;

        // Check that the cache for the class exists in the cache.
        if (values.containsKey(cls))
        {
            // Get the cache of field for the class.
            map = (HashMap) values.get(cls);
        }
        else
        {
            // The class does not already exist in the cache to create a new cache for its fields.
            map = new HashMap();

            // Cache the new field cache against the class.
            values.put(cls, map);
        }

        // Store the attribute in the field cache for the class.
        map.put(attr, val);
    }

Places the specified value into the memento based on the field's declaring class and name.

@param cls  The class in which the field is declared.
@param attr The name of the attribute.
@param val  The value to store into this memento.

Places the specified value into the memento based on the field s declaring class and name .


public Collection getAllFieldNames(Class cls)
    {
        /*log.fine("public Collection getAllFieldNames(Class cls): called");*/

        // See if the class exists in the cache
        if (!values.containsKey(cls))
        {
            // Class not in cache so return null
            return null;
        }

        // Get the cache of fields for the class
        Map map = (HashMap) values.get(cls);

        // Return all the keys from cache of fields
        return map.keySet();
    }

Generates a list of all the fields of the object that this memento maps for a given class.

@param  cls The class to get all field names for.

@return A collection of the field names or null if the specified class is not part of the objects class hierarchy
chain.

Generates a list of all the fields of the object that this memento maps for a given class .


public void execute() throws MojoExecutionException, MojoFailureException
    {
        //log.debug("public void execute() throws MojoExecutionException: called");

        // Turn each of the test runner command lines into a script.
        for (String commandName : commands.keySet())
        {
            if (prodScriptOutDirectory != null)
            {
                writeUnixScript(commandName, prodScriptOutDirectory);
                writeWindowsScript(commandName, prodScriptOutDirectory);
            }
        }
    }

Implementation of the prod-script goal.

@throws org.apache.maven.plugin.MojoExecutionException

Implementation of the prod - script goal .


public boolean offer(E o)
    {
        /*log.fine("public boolean offer(E o): called");*/
        /*log.fine("o = " + o);*/

        // Ensure that the item to add is not null.
        if (o == null)
        {
            throw new IllegalArgumentException("The 'o' parameter may not be null.");
        }

        // Derive the integer priority of the element using the priority function, shift it into this queues range if
        // necessary and adjust it to any offset caused by lowest priority not equal to zero.
        int level = priorityToLevel(p.apply(o));
        /*log.fine("offer level = " + level);*/

        // Create a new node to hold the new data element.
        Node<E> newNode = new DataNode<E>(o, markers[level + 1]);

        // Add the element to the tail of the queue with matching level, looping until this can complete as an atomic
        // operation.
        while (true)
        {
            // Get tail and next ref. Would expect next ref to be null, but other thread may update it.
            Node<E> t = markers[level + 1].getTail();
            Node<E> s = t.getNext();

            /*log.fine("t = " + t);*/
            /*log.fine("s = " + s);*/

            // Recheck the tail ref, to ensure other thread has not already moved it. This can potentially prevent
            // a relatively expensive compare and set from failing later on, if another thread has already shited
            // the tail.
            if (t == markers[level + 1].getTail())
            {
                /*log.fine("t is still the tail.");*/

                // Check that the next element reference on the tail is the tail marker, to confirm that another thread
                // has not updated it. Again, this may prevent a cas from failing later.
                if (s == markers[level + 1])
                {
                    /*log.fine("s is  the tail marker.");*/

                    // Try to join the new tail onto the old one.
                    if (t.casNext(s, newNode))
                    {
                        // The tail join was succesfull, so now update the queues tail reference. No conflict should
                        // occurr here as the tail join was succesfull, so its just a question of updating the tail
                        // reference. A compare and set is still used because ...
                        markers[level + 1].casTail(t, newNode);

                        // Increment the queue size count.
                        count.incrementAndGet();

                        return true;
                    }
                }

                // Update the tail reference, other thread may also be doing the same.
                else
                {
                    // Why bother doing this at all? I suppose, because another thread may be stalled and doing this
                    // will enable this one to keep running.
                    // Update the tail reference for the queue because another thread has already added a new tail
                    // but not yet managed to update the tail reference.
                    markers[level + 1].casTail(t, s);
                }
            }
        }
    }

Inserts the specified element onto the tail of this queue.

@param  o the element to add, may not be null.

@return <tt>true</tt> (as per the general contract of <tt>Queue.offer</tt>).

@todo   Compare and set possibly not needed after the succesfull tail join. Straight update looks like it should
work? I may have missed something here.

Inserts the specified element onto the tail of this queue .


public E poll()
    {
        /*log.fine("public E poll(): called");*/

        // This is used to keep track of the level of the list that is found to have data in it.
        int currentLevel = 0;

        while (true)
        {
            // This is used to locate the marker head of a list that contains data.
            Marker<E> h = null;

            // This is used to locate the potential data node of a list with data in it. Another thread may already
            // have taken this data.
            Node<E> first = null;

            // Second data item, may also be tail marker, first data item of next list, or null at end of last list.
            Node<E> second = null;

            // Loop down any empty lists at the front of the queue until a list with data in it is found.
            for (; currentLevel < n; currentLevel++)
            {
                h = markers[currentLevel];
                first = h.getNext();
                second = first.getNext();

                // Check if the list at the current level is not empty and should be tried for data.
                if (!h.isEmpty(markers[currentLevel + 1]))
                {
                    break;
                }

                // Check if the current level is empty and is the last level, in which case return null.
                else if (currentLevel == (n - 1))
                {
                    // log.info("returning null from level loop.");

                    return null;
                }

                // Else if the current level is empty loop to the next one to see if it has data.
            }

            /*log.fine("current poll level = " + currentLevel);*/

            // This is used to locate the tail of the list that has been found with data in it.
            Node<E> t = markers[currentLevel + 1].getTail();

            // Check that the first data item has not yet been taken. Another thread may already have taken it,
            // in which case performing a relatively expensive cas on the head will fail. If first is still intact
            // then second will be intact too.
            if (first == h.getNext())
            {
                // Check if the queue has become empty.
                if (h.isEmpty(markers[currentLevel + 1]))
                {
                    // Another thread has managed to take data from the queue, leaving it empty.

                    // First won't be null. It may point to tail though...
                    if (first == null)
                    {
                        // Don't want to return here, want to try the next list. The list loop has a return null
                        // once it gets to the end to take care of that.
                        // log.info("returning null as first == null");

                        return null;
                    }
                    else
                    {
                        // Not sure yet why castail here? Does this repair a broken tail ref left after the last item
                        // was taken?
                        markers[currentLevel + 1].casTail(t, first);
                    }
                }

                // The queue contains data, so try to move its head marker reference from the first data item, onto the
                // second item (which may be data, or the tail marker). If this succeeds, then the first data node
                // has been atomically extracted from the head of the queue.
                else if (h.casNext(first, second))
                {
                    // h Does not refer to an empty queue, so first must be a data node.
                    DataNode<E> firstDataNode = ((DataNode<E>) first);
                    E item = firstDataNode.getItem();

                    // Even though the empty test did not indicate that the list was empty, it may contain null
                    // data items, because the remove method doesn't extract nodes on a remove. These need to be skipped
                    // over. Could they be removed here?
                    if (item != null)
                    {
                        firstDataNode.setItem(null);

                        /*log.fine("returing item = " + item);*/

                        // Decrement the queue size count.
                        count.decrementAndGet();

                        return item;
                    }

                    // else skip over deleted item, continue trying at this level. Go back an retry starting from same
                    // level. List at this level may now be empty, or may get the next item from it.

                    // else skip over marker element. just make markers return null for item to skip them? No, because
                    // need to advance currentLevel and get head and tail markers for the next level. but then, next
                    // level advance will occur when this level is retried and found to be empty won't it?
                }
            }
        }
    }

Retrieves and removes the head of this queue, or null if this queue is empty.

<p/>This method will make a single pass down the queue, starting from the highest priority and working down to
the lowest. If it fails to extract an element from the queue on this single pass, it will return null. It is
possible that the queue contains transient data during this pass that this method does not manage to extract,
because other threads managed to take the data, or because other threads inserted higher priority data once this
pass was already further down the queue.

@return The head of this queue, or null if this queue is empty.

Retrieves and removes the head of this queue or null if this queue is empty .


public SearchNode<O, T> createSearchNode(T state)
    {
        return new SearchNode<O, T>(state);
    }

public SearchNode < O , T > createSearchNode ( T state ) { return new SearchNode < O , T > ( state ) ; }

Creates the correct type of search nodes for this search. This search uses ordinary search nodes.

@param  state The search space state to create a search node for.

@return The state encapsulated in an ordinary search node.

Creates the correct type of search nodes for this search . This search uses ordinary search nodes .


public Queue<SearchNode<O, T>> createQueue()
    {
        return new PriorityQueue<SearchNode<O, T>>(11, new UniformCostComparator());
    }

public Queue < SearchNode < O , T > > createQueue ( ) { return new PriorityQueue < SearchNode < O , T > > ( 11 , new UniformCostComparator ( ) ) ; }

Creates the correct type of queue for this search. This search uses a priority queue ordered by path cost.

@return An empty priority queue with path cost.

Creates the correct type of queue for this search . This search uses a priority queue ordered by path cost .


public static TermWalker simpleWalker(TermVisitor visitor)
    {
        DepthFirstBacktrackingSearch<Term, Term> search = new DepthFirstBacktrackingSearch<Term, Term>();

        return new TermWalker(search, new DefaultTraverser(), visitor);
    }

public static TermWalker simpleWalker ( TermVisitor visitor ) { DepthFirstBacktrackingSearch < Term , Term > search = new DepthFirstBacktrackingSearch < Term , Term > ( ) ; return new TermWalker ( search , new DefaultTraverser ( ) , visitor ) ; }

Provides a simple depth first walk over a term.

@param  visitor The visitor to apply to each term.

@return A simple depth first walk over a term.

Provides a simple depth first walk over a term .


public static TermWalker goalWalker(UnaryPredicate<Term> unaryPredicate, TermVisitor visitor)
    {
        TermWalker walker = simpleWalker(visitor);
        walker.setGoalPredicate(unaryPredicate);

        return walker;
    }

public static TermWalker goalWalker ( UnaryPredicate < Term > unaryPredicate , TermVisitor visitor ) { TermWalker walker = simpleWalker ( visitor ) ; walker . setGoalPredicate ( unaryPredicate ) ; return walker ; }

Provides a depth first walk over a term, visiting only when a goal predicate matches.

@param  unaryPredicate The goal predicate.
@param  visitor        The visitor to apply to each term.

@return A depth first walk over a term, visiting only when a goal predicate matches.

Provides a depth first walk over a term visiting only when a goal predicate matches .


public static TermWalker positionalWalker(PositionalTermVisitor visitor)
    {
        PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
        positionalTraverser.setContextChangeVisitor(visitor);
        visitor.setPositionalTraverser(positionalTraverser);

        return new TermWalker(new DepthFirstBacktrackingSearch<Term, Term>(), positionalTraverser, visitor);
    }

public static TermWalker positionalWalker ( PositionalTermVisitor visitor ) { PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl ( ) ; positionalTraverser . setContextChangeVisitor ( visitor ) ; visitor . setPositionalTraverser ( positionalTraverser ) ; return new TermWalker ( new DepthFirstBacktrackingSearch < Term , Term > ( ) , positionalTraverser , visitor ) ; }

Provides a positional depth first walk over a term.

@param  visitor The visitor to apply to each term, and to notify of positional context changes.

@return A positional depth first walk over a term.

Provides a positional depth first walk over a term .


public static TermWalker positionalGoalWalker(UnaryPredicate<Term> unaryPredicate, PositionalTermVisitor visitor)
    {
        TermWalker walker = positionalWalker(visitor);
        walker.setGoalPredicate(unaryPredicate);

        return walker;
    }

public static TermWalker positionalGoalWalker ( UnaryPredicate < Term > unaryPredicate , PositionalTermVisitor visitor ) { TermWalker walker = positionalWalker ( visitor ) ; walker . setGoalPredicate ( unaryPredicate ) ; return walker ; }

Provides a positional depth first walk over a term, visiting only when a goal predicate matches.

@param  unaryPredicate The goal predicate.
@param  visitor        The visitor to apply to each term.

@return A positional depth first walk over a term, visiting only when a goal predicate matches.

Provides a positional depth first walk over a term visiting only when a goal predicate matches .


public static TermWalker positionalPostfixWalker(PositionalTermVisitor visitor)
    {
        PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl();
        positionalTraverser.setContextChangeVisitor(visitor);
        visitor.setPositionalTraverser(positionalTraverser);

        return new TermWalker(new PostFixSearch<Term, Term>(), positionalTraverser, visitor);
    }

public static TermWalker positionalPostfixWalker ( PositionalTermVisitor visitor ) { PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl ( ) ; positionalTraverser . setContextChangeVisitor ( visitor ) ; visitor . setPositionalTraverser ( positionalTraverser ) ; return new TermWalker ( new PostFixSearch < Term , Term > ( ) , positionalTraverser , visitor ) ; }

Provides a positional postfix walk over a term.

@param  visitor The visitor to apply to each term, and to notify of positional context changes.

@return A positional postfix first walk over a term.

Provides a positional postfix walk over a term .


public static Properties getProperties(InputStream is) throws IOException
    {
        /*log.fine("getProperties(InputStream): called");*/

        // Create properties object laoded from input stream
        Properties properties = new Properties();

        properties.load(is);

        return properties;
    }

Get properties from an input stream.

@param  is The input stream.

@return The properties loaded from the input stream.

@throws IOException If the is an I/O error reading from the stream.


public static Properties getProperties(File file) throws IOException
    {
        /*log.fine("getProperties(File): called");*/

        // Open the file as an input stream
        InputStream is = new FileInputStream(file);

        // Create properties object loaded from the stream
        Properties properties = getProperties(is);

        // Close the file
        is.close();

        return properties;
    }

Get properties from a file.

@param  file The file.

@return The properties loaded from the file.

@throws IOException If there is an I/O error reading from the file.


public static Properties getProperties(URL url) throws IOException
    {
        /*log.fine("getProperties(URL): called");*/

        // Open the URL as an input stream
        InputStream is = url.openStream();

        // Create properties object loaded from the stream
        Properties properties = getProperties(is);

        // Close the url
        is.close();

        return properties;
    }

Get properties from a url.

@param  url The URL.

@return The properties loaded from the url.

@throws IOException If there is an I/O error reading from the URL.


public static Properties getProperties(String pathname) throws IOException
    {
        /*log.fine("getProperties(String): called");*/

        // Check that the path is not null
        if (pathname == null)
        {
            return null;
        }

        // Check if the path is a URL
        if (isURL(pathname))
        {
            // The path is a URL
            return getProperties(new URL(pathname));
        }
        else
        {
            // Assume the path is a file name
            return getProperties(new File(pathname));
        }
    }

Get properties from a path name. The path name may refer to either a file or a URL.

@param  pathname The path name.

@return The properties loaded from the file or URL.

@throws IOException If there is an I/O error reading from the URL or file named by the path.

Get properties from a path name . The path name may refer to either a file or a URL .


protected Dimension computeGridSize()
    {
        int cols = model.getWidth();
        int rows = model.getHeight();

        int horizSeparatorSize = 0;

        for (int size : model.getHorizontalSeparators().values())
        {
            horizSeparatorSize += size;
        }

        int vertSeparatorSize = 0;

        for (int size : model.getVerticalSeparators().values())
        {
            vertSeparatorSize += size;
        }

        return new Dimension(vertSeparatorSize + colToX(cols), horizSeparatorSize + rowToY(rows));
    }

protected Dimension computeGridSize ( ) { int cols = model . getWidth ( ) ; int rows = model . getHeight ( ) ; int horizSeparatorSize = 0 ; for ( int size : model . getHorizontalSeparators ( ) . values ( ) ) { horizSeparatorSize += size ; } int vertSeparatorSize = 0 ; for ( int size : model . getVerticalSeparators ( ) . values ( ) ) { vertSeparatorSize += size ; } return new Dimension ( vertSeparatorSize + colToX ( cols ) , horizSeparatorSize + rowToY ( rows ) ) ; }

Computes the rendered dimensions of the text grid model, on screen. Used for sizing this component.

@return The on-screen dimensions of the rendered text grid model.

Computes the rendered dimensions of the text grid model on screen . Used for sizing this component .


private void initializeFontMetrics()
    {
        if (!fontMetricsInitialized)
        {
            FontMetrics fontMetrics = getFontMetrics(getFont());
            charWidth = fontMetrics.charWidth(' ');
            charHeight = fontMetrics.getHeight();
            descent = fontMetrics.getDescent();
            fontMetricsInitialized = true;
        }
    }

private void initializeFontMetrics ( ) { if ( ! fontMetricsInitialized ) { FontMetrics fontMetrics = getFontMetrics ( getFont ( ) ) ; charWidth = fontMetrics . charWidth ( ' ' ) ; charHeight = fontMetrics . getHeight ( ) ; descent = fontMetrics . getDescent ( ) ; fontMetricsInitialized = true ; } }

Sets up metrics relating to the size of the font used to display the text grid. This only needs to be done once
but this method can be called many times as it is guarded by an initialization flag to prevent these being
calculated many times.

Sets up metrics relating to the size of the font used to display the text grid . This only needs to be done once but this method can be called many times as it is guarded by an initialization flag to prevent these being calculated many times .


public void addPropertyChangeListener(PropertyChangeListener l)
    {
        // Check if the listneres list has been initialized
        if (listeners == null)
        {
            // Listeneres list not intialized so create a new list
            listeners = new ArrayList();
        }

        synchronized (listeners)
        {
            // Add the new listener to the list
            listeners.add(l);
        }
    }

Adds a property changed listener to be notified of changes to the application state.

@param l The listener.

Adds a property changed listener to be notified of changes to the application state .


public void addPropertyChangeListener(String p, PropertyChangeListener l)
    {
        // Check if the listeneres list has been initialized
        if (listeners == null)
        {
            // Listeneres list not initialized so create a new list
            listeners = new ArrayList();
        }

        synchronized (listeners)
        {
            // Add the new listener to the list
            listeners.add(l);
        }
    }

Adds a property changed listener to be notified of changes to the named property.

@param l The listener/
@param p The property (ignored, notifies of changes to any properties).

Adds a property changed listener to be notified of changes to the named property .


public void removePropertyChangeListener(String p, PropertyChangeListener l)
    {
        if (listeners == null)
        {
            return;
        }

        synchronized (listeners)
        {
            listeners.remove(l);
        }
    }

public void removePropertyChangeListener ( String p , PropertyChangeListener l ) { if ( listeners == null ) { return ; } synchronized ( listeners ) { listeners . remove ( l ) ; } }

Removes the specified property change listener from the list of active listeners.

@param p Ignored. In future will be used to name the specific property to remove the listener for.
@param l The property change listener to remove.

Removes the specified property change listener from the list of active listeners .


protected void firePropertyChange(PropertyChangeEvent evt)
    {
        /*log.fine("firePropertyChange: called");*/

        // Take a copy of the event as a final variable so that it can be used in an inner class
        final PropertyChangeEvent finalEvent = evt;

        Iterator it;

        // Check if the list of listeners is empty
        if (listeners == null)
        {
            // There are no listeners so simply return without doing anything
            return;
        }

        // synchronize on the list of listeners to prevent comodification
        synchronized (listeners)
        {
            // Cycle through all listeners and notify them
            it = listeners.iterator();

            while (it.hasNext())
            {
                // Get the next listener from the list
                final PropertyChangeListener l = (PropertyChangeListener) it.next();

                // Notify the listener of the property change event
                Runnable r =
                    new Runnable()
                    {
                        public void run()
                        {
                            // Fire a property change event
                            l.propertyChange(finalEvent);
                        }
                    };

                // Run the property change event in the Swing event queue
                SwingUtilities.invokeLater(r);
            }
        }
    }

Notifies all property change listeners of the given PropertyChangeEvent.

@param evt The property change event to pass to all listeners.

Notifies all property change listeners of the given PropertyChangeEvent .


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

        synchronized (DOUBLE_RANGE_TYPES)
        {
            // Add the newly created type to the map of all types.
            DoubleRangeType newType = new DoubleRangeType(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.
            DoubleRangeType oldType = DOUBLE_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
            {
                DOUBLE_RANGE_TYPES.put(name, newType);

                return newType;
            }
        }
    }

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

@param  name The name of the double 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 double range type.

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

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


public void doFade(ColorDelta target, String groupName)
    {
        FadeState fadeState = timers.get(groupName);

        // Set up the color interpolator.
        Iterator<Color> interpolator = new ColorInterpolator(startColor, endColor, 8).iterator();

        if (fadeState == null)
        {
            // Create a new fade state for the target group, and a timer to run it.
            Timer timer = new Timer(20, this);

            fadeState = new FadeState(timer, target, interpolator);
            timers.put(groupName, fadeState);
        }
        else
        {
            // Kill any previous fade and replace the target with the new one.
            fadeState.timer.stop();
            fadeState.target = target;
            fadeState.interpolator = interpolator;
        }

        // Iterate to the initial color.
        Color firstColor = fadeState.interpolator.next();
        fadeState.target.changeColor(firstColor);

        // Kick off the fade timer.
        fadeState.timer.setActionCommand(groupName);
        fadeState.timer.setInitialDelay(400);
        fadeState.timer.start();
    }

Requests a color fade against the specified target, under a group name.

@param target    The color delta target.
@param groupName The group name for the fade. See class level comment for {@link FaderImpl} for an explanation of
how the group name is used.

Requests a color fade against the specified target under a group name .


private void showHorizontalBar()
    {
        // Left vertical bar.
        Component bar = factory.createGripPanel(layout.getConsoleHeightResizer(), false);

        frame.getContentPane().add(bar, DesktopAppLayout.STATUS_BAR);
    }

private
void
showHorizontalBar
(
)
{
// Left vertical bar.
Component
bar
=
factory
.
createGripPanel
(
layout
.
getConsoleHeightResizer
(
)
,
false
)
;
frame
.
getContentPane
(
)
.
add
(
bar
,
DesktopAppLayout
.
STATUS_BAR
)
;
}

Creates a horizontal grip-able bar for adjusting the console height.

Creates a horizontal grip - able bar for adjusting the console height .


private void showLeftBar()
    {
        // Left vertical bar.
        Component bar = factory.createGripPanel(layout.getLeftPaneWidthResizer(), true);

        frame.getContentPane().add(bar, DesktopAppLayout.LEFT_VERTICAL_BAR);
    }

private
void
showLeftBar
(
)
{
// Left vertical bar.
Component
bar
=
factory
.
createGripPanel
(
layout
.
getLeftPaneWidthResizer
(
)
,
true
)
;
frame
.
getContentPane
(
)
.
add
(
bar
,
DesktopAppLayout
.
LEFT_VERTICAL_BAR
)
;
}

Creates a vertical grip-able bar for adjusting the left panel width.

Creates a vertical grip - able bar for adjusting the left panel width .


private void showRightBar()
    {
        // Right vertical bar.
        Component bar = factory.createGripPanel(layout.getRightPaneWidthResizer(), true);

        frame.getContentPane().add(bar, DesktopAppLayout.RIGHT_VERTICAL_BAR);
    }

private
void
showRightBar
(
)
{
// Right vertical bar.
Component
bar
=
factory
.
createGripPanel
(
layout
.
getRightPaneWidthResizer
(
)
,
true
)
;
frame
.
getContentPane
(
)
.
add
(
bar
,
DesktopAppLayout
.
RIGHT_VERTICAL_BAR
)
;
}

Creates a vertical grip-able bar for adjusting the right panel width.

Creates a vertical grip - able bar for adjusting the right panel width .


private static void sanitizeRadioControls(FormElement form)
	{
		Map<String, Element> controlsByName = new HashMap<String, Element>();

		for (Element control : form.elements())
		{
			// cannot use Element.select since Element.hashCode collapses like elements
			if ("radio".equals(control.attr("type")) && control.hasAttr("checked"))
			{
				String name = control.attr("name");

				if (controlsByName.containsKey(name))
				{
					controlsByName.get(name).attr("checked", false);
				}

				controlsByName.put(name, control);
			}
		}
	}

Ensures that radio controls are mutually exclusive within control groups.

Ensures that radio controls are mutually exclusive within control groups .


public void await(T t) throws InterruptedException
    {
        synchronized (monitor)
        {
            long waitNanos = evaluateWithWaitTimeNanos(t);

            // Loop forever until all conditions pass or the thread is interrupted.
            while (waitNanos > 0)
            {
                // If some conditions failed, then wait for the shortest wait time, or until the thread is woken up by
                // a signal, before re-evaluating conditions.
                long milliPause = waitNanos / 1000000;
                int nanoPause = (int) (waitNanos % 1000000);

                monitor.wait(milliPause, nanoPause);

                waitNanos = evaluateWithWaitTimeNanos(t);
            }
        }
    }

Wait for the predicate to become true on the specified object.

@param  t The object to test for predicate membership.

@throws InterruptedException If interrupted whilst waiting.

Wait for the predicate to become true on the specified object .


public boolean await(T t, long timeout, TimeUnit unit) throws InterruptedException
    {
        synchronized (monitor)
        {
            // Holds the absolute time when the timeout expires.
            long expiryTimeNanos = System.nanoTime() + unit.toNanos(timeout);

            // Used to hold the estimated wait time until the condition may pass.
            long waitNanos = evaluateWithWaitTimeNanos(t);

            // Loop forever until all conditions pass, the timeout expires, or the thread is interrupted.
            while (waitNanos > 0)
            {
                // Check how much time remains until the timeout expires.
                long remainingTimeNanos = expiryTimeNanos - System.nanoTime();

                // Check if the timeout has expired.
                if (remainingTimeNanos <= 0)
                {
                    return false;
                }

                // If some conditions failed, then wait for the shortest of the wait time or the remaining time until the
                // timout expires, or until the thread is woken up by a signal, before re-evaluating conditions.
                long timeToPauseNanos = (waitNanos < remainingTimeNanos) ? waitNanos : remainingTimeNanos;

                long milliPause = timeToPauseNanos / 1000000;
                int nanoPause = (int) (timeToPauseNanos % 1000000);

                monitor.wait(milliPause, nanoPause);

                // Re-evelaute the condition and obtain a new estimate of how long until it may pass.
                waitNanos = evaluateWithWaitTimeNanos(t);
            }
        }

        // All conditions have passed when the above loop terminates.
        return true;
    }

Wait for up to a timeout limit for the predicate to become true on the specified object.

@param  t       The object to test for predicate membership.
@param  timeout The amount of time to wait.
@param  unit    The units of time used.

@return <tt>true</tt> if the predicate became true before the timeout expired, <tt>false</tt> otherwise.

@throws InterruptedException If interrupted whilst waiting.

Wait for up to a timeout limit for the predicate to become true on the specified object .


public void execute() throws MojoExecutionException, MojoFailureException
    {
        //log.debug("public void execute() throws MojoExecutionException: called");

        // Turn each of the test runner command lines into a script.
        for (String commandName : commands.keySet())
        {
            if (scriptOutDirectory != null)
            {
                writeUnixScript(commandName, scriptOutDirectory);
                writeWindowsScript(commandName, scriptOutDirectory);
            }
        }
    }

Implementation of the script goal.

@throws MojoExecutionException


protected String appendClasspath(String commandLine, boolean unix)
    {
        String pathSeperator;
        String seperator;

        if (unix)
        {
            pathSeperator = "/";
            seperator = ":";
        }
        else
        {
            pathSeperator = "\\";
            seperator = ";";
        }

        for (Iterator i = classpathElements.iterator(); i.hasNext();)
        {
            String cpPath = (String) i.next();

            cpPath = cpPath.replace("/", pathSeperator);

            commandLine += cpPath + (i.hasNext() ? seperator : "");
        }

        return commandLine;
    }

protected String appendClasspath ( String commandLine , boolean unix ) { String pathSeperator ; String seperator ; if ( unix ) { pathSeperator = "/" ; seperator = ":" ; } else { pathSeperator = "\\" ; seperator = ";" ; } for ( Iterator i = classpathElements . iterator ( ) ; i . hasNext ( ) ; ) { String cpPath = ( String ) i . next ( ) ; cpPath = cpPath . replace ( "/" , pathSeperator ) ; commandLine += cpPath + ( i . hasNext ( ) ? seperator : "" ) ; } return commandLine ; }

Appends the classpath onto the command line.

@param  commandLine The command line to append to.
@param  unix        <tt>true</tt> to use unix paths, <tt>false</tt> to use windows.

@return The appended to command line.

Appends the classpath onto the command line .


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

        synchronized (DATE_RANGE_TYPES)
        {
            // Add the newly created type to the map of all types.
            DateRangeType newType = new DateRangeType(name, from, to);

            // 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.
            DateRangeType oldType = DATE_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
            {
                DATE_RANGE_TYPES.put(name, newType);

                return newType;
            }
        }
    }

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

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

@return A new date range type.

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

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


private void printIntroduction()
    {
        System.out.println("| LoJiX Prolog.");
        System.out.println("| Copyright The Sett Ltd.");
        System.out.println("| Licensed under the Apache License, Version 2.0.");
        System.out.println("| //www.apache.org/licenses/LICENSE-2.0");
        System.out.println();
    }


private ConsoleReader initializeCommandLineReader() throws IOException
    {
        ConsoleReader reader = new ConsoleReader();
        reader.setBellEnabled(false);

        return reader;
    }

private ConsoleReader initializeCommandLineReader ( ) throws IOException { ConsoleReader reader = new ConsoleReader ( ) ; reader . setBellEnabled ( false ) ; return reader ; }

Sets up the JLine console reader.

@return A JLine console reader.

@throws IOException If an IO error is encountered while reading the input.


private void evaluate(Sentence<Clause> sentence) throws SourceCodeException
    {
        Clause clause = sentence.getT();

        if (clause.isQuery())
        {
            engine.endScope();
            engine.compile(sentence);
            evaluateQuery();
        }
        else
        {
            // Check if the program clause is new, or a continuation of the current predicate.
            int name = clause.getHead().getName();

            if ((currentPredicateName == null) || (currentPredicateName != name))
            {
                engine.endScope();
                currentPredicateName = name;
            }

            addProgramClause(sentence);
        }
    }

Evaluates a query against the resolver or adds a clause to the resolvers domain.

@param  sentence The clausal sentence to run as a query or as a clause to add to the domain.

@throws SourceCodeException If the query or domain clause fails to compile or link into the resolver.

Evaluates a query against the resolver or adds a clause to the resolvers domain .


private void evaluateQuery()
    {
        /*log.fine("Read query from input.");*/

        // Create an iterator to generate all solutions on demand with. Iteration will stop if the request to
        // the parser for the more ';' token fails.
        Iterator<Set<Variable>> i = engine.iterator();

        if (!i.hasNext())
        {
            System.out.println("false. ");

            return;
        }

        for (; i.hasNext();)
        {
            Set<Variable> solution = i.next();

            if (solution.isEmpty())
            {
                System.out.print("true");
            }
            else
            {
                for (Iterator<Variable> j = solution.iterator(); j.hasNext();)
                {
                    Variable nextVar = j.next();

                    String varName = engine.getVariableName(nextVar.getName());

                    System.out.print(varName + " = " + nextVar.getValue().toString(engine, true, false));

                    if (j.hasNext())
                    {
                        System.out.println();
                    }
                }
            }

            // Finish automatically if there are no more solutions.
            if (!i.hasNext())
            {
                System.out.println(".");

                break;
            }

            // Check if the user wants more solutions.
            try
            {
                int key = consoleReader.readVirtualKey();

                if (key == SEMICOLON)
                {
                    System.out.println(" ;");
                }
                else
                {
                    System.out.println();

                    break;
                }
            }
            catch (IOException e)
            {
                throw new IllegalStateException(e);
            }
        }
    }

Evaluates a query. In the case of queries, the interner is used to recover textual names for the resulting
variable bindings. The user is queried through the parser to if more than one solution is required.

Evaluates a query . In the case of queries the interner is used to recover textual names for the resulting variable bindings . The user is queried through the parser to if more than one solution is required .


public static MultiTypeData getMultiTypeData(boolean b)
    {
        // Convert the value to a String and return the set of types that that String can be converted to.
        MultiTypeData result = getMultiTypeData(Boolean.toString(b));
        result.nativeType = BOOLEAN;

        return result;
    }

Converts a boolean into a multi type data object.

@param  b The boolean to convert.

@return A multi type data object holding all the types that the boolean can be converted into.

Converts a boolean into a multi type data object .


public static MultiTypeData getMultiTypeData(byte b)
    {
        // Convert the value to a String and return the set of types that that String can be converted to.
        MultiTypeData result = getMultiTypeData(Byte.toString(b));
        result.nativeType = BYTE;

        return result;
    }

Converts a byte into a multi type data object.

@param  b The byte to convert.

@return A multi type data object holding all the types that the byte can be converted into.

Converts a byte into a multi type data object .


public static MultiTypeData getMultiTypeData(char c)
    {
        // Convert the value to a String and return the set of types that that String can be converted to.
        MultiTypeData result = getMultiTypeData(Character.toString(c));
        result.nativeType = CHAR;

        return result;
    }

Converts a char into a multi type data object.

@param  c The char to convert.

@return A multi type data object holding all the types that the char can be converted into.

Converts a char into a multi type data object .


public static MultiTypeData getMultiTypeData(short s)
    {
        // Convert the value to a String and return the set of types that that String can be converted to.
        MultiTypeData result = getMultiTypeData(Short.toString(s));
        result.nativeType = SHORT;

        return result;
    }

Converts a short into a multi type data object.

@param  s The short to convert.

@return A multi type data object holding all the types that the short can be converted into.

Converts a short into a multi type data object .


public static MultiTypeData getMultiTypeData(int i)
    {
        // Convert the value to a String and return the set of types that that String can be converted to.
        MultiTypeData result = getMultiTypeData(Integer.toString(i));
        result.nativeType = INT;

        return result;
    }

Converts a int into a multi type data object.

@param  i The int to convert.

@return A multi type data object holding all the types that the int can be converted into.

Converts a int into a multi type data object .


public static MultiTypeData getMultiTypeData(long l)
    {
        // Convert the value to a String and return the set of types that that String can be converted to.
        MultiTypeData result = getMultiTypeData(Long.toString(l));
        result.nativeType = LONG;

        return result;
    }

Converts a long into a multi type data object.

@param  l The long to convert.

@return A multi type data object holding all the types that the long can be converted into.

Converts a long into a multi type data object .


public static MultiTypeData getMultiTypeData(float f)
    {
        // Convert the value to a String and return the set of types that that String can be converted to.
        MultiTypeData result = getMultiTypeData(Float.toString(f));
        result.nativeType = FLOAT;

        return result;
    }

Converts a float into a multi type data object.

@param  f The float to convert.

@return A multi type data object holding all the types that the float can be converted into.

Converts a float into a multi type data object .


public static MultiTypeData getMultiTypeData(double d)
    {
        // Convert the value to a String and return the set of types that that String can be converted to.
        MultiTypeData result = getMultiTypeData(Double.toString(d));
        result.nativeType = DOUBLE;

        return result;
    }

Converts a double into a multi type data object.

@param  d The double to convert.

@return A multi type data object holding all the types that the double can be converted into.

Converts a double into a multi type data object .


public static MultiTypeData getMultiTypeData(String s)
    {
        MultiTypeData result = new MultiTypeData();

        // Start by assuming that the String can only be converted to a String.
        result.typeFlags = STRING;
        result.stringValue = s;

        // Assume that the native type is String. It is up to methods that call this one to override this if this is
        // not the case.
        result.nativeType = STRING;

        // Check if the string can be converted to a boolean.
        if ("true".equals(s))
        {
            result.booleanValue = true;
            result.typeFlags |= BOOLEAN;
        }
        else if ("false".equals(s))
        {
            result.booleanValue = false;
            result.typeFlags |= BOOLEAN;
        }

        // Check if the string can be converted to an int.
        try
        {
            result.intValue = Integer.parseInt(s);
            result.typeFlags |= INT;
        }
        catch (NumberFormatException e)
        {
            // Exception noted so can be ignored.
            e = null;

            result.typeFlags &= (Integer.MAX_VALUE - INT);
        }

        // Check if the string can be converted to a byte.
        try
        {
            result.byteValue = Byte.parseByte(s);
            result.typeFlags |= BYTE;
        }
        catch (NumberFormatException e)
        {
            // Exception noted so can be ignored.
            e = null;

            result.typeFlags = (Integer.MAX_VALUE - BYTE);
        }

        // Check if the string can be converted to a char.
        if (s.length() == 1)
        {
            result.charValue = s.charAt(0);
            result.typeFlags |= CHAR;
        }

        // Check if the string can be converted to a short.
        try
        {
            result.shortValue = Short.parseShort(s);
            result.typeFlags |= SHORT;
        }
        catch (NumberFormatException e)
        {
            // Exception noted so can be ignored.
            e = null;

            result.typeFlags = (Integer.MAX_VALUE - SHORT);
        }

        // Check if the string can be converted to a long.
        try
        {
            result.longValue = Long.parseLong(s);
            result.typeFlags |= LONG;
        }
        catch (NumberFormatException e)
        {
            // Exception noted so can be ignored.
            e = null;

            result.typeFlags = (Integer.MAX_VALUE - LONG);
        }

        // Check if the string can be converted to a float.
        try
        {
            result.floatValue = Float.parseFloat(s);
            result.typeFlags |= FLOAT;
        }
        catch (NumberFormatException e)
        {
            // Exception noted so can be ignored.
            e = null;

            result.typeFlags = (Integer.MAX_VALUE - FLOAT);
        }

        // Check if the string can be converted to a double.
        try
        {
            result.doubleValue = Double.parseDouble(s);
            result.typeFlags |= DOUBLE;
        }
        catch (NumberFormatException e)
        {
            // Exception noted so can be ignored.
            e = null;

            result.typeFlags = (Integer.MAX_VALUE - DOUBLE);
        }

        // Assume the string can never be converted to an object.
        return result;
    }

Converts a String into a multi type data object.

<p/>This method will return the native type as String. Methods that use this one to convert other types via
String should override this with the correct native type.

@param  s The String to convert.

@return A multi type data object holding all the types that the String can be converted into.

Converts a String into a multi type data object .


public static MultiTypeData getMultiTypeData(Object o)
    {
        // Convert the value to a String and return the set of types that that String can be converted to.
        MultiTypeData result = getMultiTypeData(o.toString());
        result.nativeType = OBJECT;

        return result;
    }

Converts a Object into a multi type data object.

@param  o The Object to convert.

@return A multi type data object holding all the types that the Object can be converted into.

Converts a Object into a multi type data object .


public static Object convert(MultiTypeData d, Class c)
    {
        // Check if it is an boolean convertion.
        if (((d.typeFlags & BOOLEAN) != 0) && (Boolean.TYPE.equals(c) || Boolean.class.equals(c)))
        {
            return d.booleanValue;
        }

        // Check if it is an int convertion.
        else if (((d.typeFlags & INT) != 0) && (Integer.TYPE.equals(c) || Integer.class.equals(c)))
        {
            return d.intValue;
        }

        // Check if it is an char convertion.
        else if (((d.typeFlags & CHAR) != 0) && (Character.TYPE.equals(c) || Character.class.equals(c)))
        {
            return d.charValue;
        }

        // Check if it is an byte convertion.
        else if (((d.typeFlags & BYTE) != 0) && (Byte.TYPE.equals(c) || Byte.class.equals(c)))
        {
            return d.byteValue;
        }

        // Check if it is an short convertion.
        else if (((d.typeFlags & SHORT) != 0) && (Short.TYPE.equals(c) || Short.class.equals(c)))
        {
            return d.shortValue;
        }

        // Check if it is an long convertion.
        else if (((d.typeFlags & LONG) != 0) && (Long.TYPE.equals(c) || Long.class.equals(c)))
        {
            return d.longValue;
        }

        // Check if it is an float convertion.
        else if (((d.typeFlags & FLOAT) != 0) && (Float.TYPE.equals(c) || Float.class.equals(c)))
        {
            return d.floatValue;
        }

        // Check if it is an double convertion.
        else if (((d.typeFlags & DOUBLE) != 0) && (Double.TYPE.equals(c) || Double.class.equals(c)))
        {
            return d.doubleValue;
        }

        // Check if it is a string convertion.
        else if (((d.typeFlags & STRING) != 0) && String.class.equals(c))
        {
            return d.stringValue;
        }

        // Check if it is an object convertion and th object types match.
        else if (((d.typeFlags & OBJECT) != 0) && d.objectValue.getClass().equals(c))
        {
            return d.objectValue;
        }

        // Throw a class cast exception if the multi data type cannot be converted to the specified class.
        else
        {
            throw new ClassCastException("The multi data type, " + d + ", cannot be converted to the class, " + c +
                ".");
        }
    }

Given a multi type data object and a class representing a type, this method attemps to return an object of that
class created from the multi type data. The exception to this rule is if the specified data type is a primtive
type, such as int.clas, then the returned object will be of the equivalent wrapper class type, Integer.class in
this case. This is because a primitive cannot be returned under an Object return type.

@param     d The multi type data object to convert.
@param     c The class to convert to.

@return    An object of the specified class which is the result of converting the multi type data object to that
class.

@exception ClassCastException Is thrown if the multi type data object cannot be converted to the specified class.

Given a multi type data object and a class representing a type this method attemps to return an object of that class created from the multi type data . The exception to this rule is if the specified data type is a primtive type such as int . clas then the returned object will be of the equivalent wrapper class type Integer . class in this case . This is because a primitive cannot be returned under an Object return type .


public void put(String name, Object value)
    {
        pageContext.setAttribute(name, value, scope);
    }

public void put ( String name , Object value ) { pageContext . setAttribute ( name , value , scope ) ; }

Inserts an object into the scope.

@param name  The name of the variable to set.
@param value The value to set.


public void clearUpTo(int key)
    {
        if (((start <= key) && (key < (end - 1))))
        {
            // Loop from the start of the data, up to the key to clear up to, clearing all data encountered in-between.
            int newStart;

            for (newStart = start; (newStart <= end) && (newStart <= key); newStart++)
            {
                int offset = offset(newStart);

                if (data[offset] != null)
                {
                    data[offset] = null;
                    count--;
                }
            }

            // Continue on after the clear up to point, until the first non-null entry or end of array is encountered,
            // and make that the new start.
            for (; newStart <= end; newStart++)
            {
                if (data[offset(newStart)] != null)
                {
                    break;
                }
            }

            start = newStart;
        }
        else
        {
            // The key does not lie between the start and end markers, so clear the entire map up to the end
            int newStart;

            for (newStart = start; (newStart <= end); newStart++)
            {
                int offset = offset(newStart);

                if (data[offset] != null)
                {
                    data[offset] = null;
                    count--;
                }
            }

            start = newStart;

            offset = -start;
        }
    }

Clears entries up to and including the specified key, from the map. This is a simple garbage collection operation
to clear consumed data from the circular buffer.

@param key The key to clear up to.

Clears entries up to and including the specified key from the map . This is a simple garbage collection operation to clear consumed data from the circular buffer .


private void expand(int key)
    {
        // Set the new size to whichever is the larger of 1.5 times the old size, or an array large enough to hold
        // the proposed key that caused the expansion.
        int newFactorSize = ((length * 3) / 2) + 1;
        int newSpaceSize = spaceRequired(key);

        int newSize = (newSpaceSize > newFactorSize) ? newSpaceSize : newFactorSize;

        Object[] oldData = data;
        data = new Object[newSize];

        // The valid data in the old array runs from offset(start) to offset(end) when offset(start) < offset(end), and
        // from offset(start) to length - 1 and 0 to offset(end) when offset(start) >= offset(end).
        int offsetStart = offset(start);
        int offsetEnd = offset(end);

        if (offsetStart < offsetEnd)
        {
            System.arraycopy(oldData, offsetStart, data, 0, end - start);
        }
        else
        {
            System.arraycopy(oldData, offsetStart, data, 0, length - offsetStart);
            System.arraycopy(oldData, 0, data, length - offsetStart, offsetEnd);
        }

        offset = -start;
        length = newSize;
    }

Expands the size of the storage to whichever is the larger of 1.5 times the old size, or an array large enough to
hold the proposed key that caused the expansion, copying the old data into a new array.

@param key The key that was too large and caused expansion.

Expands the size of the storage to whichever is the larger of 1 . 5 times the old size or an array large enough to hold the proposed key that caused the expansion copying the old data into a new array .


private void internalInsert(char character, int c, int r)
    {
        maxColumn = (c > maxColumn) ? c : maxColumn;
        maxRow = (r > maxRow) ? r : maxRow;

        data.put((long) c, (long) r, character);
    }

private void internalInsert ( char character , int c , int r ) { maxColumn = ( c > maxColumn ) ? c : maxColumn ; maxRow = ( r > maxRow ) ? r : maxRow ; data . put ( ( long ) c , ( long ) r , character ) ; }

Inserts a single character 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 character The character to insert.
@param c         The column position.
@param r         The row position.

Inserts a single character 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 int compare(SearchNode object1, SearchNode object2)
    {
        float cost1 = object1.getPathCost();
        float cost2 = object2.getPathCost();

        return (cost1 > cost2) ? 1 : ((cost1 < cost2) ? -1 : 0);
    }

public int compare ( SearchNode object1 , SearchNode object2 ) { float cost1 = object1 . getPathCost ( ) ; float cost2 = object2 . getPathCost ( ) ; return ( cost1 > cost2 ) ? 1 : ( ( cost1 < cost2 ) ? - 1 : 0 ) ; }

Compares two search nodes by their path cost.

@param  object1 The first search node to compare.
@param  object2 The second search node to compare.

@return 1 if the first node has a higher path cost than the second, -1 if it has a lower path cost and 0 if they
have the same path cost.

Compares two search nodes by their path cost .


public Term parseOperators(Term[] terms) throws SourceCodeException
    {
        // Initialize the parsers state.
        stack.offer(0);
        state = 0;
        position = 0;
        nextTerm = null;

        // Consume the terms from left to right.
        for (position = 0; position <= terms.length;)
        {
            Symbol nextSymbol;

            // Decide what the next symbol to parse is; candidate op, term or final.
            if (position < terms.length)
            {
                nextTerm = terms[position];

                if (nextTerm instanceof CandidateOpSymbol)
                {
                    nextSymbol = Symbol.Op;
                }
                else
                {
                    nextSymbol = Symbol.Term;
                }
            }
            else
            {
                nextSymbol = Symbol.Final;
            }

            // Look in the action table to find the action associated with the current symbol and state.
            Action action = actionTable[state][nextSymbol.ordinal()];

            // Apply the action.
            action.apply();
        }

        return (Functor) outputStack.poll();
    }

Parses a flat list of terms, which are literals, variables, functors, or operators into a tree in such a way that
the operators associativity and precendence is obeyed.

@param  terms A flat list of terms possibly containing operators, to be parsed.

@return The functor at the root of the sequence of terms parsed into an abstract syntax tree.

@throws SourceCodeException If the list of terms does not form a valid syntactical construction under the current
set of defined operators.

Parses a flat list of terms which are literals variables functors or operators into a tree in such a way that the operators associativity and precendence is obeyed .


public EnumMap<OpSymbol.Fixity, OpSymbol> getOperatorsMatchingNameByFixity(String name)
    {
        return operators.get(name);
    }

public EnumMap < OpSymbol . Fixity , OpSymbol > getOperatorsMatchingNameByFixity ( String name ) { return operators . get ( name ) ; }

Checks the operator table for all possible operators matching a given name.

@param  name The interned name of the operator to find.

@return An array of matching operators, or <tt>null</tt> if none can be found.

Checks the operator table for all possible operators matching a given name .


protected static OpSymbol checkAndResolveToFixity(CandidateOpSymbol candidate, OpSymbol.Fixity... fixities)
        throws SourceCodeException
    {
        OpSymbol result = null;

        for (OpSymbol.Fixity fixity : fixities)
        {
            result = candidate.getPossibleOperators().get(fixity);

            if (result != null)
            {
                break;
            }
        }

        if (result == null)
        {
            throw new SourceCodeException("Operator " + candidate + " must be one of " + Arrays.toString(fixities) +
                ", but does not have the required form.", null, null, null, candidate.getSourceCodePosition());
        }

        return result;
    }

Checks if a candidate operator symbol can have one of the specified fixities, and resolve it to an oeprator with
that fixity if so. If it cannot be resolved an exception is raised.

@param  candidate The candidate operator symbol to resolve.
@param  fixities  The possible fixities to resolve the symbol to.

@return The candidate operator resolved to an actual operator.

@throws SourceCodeException If the candidate operator cannot be resolved.

Checks if a candidate operator symbol can have one of the specified fixities and resolve it to an oeprator with that fixity if so . If it cannot be resolved an exception is raised .


public SearchNode<O, T> makeNode(Successor successor) throws SearchNotExhaustiveException
    {
        SearchNode newNode;

        try
        {
            // Create a new instance of this class
            newNode = getClass().newInstance();

            // Set the state, operation, parent, depth and cost for the new search node
            newNode.state = successor.getState();
            newNode.parent = this;
            newNode.appliedOp = successor.getOperator();
            newNode.depth = depth + 1;
            newNode.pathCost = pathCost + successor.getCost();

            // Check if there is a repeated state filter and copy the reference to it into the new node if so
            if (repeatedStateFilter != null)
            {
                newNode.setRepeatedStateFilter(repeatedStateFilter);
            }

            return newNode;
        }
        catch (InstantiationException e)
        {
            // In practice this should never happen but may if the nodes if some class loader error were to occur whilst
            // using a custom node implementation. Rethrow this as a RuntimeException.
            throw new IllegalStateException("InstantiationException during creation of new search node.", e);
        }
        catch (IllegalAccessException e)
        {
            // In practice this should never happen but may if the nodes to use are not public whilst using a custom node
            // implementation. Rethrow this as a RuntimeException.
            throw new IllegalStateException("IllegalAccessException during creation of new search node.", e);
        }
    }

Makes a new node of the same type as this one from a Successor state.

@param  successor The successor state to turn into a search node.

@return A search node covering the successor state.

@throws SearchNotExhaustiveException If the successor nodes cannot be created. This may happen when using a
custom node implementation that is not publicly accessible or that causes
other class loading/creation errors.

Makes a new node of the same type as this one from a Successor state .


public static String rightPad(String stringToPad, String padder, int size)
    {
        if (padder.length() == 0)
        {
            return stringToPad;
        }

        StringBuffer strb = new StringBuffer(stringToPad);
        CharacterIterator sci = new StringCharacterIterator(padder);

        while (strb.length() < size)
        {
            for (char ch = sci.first(); ch != CharacterIterator.DONE; ch = sci.next())
            {
                if (strb.length() < size)
                {
                    strb.append(String.valueOf(ch));
                }
            }
        }

        return strb.toString();
    }

public static String rightPad ( String stringToPad , String padder , int size ) { if ( padder . length ( ) == 0 ) { return stringToPad ; } StringBuffer strb = new StringBuffer ( stringToPad ) ; CharacterIterator sci = new StringCharacterIterator ( padder ) ; while ( strb . length ( ) < size ) { for ( char ch = sci . first ( ) ; ch != CharacterIterator . DONE ; ch = sci . next ( ) ) { if ( strb . length ( ) < size ) { strb . append ( String . valueOf ( ch ) ) ; } } } return strb . toString ( ) ; }

Right pads a string with a given string to a given size. This method will repeat the padder string as many times
as is necessary until the exact specified size is reached. If the specified size is less than the size of the
original string then the original string is returned unchanged.

<pre>
Example1 - original string "cat", padder string "white", size 8 gives "catwhite".
Example2 - original string "cat", padder string "white", size 15 gives "catwhitewhitewh".
Example3 - original string "cat", padder string "white", size 2 gives "cat".
</pre>

@param  stringToPad The original string.
@param  padder      The string to pad onto the original string.
@param  size        The required size of the new string.

@return The newly padded string.

Right pads a string with a given string to a given size . This method will repeat the padder string as many times as is necessary until the exact specified size is reached . If the specified size is less than the size of the original string then the original string is returned unchanged .


public String getErrors()
    {
        // Return the empty string if there are no errors.
        if (parsingErrors.isEmpty())
        {
            return "";
        }

        // Concatenate all the parsing errors together.
        String result = "";

        for (String s : parsingErrors)
        {
            result += s;
        }

        return result;
    }

Lists all the parsing errors from the most recent parsing in a string.

@return All the parsing errors from the most recent parsing.

Lists all the parsing errors from the most recent parsing in a string .


public String getOptionsInForce()
    {
        // Check if there are no properties to report and return and empty string if so.
        if (parsedProperties == null)
        {
            return "";
        }

        // List all the properties.
        String result = "Options in force:\n";

        for (Map.Entry<Object, Object> property : parsedProperties.entrySet())
        {
            result += property.getKey() + " = " + property.getValue() + "\n";
        }

        return result;
    }

Lists the properties set from the most recent parsing or an empty string if no parsing has been done yet.

@return The properties set from the most recent parsing or an empty string if no parsing has been done yet.

Lists the properties set from the most recent parsing or an empty string if no parsing has been done yet .


public String getUsage()
    {
        String result = "Options:\n";

        int optionWidth = 0;
        int argumentWidth = 0;

        // Calculate the column widths required for aligned layout.
        for (CommandLineOption optionInfo : optionMap.values())
        {
            int oWidth = optionInfo.option.length();
            int aWidth = (optionInfo.argument != null) ? (optionInfo.argument.length()) : 0;

            optionWidth = (oWidth > optionWidth) ? oWidth : optionWidth;
            argumentWidth = (aWidth > argumentWidth) ? aWidth : argumentWidth;
        }

        // Print usage on each of the command line options.
        for (CommandLineOption optionInfo : optionMap.values())
        {
            String argString = ((optionInfo.argument != null) ? (optionInfo.argument) : "");
            String optionString = optionInfo.option;

            argString = rightPad(argString, " ", argumentWidth);
            optionString = rightPad(optionString, " ", optionWidth);

            result += "-" + optionString + " " + argString + " " + optionInfo.comment + "\n";
        }

        return result;
    }

Generates a usage string consisting of the name of each option and each options argument description and comment.

@return A usage string for all the options.

Generates a usage string consisting of the name of each option and each options argument description and comment .


public void addTrailingPairsToProperties(Properties properties)
    {
        if (trailingProperties != null)
        {
            for (Object propKey : trailingProperties.keySet())
            {
                String name = (String) propKey;
                String value = trailingProperties.getProperty(name);

                properties.setProperty(name, value);
            }
        }
    }

public void addTrailingPairsToProperties ( Properties properties ) { if ( trailingProperties != null ) { for ( Object propKey : trailingProperties . keySet ( ) ) { String name = ( String ) propKey ; String value = trailingProperties . getProperty ( name ) ; properties . setProperty ( name , value ) ; } } }

If a command line has been parsed, calling this method sets all of its free arguments that were name=value pairs
on the specified properties.

@param properties The property set to add the name=value pairs to.

If a command line has been parsed calling this method sets all of its free arguments that were name = value pairs on the specified properties .


public void addOptionsToProperties(Properties properties)
    {
        if (parsedProperties != null)
        {
            for (Object propKey : parsedProperties.keySet())
            {
                String name = (String) propKey;
                String value = parsedProperties.getProperty(name);

                // This filters out all trailing items.
                if (!name.matches("^[0-9]+$"))
                {
                    properties.setProperty(name, value);
                }
            }
        }
    }

public
void
addOptionsToProperties
(
Properties
properties
)
{
if
(
parsedProperties
!=
)
{
for
(
Object
propKey
:
parsedProperties
.
keySet
(
)
)
{
String
name
=
(
String
)
propKey
;
String
value
=
parsedProperties
.
getProperty
(
name
)
;
// This filters out all trailing items.
if
(
!
name
.
matches
(
"^[0-9]+$"
)
)
{
properties
.
setProperty
(
name
,
value
)
;
}
}
}
}

If a command line has been parsed, calling this method sets all of its options that were set to the specified
properties.

@param properties The property set to the options to.

If a command line has been parsed calling this method sets all of its options that were set to the specified properties .


protected void addOption(String option, String comment, String argument, boolean mandatory, String formatRegexp)
    {
        // Check if usage text has been set in which case this option is expecting arguments.
        boolean expectsArgs = (!((argument == null) || "".equals(argument)));

        // Add the option to the map of command line options.
        CommandLineOption opt = new CommandLineOption(option, expectsArgs, comment, argument, mandatory, formatRegexp);
        optionMap.put(option, opt);
    }

Adds the option to list of available command line options.

@param option       The option to add as an available command line option.
@param comment      A comment for the option.
@param argument     The text that appears after the option in the usage string.
@param mandatory    When true, indicates that this option is mandatory.
@param formatRegexp The format that the argument must take, defined as a regular expression.

Adds the option to list of available command line options .


private Properties takeFreeArgsAsProperties(Properties properties, int from)
    {
        Properties result = new Properties();

        for (int i = from; true; i++)
        {
            String nextFreeArg = properties.getProperty(Integer.toString(i));

            // Terminate the loop once all free arguments have been consumed.
            if (nextFreeArg == null)
            {
                break;
            }

            // Split it on the =, strip any whitespace and set it as a system property.
            String[] nameValuePair = nextFreeArg.split("=");

            if (nameValuePair.length == 2)
            {
                result.setProperty(nameValuePair[0], nameValuePair[1]);
            }
        }

        return result;
    }

Converts the free arguments into property declarations. After parsing the command line the free arguments are
numbered from 1, such that the parsed properties contain values for the keys "1", "2", ... This method converts
any free arguments declared using the 'name=value' syntax into properties with key 'name', value 'value'.

For example the comand line:

... debug=true

After parsing has properties:

[[1, debug=true]]

After applying this method the properties are:

[[1, debug=true], [debug, true]]

@param  properties The parsed command line properties.
@param  from       The free argument index to convert to properties from.

@return The parsed command line properties, with free argument name value pairs too.

Converts the free arguments into property declarations . After parsing the command line the free arguments are numbered from 1 such that the parsed properties contain values for the keys 1 2 ... This method converts any free arguments declared using the name = value syntax into properties with key name value value .


private void checkArgumentFormat(CommandLineOption optionInfo, CharSequence matchedArg)
    {
        // Check if this option enforces a format for its argument.
        if (optionInfo.argumentFormatRegexp != null)
        {
            Pattern pattern = Pattern.compile(optionInfo.argumentFormatRegexp);
            Matcher argumentMatcher = pattern.matcher(matchedArg);

            // Check if the argument does not meet its required format.
            if (!argumentMatcher.matches())
            {
                // Create an error for this badly formed argument.
                parsingErrors.add("The argument to option " + optionInfo.option +
                    " does not meet its required format.\n");
            }
        }
    }

Checks the format of an argument to an option against its specified regular expression format if one has been
set. Any errors are added to the list of parsing errors.

@param optionInfo The command line option information for the option which is havings its argument checked.
@param matchedArg The string argument to the option.

Checks the format of an argument to an option against its specified regular expression format if one has been set . Any errors are added to the list of parsing errors .


public static <T, U> String compareIterators(Iterator<U> iterator, Iterator<T> expectedIterator,
        Function<U, T> mapping)
    {
        String errorMessage = "";

        while (iterator.hasNext())
        {
            U next = iterator.next();
            T nextMapped = mapping.apply(next);
            T nextExpected = expectedIterator.next();

            if (!nextMapped.equals(nextExpected))
            {
                errorMessage += "Expecting " + nextExpected + " but got " + nextMapped;
            }
        }

        return errorMessage;
    }

public
static
<
T
,
U
>
String
compareIterators
(
Iterator
<
U
>
iterator
,
Iterator
<
T
>
expectedIterator
,
Function
<
U
,
T
>
mapping
)
{
String
errorMessage
=
""
;
while
(
iterator
.
hasNext
(
)
)
{
U
next
=
iterator
.
next
(
)
;
T
nextMapped
=
mapping
.
apply
(
next
)
;
T
nextExpected
=
expectedIterator
.
next
(
)
;
if
(
!
nextMapped
.
equals
(
nextExpected
)
)
{
errorMessage
+=
"Expecting "
+
nextExpected
+
" but got "
+
nextMapped
;
}
}
return
errorMessage
;
}

Walks down two iterators, comparing them element by element, using the equals method.

@param  iterator         The first iterator to compare.
@param  expectedIterator The second iterator to compare.
@param  mapping          A mapping between the types of the iterators.
@param  <U>              The type of the left iterator.
@param  <T>              The type of the right iterator.

@return Any mismatches encountered in a string, or the empty string if none found.

Walks down two iterators comparing them element by element using the equals method .


public Enumeration listOptions() {
    Vector<Option>	result;
    String		desc;
    SelectedTag		tag;
    int			i;

    result = new Vector<Option>();
    desc  = "";
    for (i = 0; i < TAGS_STEMMERS.length; i++) {
      tag = new SelectedTag(TAGS_STEMMERS[i].getID(), TAGS_STEMMERS);
      desc  +=   "\t" + tag.getSelectedTag().getIDStr()
      	       + " = " + tag.getSelectedTag().getReadable()
      	       + "\n";
    }
    result.addElement(new Option(
	"\tThe type of stemmer algorithm to use:\n"
	+ desc
	+ "\t(default: " + new SelectedTag(STEMMER_ORENGO, TAGS_STEMMERS) + ")",
	"S", 1, "-S " + Tag.toOptionList(TAGS_STEMMERS)));

    result.addElement(new Option(
        "\tThe file with the named entities to ignore (optional).\n"
        + "\tFile format: simple text file with one entity per line.\n"
        + "\t(default: none)\n",
        "N", 1, "-N <file>"));

    result.addElement(new Option(
        "\tThe file with the stopwords (optional).\n"
        + "\tFile format: simple text file with one stopword per line.\n"
        + "\t(default: none)\n",
        "W", 1, "-W <file>"));

    result.addElement(new Option(
        "\tThe size of the cache. Disable with 0.\n"
        + "\t(default: 1000)\n",
        "C", 1, "-C <int>"));

    return result.elements();
  }

Returns an enumeration describing the available options.

@return an enumeration of all the available options.

Returns an enumeration describing the available options .