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

implementation:
Functor goalTerm = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; Term argument = goalTerm . getArgument ( 0 ) . getValue ( ) ; // Check that the argument is not a free variable .
return argument . isNumber ( ) && ( ( NumericType ) argument . getValue ( ) ) . isReal ( ) ;


signature:
public class Decision { /** * Performs the actual decision based on a property of the state . If the quick lookup table has been initialized
 * then the decision is taken straight from it . If not then the supplied reference to the decision tree at this
 * point is used to find the outcome by scanning over its children .
 * @ param state the { @ link com . thesett . aima . state . State } to decide on .
 * @ return a { @ link DecisionTree } to continue the decision process with . */
public DecisionTree decide ( State state ) { } }

implementation:
// Extract the value of the property being decided from state to be classified .
OrdinalAttribute attributeValue = ( OrdinalAttribute ) state . getProperty ( propertyName ) ; // Extract the child decision tree that matches the property value , using the attributes ordinal for a quick
// look up .
return decisions [ attributeValue . ordinal ( ) ] ;


signature:
public class Decision { /** * Initializes the lookup table for this decision node . The specified decision tree that corresponds to this node is
 * used to extract all the possible outcomes for this decision and these are stored in a lookup table so that future
 * decisions made with this tree will run faster .
 * @ param thisNode the decision tree that this decision node is the element from . */
public void initializeLookups ( DecisionTree thisNode ) { } }

implementation:
// Scan over all the decision trees children at this point inserting them into the lookup table depending
// on the ordinal of the attribute value that matches them .
for ( Iterator < Tree < DecisionTreeElement > > i = thisNode . getChildIterator ( ) ; i . hasNext ( ) ; ) { DecisionTree nextChildTree = ( DecisionTree ) i . next ( ) ; // Get the matching attribute value from the childs decision tree element .
OrdinalAttribute matchingValue = nextChildTree . getElement ( ) . getAttributeValue ( ) ; // Insert the matching sub - tree into the lookup table .
decisions [ matchingValue . ordinal ( ) ] = nextChildTree ; }


signature:
public class PrologUnifier { /** * Unifies two terms and produces a list of bound variables that form the unification , when it it possible .
 * @ param query The left term to unify .
 * @ param statement The right term to unify .
 * @ return A list of bound variables to form the unification , or < tt > null < / tt > when no unification is possible . */
public List < Variable > unify ( Term query , Term statement ) { } }

implementation:
/* log . fine ( " unify ( Term left = " + query + " , Term right = " + statement + " ) : called " ) ; */
// Find all free variables in the query .
Set < Variable > freeVars = TermUtils . findFreeNonAnonymousVariables ( query ) ; // Build up all the variable bindings in both sides of the unification in these bindings .
List < Variable > queryBindings = new LinkedList < Variable > ( ) ; List < Variable > statementBindings = new LinkedList < Variable > ( ) ; // Fund the most general unifier , if possible .
boolean unified = unifyInternal ( query , statement , queryBindings , statementBindings ) ; List < Variable > results = null ; // If a unification was found , only retain the free variables in the query in the results returned .
if ( unified ) { queryBindings . retainAll ( freeVars ) ; results = new ArrayList < Variable > ( queryBindings ) ; } return results ;


signature:
public class PrologUnifier { /** * Attempts to unify one term with another , against a background of already unified variables in both terms . In the
 * case where two terms are being unified from scratch the variable assignments will be empty .
 * @ param left The left hand term to unify with .
 * @ param right The right hand term to unify against .
 * @ param leftTrail The trail of bound variables in the left hand term .
 * @ param rightTrail The trail of bound variables in the right hand term .
 * @ return < tt > true < / tt > if the terms were unified , < tt > false < / tt > otherwise . */
public boolean unifyInternal ( Term left , Term right , List < Variable > leftTrail , List < Variable > rightTrail ) { } }

implementation:
/* log . fine ( " public boolean unifyInternal ( Term left = " + left + " , Term right = " + right +
 " , List < Variable > trail = " + leftTrail + " ) : called " ) ; */
if ( left == right ) { /* log . fine ( " Terms are identical objects . " ) ; */
return true ; } if ( ! left . isVar ( ) && ! right . isVar ( ) && left . isConstant ( ) && right . isConstant ( ) && left . equals ( right ) ) { /* log . fine ( " Terms are equal atoms or literals . " ) ; */
return true ; } else if ( left . isVar ( ) ) { /* log . fine ( " Left is a variable . " ) ; */
return unifyVar ( ( Variable ) left , right , leftTrail , rightTrail ) ; } else if ( right . isVar ( ) ) { /* log . fine ( " Right is a variable . " ) ; */
return unifyVar ( ( Variable ) right , left , rightTrail , leftTrail ) ; } else if ( left . isFunctor ( ) && right . isFunctor ( ) ) { /* log . fine ( " Terms are functors , at least one of which is not an atom . " ) ; */
Functor leftFunctor = ( Functor ) left ; Functor rightFunctor = ( Functor ) right ; // Check if the functors may be not be equal ( that is , they do not have the same name and arity ) , in
// which case they cannot possibly be unified .
if ( ! left . equals ( right ) ) { return false ; } /* log . fine ( " Terms are functors with same name and arity , both are compound . " ) ; */
// Pairwise unify all of the arguments of the functor .
int arity = leftFunctor . getArity ( ) ; for ( int i = 0 ; i < arity ; i ++ ) { Term leftArgument = leftFunctor . getArgument ( i ) ; Term rightArgument = rightFunctor . getArgument ( i ) ; boolean result = unifyInternal ( leftArgument , rightArgument , leftTrail , rightTrail ) ; if ( ! result ) { /* log . fine ( " Non unifying arguments in functors encountered , left = " + leftArgument + " , right = " +
 rightArgument ) ; */
return false ; } } return true ; } else { return false ; }


signature:
public class PrologUnifier { /** * Unifies a variable with a term . If the variable is bound , then the bound value is unified with the term . If the
 * term is a bound variable , and the variable is free , then the vairable is unified with the bound value of the
 * term . Otherwise , the variable is free and is bound to the value of the term .
 * @ param leftVar The variable to unify .
 * @ param rightTerm The term to unify against .
 * @ param leftTrail The built up trail of substitutions in the left hand side .
 * @ param rightTrail The built up trail of substitutions in the right hand side .
 * @ return < tt > true < / tt > if the variable unifies with the term , < tt > false < / tt > otherwise . */
protected boolean unifyVar ( Variable leftVar , Term rightTerm , List < Variable > leftTrail , List < Variable > rightTrail ) { } }

implementation:
/* log . fine ( " protected boolean unifyVar ( Variable var = " + leftVar + " , Term term = " + rightTerm +
 " , List < Variable > trail = " + leftTrail + " ) : called " ) ; */
// Check if the variable is bound ( in the trail , but no need to explicitly check the trail as the binding is
// already held against the variable ) .
if ( leftVar . isBound ( ) ) { /* log . fine ( " Variable is bound . " ) ; */
return unifyInternal ( leftVar . getValue ( ) , rightTerm , leftTrail , rightTrail ) ; } else if ( rightTerm . isVar ( ) && ( ( Variable ) rightTerm ) . isBound ( ) ) { // The variable is free , but the term itself is a bound variable , in which case unify againt the value
// of the term .
/* log . fine ( " Term is a bound variable . " ) ; */
return unifyInternal ( leftVar , rightTerm . getValue ( ) , leftTrail , rightTrail ) ; } else { // Otherwise , unify by binding the variable to the value of the term .
/* log . fine ( " Variable is free , substituting in the term for it . " ) ; */
leftVar . setSubstitution ( rightTerm ) ; leftTrail . add ( leftVar . getStorageCell ( leftVar ) ) ; // leftTrail . add ( leftVar ) ;
return true ; } // Occurs can go above if desired .
/* else if ( var occurs anywhere in x )
 return false ; */


signature:
public class InstructionCompiler { /** * { @ inheritDoc } */
public void endScope ( ) throws SourceCodeException { } }

implementation:
// Loop over all predicates in the current scope , found in the symbol table , and consume and compile them .
for ( SymbolKey predicateKey = predicatesInScope . poll ( ) ; predicateKey != null ; predicateKey = predicatesInScope . poll ( ) ) { List < Clause > clauseList = ( List < Clause > ) scopeTable . get ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES ) ; // Used to keep track of where within the predicate the current clause is .
int size = clauseList . size ( ) ; int current = 0 ; boolean multipleClauses = size > 1 ; // Used to build up the compiled predicate in .
WAMCompiledPredicate result = null ; for ( Iterator < Clause > iterator = clauseList . iterator ( ) ; iterator . hasNext ( ) ; iterator . remove ( ) ) { Clause clause = iterator . next ( ) ; if ( result == null ) { result = new WAMCompiledPredicate ( clause . getHead ( ) . getName ( ) ) ; } // Compile the single clause , adding it to the parent compiled predicate .
compileClause ( clause , result , current == 0 , current >= ( size - 1 ) , multipleClauses , current ) ; current ++ ; } // Run the optimizer on the output .
result = optimizer . apply ( result ) ; displayCompiledPredicate ( result ) ; observer . onCompilation ( result ) ; // Move up the low water mark on the predicates table .
symbolTable . setLowMark ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES ) ; } // Clear up the symbol table , and bump the compilation scope up by one .
symbolTable . clearUpToLowMark ( SymbolTableKeys . SYMKEY_PREDICATES ) ; scopeTable = null ; scope ++ ;


signature:
public class InstructionCompiler { /** * { @ inheritDoc }
 * < p / > Compiles a sentence into a binary form , that provides a Java interface into the compiled structure .
 * < p / > The clausal sentence may be a query , or a program statement . If it is a query , it is compiled immediately . If
 * it is a clause , it is retained against the predicate which it forms part of , and compiled on the
 * { @ link # endScope ( ) } method is invoked . */
public void compile ( Sentence < Clause > sentence ) throws SourceCodeException { } }

implementation:
/* log . fine ( " public WAMCompiledClause compile ( Sentence < Term > sentence = " + sentence + " ) : called " ) ; */
// Extract the clause to compile from the parsed sentence .
Clause clause = sentence . getT ( ) ; // Classify the sentence to compile by the different sentence types in the language .
if ( clause . isQuery ( ) ) { compileQuery ( clause ) ; } else { // Initialise a nested symbol table for the current compilation scope , if it has not already been .
if ( scopeTable == null ) { scopeTable = symbolTable . enterScope ( scope ) ; } // Check in the symbol table , if a compiled predicate with name matching the program clause exists , and if
// not create it .
SymbolKey predicateKey = scopeTable . getSymbolKey ( clause . getHead ( ) . getName ( ) ) ; Collection < Clause > clauseList = ( List < Clause > ) scopeTable . get ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES ) ; if ( clauseList == null ) { clauseList = new LinkedList < Clause > ( ) ; scopeTable . put ( predicateKey , SymbolTableKeys . SYMKEY_PREDICATES , clauseList ) ; predicatesInScope . offer ( predicateKey ) ; } // Add the clause to compile to its parent predicate for compilation at the end of the current scope .
clauseList . add ( clause ) ; }


signature:
public class InstructionCompiler { /** * Compiles a program clause , and adds its instructions to a compiled predicate .
 * @ param clause The source clause to compile .
 * @ param compiledPredicate The predicate to add instructions to .
 * @ param isFirst < tt > true < / tt > iff the clause is the first in the predicate .
 * @ param isLast < tt > true < / tt > iff the clause is the last in the predicate .
 * @ param multipleClauses < tt > true < / tt > iff the predicate contains > 1 clause .
 * @ param clauseNumber The position of the clause within the predicate .
 * @ throws SourceCodeException If there is an error in the source code preventing its compilation . */
private void compileClause ( Clause clause , WAMCompiledPredicate compiledPredicate , boolean isFirst , boolean isLast , boolean multipleClauses , int clauseNumber ) throws SourceCodeException { } }

implementation:
// Used to build up the compiled clause in .
WAMCompiledClause result = new WAMCompiledClause ( compiledPredicate ) ; // Check if the clause to compile is a fact ( no body ) .
boolean isFact = clause . getBody ( ) == null ; // Check if the clause to compile is a chain rule , ( one called body ) .
boolean isChainRule = ( clause . getBody ( ) != null ) && ( clause . getBody ( ) . length == 1 ) ; // Used to keep track of registers as they are seen during compilation . The first time a variable is seen ,
// a variable is written onto the heap , subsequent times its value . The first time a functor is seen ,
// its structure is written onto the heap , subsequent times it is compared with .
seenRegisters = new TreeSet < Integer > ( ) ; // This is used to keep track of the next temporary register available to allocate .
lastAllocatedTempReg = findMaxArgumentsInClause ( clause ) ; // This is used to keep track of the number of permanent variables .
numPermanentVars = 0 ; // This is used to keep track of the allocation slot for the cut level variable , when needed . - 1 means it is
// not needed , so it is initialized to this .
cutLevelVarSlot = - 1 ; // These are used to generate pre and post instructions for the clause , for example , for the creation and
// clean - up of stack frames .
SizeableList < WAMInstruction > preFixInstructions = new SizeableLinkedList < WAMInstruction > ( ) ; SizeableList < WAMInstruction > postFixInstructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Find all the free non - anonymous variables in the clause .
Set < Variable > freeVars = TermUtils . findFreeNonAnonymousVariables ( clause ) ; Collection < Integer > freeVarNames = new TreeSet < Integer > ( ) ; for ( Variable var : freeVars ) { freeVarNames . add ( var . getName ( ) ) ; } // Allocate permanent variables for a program clause . Program clauses only use permanent variables when really
// needed to preserve variables across calls .
allocatePermanentProgramRegisters ( clause ) ; // Gather information about the counts and positions of occurrence of variables and constants within the clause .
gatherPositionAndOccurrenceInfo ( clause ) ; // Labels the entry point to each choice point .
FunctorName fn = interner . getFunctorFunctorName ( clause . getHead ( ) ) ; WAMLabel entryLabel = new WAMLabel ( fn , clauseNumber ) ; // Label for the entry point to the next choice point , to backtrack to .
WAMLabel retryLabel = new WAMLabel ( fn , clauseNumber + 1 ) ; // Create choice point instructions for the clause , depending on its position within the containing predicate .
// The choice point instructions are only created when a predicate is built from multiple clauses , as otherwise
// there are no choices to be made .
if ( isFirst && ! isLast && multipleClauses ) { // try me else .
preFixInstructions . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TryMeElse , retryLabel ) ) ; } else if ( ! isFirst && ! isLast && multipleClauses ) { // retry me else .
preFixInstructions . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . RetryMeElse , retryLabel ) ) ; } else if ( isLast && multipleClauses ) { // trust me .
preFixInstructions . add ( new WAMInstruction ( entryLabel , WAMInstruction . WAMInstructionSet . TrustMe ) ) ; } // Generate the prefix code for the clause .
// Rules may chain multiple , so require stack frames to preserve registers across calls .
// Facts are always leafs so can use the global continuation point register to return from calls .
// Chain rules only make one call , so also do not need a stack frame .
if ( ! ( isFact || isChainRule ) ) { // Allocate a stack frame at the start of the clause .
/* log . fine ( " ALLOCATE " + numPermanentVars ) ; */
preFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Allocate ) ) ; } // Deep cuts require the current choice point to be kept in a permanent variable , so that it can be recovered
// once deeper choice points or environments have been reached .
if ( cutLevelVarSlot >= 0 ) { /* log . fine ( " GET _ LEVEL " + cutLevelVarSlot ) ; */
preFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetLevel , ( byte ) cutLevelVarSlot ) ) ; } result . addInstructions ( preFixInstructions ) ; // Compile the clause head .
Functor expression = clause . getHead ( ) ; SizeableLinkedList < WAMInstruction > instructions = compileHead ( expression ) ; result . addInstructions ( expression , instructions ) ; // Compile all of the conjunctive parts of the body of the clause , if there are any .
if ( ! isFact ) { Functor [ ] expressions = clause . getBody ( ) ; for ( int i = 0 ; i < expressions . length ; i ++ ) { expression = expressions [ i ] ; boolean isLastBody = i == ( expressions . length - 1 ) ; boolean isFirstBody = i == 0 ; Integer permVarsRemaining = ( Integer ) symbolTable . get ( expression . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_PERM_VARS_REMAINING ) ; // Select a non - default built - in implementation to compile the functor with , if it is a built - in .
BuiltIn builtIn ; if ( expression instanceof BuiltIn ) { builtIn = ( BuiltIn ) expression ; } else { builtIn = this ; } // The ' isFirstBody ' parameter is only set to true , when this is the first functor of a rule .
instructions = builtIn . compileBodyArguments ( expression , i == 0 , fn , i ) ; result . addInstructions ( expression , instructions ) ; // Call the body . The number of permanent variables remaining is specified for environment trimming .
instructions = builtIn . compileBodyCall ( expression , isFirstBody , isLastBody , isChainRule , permVarsRemaining ) ; result . addInstructions ( expression , instructions ) ; } } // Generate the postfix code for the clause . Rules may chain , so require stack frames .
// Facts are always leafs so can use the global continuation point register to return from calls .
if ( isFact ) { /* log . fine ( " PROCEED " ) ; */
postFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Proceed ) ) ; } result . addInstructions ( postFixInstructions ) ;


signature:
public class InstructionCompiler { /** * Compiles a clause as a query . The clause should have no head , only a body .
 * @ param clause The clause to compile as a query .
 * @ throws SourceCodeException If there is an error in the source code preventing its compilation . */
private void compileQuery ( Clause clause ) throws SourceCodeException { } }

implementation:
// Used to build up the compiled result in .
WAMCompiledQuery result ; // A mapping from top stack frame slots to interned variable names is built up in this .
// This is used to track the stack positions that variables in a query are assigned to .
Map < Byte , Integer > varNames = new TreeMap < Byte , Integer > ( ) ; // Used to keep track of registers as they are seen during compilation . The first time a variable is seen ,
// a variable is written onto the heap , subsequent times its value . The first time a functor is seen ,
// its structure is written onto the heap , subsequent times it is compared with .
seenRegisters = new TreeSet < Integer > ( ) ; // This is used to keep track of the next temporary register available to allocate .
lastAllocatedTempReg = findMaxArgumentsInClause ( clause ) ; // This is used to keep track of the number of permanent variables .
numPermanentVars = 0 ; // This is used to keep track of the allocation slot for the cut level variable , when needed . - 1 means it is
// not needed , so it is initialized to this .
cutLevelVarSlot = - 1 ; // These are used to generate pre and post instructions for the clause , for example , for the creation and
// clean - up of stack frames .
SizeableList < WAMInstruction > preFixInstructions = new SizeableLinkedList < WAMInstruction > ( ) ; SizeableList < WAMInstruction > postFixInstructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Find all the free non - anonymous variables in the clause .
Set < Variable > freeVars = TermUtils . findFreeNonAnonymousVariables ( clause ) ; Set < Integer > freeVarNames = new TreeSet < Integer > ( ) ; for ( Variable var : freeVars ) { freeVarNames . add ( var . getName ( ) ) ; } // Allocate permanent variables for a query . In queries all variables are permanent so that they are preserved
// on the stack upon completion of the query .
allocatePermanentQueryRegisters ( clause , varNames ) ; // Gather information about the counts and positions of occurrence of variables and constants within the clause .
gatherPositionAndOccurrenceInfo ( clause ) ; result = new WAMCompiledQuery ( varNames , freeVarNames ) ; // Generate the prefix code for the clause . Queries require a stack frames to hold their environment .
/* log . fine ( " ALLOCATE " + numPermanentVars ) ; */
preFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . AllocateN , REG_ADDR , ( byte ) ( numPermanentVars & 0xff ) ) ) ; // Deep cuts require the current choice point to be kept in a permanent variable , so that it can be recovered
// once deeper choice points or environments have been reached .
if ( cutLevelVarSlot >= 0 ) { /* log . fine ( " GET _ LEVEL " + cutLevelVarSlot ) ; */
preFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetLevel , STACK_ADDR , ( byte ) cutLevelVarSlot ) ) ; } result . addInstructions ( preFixInstructions ) ; // Compile all of the conjunctive parts of the body of the clause , if there are any .
Functor [ ] expressions = clause . getBody ( ) ; // The current query does not have a name , so invent one for it .
FunctorName fn = new FunctorName ( "tq" , 0 ) ; for ( int i = 0 ; i < expressions . length ; i ++ ) { Functor expression = expressions [ i ] ; boolean isFirstBody = i == 0 ; // Select a non - default built - in implementation to compile the functor with , if it is a built - in .
BuiltIn builtIn ; if ( expression instanceof BuiltIn ) { builtIn = ( BuiltIn ) expression ; } else { builtIn = this ; } // The ' isFirstBody ' parameter is only set to true , when this is the first functor of a rule , which it
// never is for a query .
SizeableLinkedList < WAMInstruction > instructions = builtIn . compileBodyArguments ( expression , false , fn , i ) ; result . addInstructions ( expression , instructions ) ; // Queries are never chain rules , and as all permanent variables are preserved , bodies are never called
// as last calls .
instructions = builtIn . compileBodyCall ( expression , isFirstBody , false , false , numPermanentVars ) ; result . addInstructions ( expression , instructions ) ; } // Generate the postfix code for the clause .
/* log . fine ( " DEALLOCATE " ) ; */
postFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Suspend ) ) ; postFixInstructions . add ( new WAMInstruction ( WAMInstruction . WAMInstructionSet . Deallocate ) ) ; result . addInstructions ( postFixInstructions ) ; // Run the optimizer on the output .
result = optimizer . apply ( result ) ; displayCompiledQuery ( result ) ; observer . onQueryCompilation ( result ) ;


signature:
public class InstructionCompiler { /** * Examines all top - level functors within a clause , including any head and body , and determines which functor has
 * the highest number of arguments .
 * @ param clause The clause to determine the highest number of arguments within .
 * @ return The highest number of arguments within any top - level functor in the clause . */
private int findMaxArgumentsInClause ( Clause clause ) { } }

implementation: int result = 0 ; Functor head = clause . getHead ( ) ; if ( head != null ) { result = head . getArity ( ) ; } Functor [ ] body = clause . getBody ( ) ; if ( body != null ) { for ( int i = 0 ; i < body . length ; i ++ ) { int arity = body [ i ] . getArity ( ) ; result = ( arity > result ) ? arity : result ; } } return result ;


signature:
public class InstructionCompiler { /** * Compiles the head of a clause into an instruction listing in WAM .
 * @ param expression The clause head to compile .
 * @ return A listing of the instructions for the clause head in the WAM instruction set . */
private SizeableLinkedList < WAMInstruction > compileHead ( Functor expression ) { } }

implementation:
// Used to build up the results in .
SizeableLinkedList < WAMInstruction > instructions = new SizeableLinkedList < WAMInstruction > ( ) ; // Allocate argument registers on the body , to all functors as outermost arguments .
// Allocate temporary registers on the body , to all terms not already allocated .
allocateArgumentRegisters ( expression ) ; allocateTemporaryRegisters ( expression ) ; // Program instructions are generated in the same order as the registers are assigned , the postfix
// ordering used for queries is not needed .
SearchMethod outInSearch = new BreadthFirstSearch < Term , Term > ( ) ; outInSearch . reset ( ) ; outInSearch . addStartState ( expression ) ; Iterator < Term > treeWalker = Searches . allSolutions ( outInSearch ) ; // Skip the outermost functor .
treeWalker . next ( ) ; // Allocate argument registers on the body , to all functors as outermost arguments .
// Allocate temporary registers on the body , to all terms not already allocated .
// Keep track of processing of the arguments to the outermost functor as get _ val and get _ var instructions
// need to be output for variables encountered in the arguments only .
int numOutermostArgs = expression . getArity ( ) ; for ( int j = 0 ; treeWalker . hasNext ( ) ; j ++ ) { Term nextTerm = treeWalker . next ( ) ; /* log . fine ( " nextTerm = " + nextTerm ) ; */
// For each functor encountered : get _ struc .
if ( nextTerm . isFunctor ( ) ) { Functor nextFunctor = ( Functor ) nextTerm ; int allocation = ( Integer ) symbolTable . get ( nextFunctor . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; byte addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; byte address = ( byte ) ( allocation & 0xff ) ; // Ouput a get _ struc instruction , except on the outermost functor .
/* log . fine ( " GET _ STRUC " + interner . getFunctorName ( nextFunctor ) + " / " + nextFunctor . getArity ( ) +
 ( ( addrMode = = REG _ ADDR ) ? " , X " : " , Y " ) + address ) ; */
WAMInstruction instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetStruc , addrMode , address , interner . getFunctorFunctorName ( nextFunctor ) , nextFunctor ) ; instructions . add ( instruction ) ; // For each argument of the functor .
int numArgs = nextFunctor . getArity ( ) ; for ( int i = 0 ; i < numArgs ; i ++ ) { Term nextArg = nextFunctor . getArgument ( i ) ; allocation = ( Integer ) symbolTable . get ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; address = ( byte ) ( allocation & 0xff ) ; /* log . fine ( " nextArg = " + nextArg ) ; */
// If it is register not seen before : unify _ var .
// If it is register seen before : unify _ val .
if ( ! seenRegisters . contains ( allocation ) ) { /* log . fine ( " UNIFY _ VAR " + ( ( addrMode = = REG _ ADDR ) ? " X " : " Y " ) + address ) ; */
seenRegisters . add ( allocation ) ; instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . UnifyVar , addrMode , address , nextArg ) ; // Record the way in which this variable was introduced into the clause .
symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Unify ) ; } else { // Check if the variable is ' local ' and use a local instruction on the first occurrence .
VarIntroduction introduction = ( VarIntroduction ) symbolTable . get ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO ) ; if ( isLocalVariable ( introduction , addrMode ) ) { /* log . fine ( " UNIFY _ LOCAL _ VAL " + ( ( addrMode = = REG _ ADDR ) ? " X " : " Y " ) +
 address ) ; */
instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . UnifyLocalVal , addrMode , address , nextArg ) ; symbolTable . put ( nextArg . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , null ) ; } else { /* log . fine ( " UNIFY _ VAL " + ( ( addrMode = = REG _ ADDR ) ? " X " : " Y " ) + address ) ; */
instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . UnifyVal , addrMode , address , nextArg ) ; } } instructions . add ( instruction ) ; } } else if ( j < numOutermostArgs ) { Term nextVar = ( Variable ) nextTerm ; int allocation = ( Integer ) symbolTable . get ( nextVar . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION ) ; byte addrMode = ( byte ) ( ( allocation & 0xff00 ) >> 8 ) ; byte address = ( byte ) ( allocation & 0xff ) ; WAMInstruction instruction ; // If it is register not seen before : get _ var .
// If it is register seen before : get _ val .
if ( ! seenRegisters . contains ( allocation ) ) { /* log . fine ( " GET _ VAR " + ( ( addrMode = = REG _ ADDR ) ? " X " : " Y " ) + address + " , A " + j ) ; */
seenRegisters . add ( allocation ) ; instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetVar , addrMode , address , ( byte ) ( j & 0xff ) ) ; // Record the way in which this variable was introduced into the clause .
symbolTable . put ( nextVar . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_VARIABLE_INTRO , VarIntroduction . Get ) ; } else { /* log . fine ( " GET _ VAL " + ( ( addrMode = = REG _ ADDR ) ? " X " : " Y " ) + address + " , A " + j ) ; */
instruction = new WAMInstruction ( WAMInstruction . WAMInstructionSet . GetVal , addrMode , address , ( byte ) ( j & 0xff ) ) ; } instructions . add ( instruction ) ; } } return instructions ;


signature:
public class InstructionCompiler { /** * Allocates stack slots where needed to the variables in a program clause . The algorithm here is fairly complex .
 * < p / > A clause head and first body functor are taken together as the first unit , subsequent clause body functors
 * are taken as subsequent units . A variable appearing in more than one unit is said to be permanent , and must be
 * stored on the stack , rather than a register , otherwise the register that it occupies may be overwritten by calls
 * to subsequent units . These variables are called permanent , which really means that they are local variables on
 * the call stack .
 * < p / > In addition to working out which variables are permanent , the variables are also ordered by reverse position
 * of last body of occurrence , and assigned to allocation slots in this order . The number of permanent variables
 * remaining at each body call is also calculated and recorded against the body functor in the symbol table using
 * column { @ link SymbolTableKeys # SYMKEY _ PERM _ VARS _ REMAINING } . This allocation ordering of the variables and the
 * count of the number remaining are used to implement environment trimming .
 * @ param clause The clause to allocate registers for . */
private void allocatePermanentProgramRegisters ( Clause clause ) { } }

implementation:
// A bag to hold variable occurrence counts in .
Map < Variable , Integer > variableCountBag = new HashMap < Variable , Integer > ( ) ; // A mapping from variables to the body number in which they appear last .
Map < Variable , Integer > lastBodyMap = new HashMap < Variable , Integer > ( ) ; // Holds the variable that are in the head and first clause body argument .
Collection < Variable > firstGroupVariables = new HashSet < Variable > ( ) ; // Get the occurrence counts of variables in all clauses after the initial head and first body grouping .
// In the same pass , pick out which body variables last occur in .
if ( ( clause . getBody ( ) != null ) ) { for ( int i = clause . getBody ( ) . length - 1 ; i >= 1 ; i -- ) { Set < Variable > groupVariables = TermUtils . findFreeVariables ( clause . getBody ( ) [ i ] ) ; // Add all their counts to the bag and update their last occurrence positions .
for ( Variable variable : groupVariables ) { Integer count = variableCountBag . get ( variable ) ; variableCountBag . put ( variable , ( count == null ) ? 1 : ( count + 1 ) ) ; if ( ! lastBodyMap . containsKey ( variable ) ) { lastBodyMap . put ( variable , i ) ; } // If the cut level variable is seen , automatically add it to the first group variables ,
// so that it will be counted as a permanent variable , and assigned a stack slot . This
// will only occur for deep cuts , that is where the cut comes after the first group .
if ( variable instanceof Cut . CutLevelVariable ) { firstGroupVariables . add ( variable ) ; } } } } // Get the set of variables in the head and first clause body argument .
if ( clause . getHead ( ) != null ) { Set < Variable > headVariables = TermUtils . findFreeVariables ( clause . getHead ( ) ) ; firstGroupVariables . addAll ( headVariables ) ; } if ( ( clause . getBody ( ) != null ) && ( clause . getBody ( ) . length > 0 ) ) { Set < Variable > firstArgVariables = TermUtils . findFreeVariables ( clause . getBody ( ) [ 0 ] ) ; firstGroupVariables . addAll ( firstArgVariables ) ; } // Add their counts to the bag , and set their last positions of occurrence as required .
for ( Variable variable : firstGroupVariables ) { Integer count = variableCountBag . get ( variable ) ; variableCountBag . put ( variable , ( count == null ) ? 1 : ( count + 1 ) ) ; if ( ! lastBodyMap . containsKey ( variable ) ) { lastBodyMap . put ( variable , 0 ) ; } } // Sort the variables by reverse position of last occurrence .
List < Map . Entry < Variable , Integer > > lastBodyList = new ArrayList < Map . Entry < Variable , Integer > > ( lastBodyMap . entrySet ( ) ) ; Collections . sort ( lastBodyList , new Comparator < Map . Entry < Variable , Integer > > ( ) { public int compare ( Map . Entry < Variable , Integer > o1 , Map . Entry < Variable , Integer > o2 ) { return o2 . getValue ( ) . compareTo ( o1 . getValue ( ) ) ; } } ) ; // Holds counts of permanent variable last appearances against the body in which they last occur .
int [ ] permVarsRemainingCount = new int [ ( clause . getBody ( ) != null ) ? clause . getBody ( ) . length : 0 ] ; // Search the count bag for all variable occurrences greater than one , and assign them to stack slots .
// The variables are examined by reverse position of last occurrence , to ensure that later variables
// are assigned to lower permanent allocation slots for environment trimming purposes .
for ( Map . Entry < Variable , Integer > entry : lastBodyList ) { Variable variable = entry . getKey ( ) ; Integer count = variableCountBag . get ( variable ) ; int body = entry . getValue ( ) ; if ( ( count != null ) && ( count > 1 ) ) { /* log . fine ( " Variable " + variable + " is permanent , count = " + count ) ; */
int allocation = ( numPermanentVars ++ & ( 0xff ) ) | ( WAMInstruction . STACK_ADDR << 8 ) ; symbolTable . put ( variable . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_ALLOCATION , allocation ) ; // Check if the variable is the cut level variable , and cache its stack slot in ' cutLevelVarSlot ' , so that
// the clause compiler knows which variable to use for the get _ level instruction .
if ( variable instanceof Cut . CutLevelVariable ) { // cutLevelVarSlot = allocation ;
cutLevelVarSlot = numPermanentVars - 1 ; /* log . fine ( " cutLevelVarSlot = " + cutLevelVarSlot ) ; */
} permVarsRemainingCount [ body ] ++ ; } } // Roll up the permanent variable remaining counts from the counts of last position of occurrence and
// store the count of permanent variables remaining against the body .
int permVarsRemaining = 0 ; for ( int i = permVarsRemainingCount . length - 1 ; i >= 0 ; i -- ) { symbolTable . put ( clause . getBody ( ) [ i ] . getSymbolKey ( ) , SymbolTableKeys . SYMKEY_PERM_VARS_REMAINING , permVarsRemaining ) ; permVarsRemaining += permVarsRemainingCount [ i ] ; }


signature:
public class InstructionCompiler { /** * Allocates stack slots to all free variables in a query clause .
 * < p / > At the end of processing a query its variable bindings are usually printed . For this reason all free
 * variables in a query are marked as permanent variables on the call stack , to ensure that they are preserved .
 * @ param clause The clause to allocate registers for .
 * @ param varNames A map of permanent variables to variable names to record the allocations in . */
private void allocatePermanentQueryRegisters ( Term clause , Map < Byte , Integer > varNames ) { } }

implementation:
// Allocate local variable slots for all variables in a query .
QueryRegisterAllocatingVisitor allocatingVisitor = new QueryRegisterAllocatingVisitor ( symbolTable , varNames , null ) ; PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl ( ) ; positionalTraverser . setContextChangeVisitor ( allocatingVisitor ) ; TermWalker walker = new TermWalker ( new DepthFirstBacktrackingSearch < Term , Term > ( ) , positionalTraverser , allocatingVisitor ) ; walker . walk ( clause ) ;


signature:
public class InstructionCompiler { /** * Gather information about variable counts and positions of occurrence of constants and variable within a clause .
 * @ param clause The clause to check the variable occurrence and position of occurrence within . */
private void gatherPositionAndOccurrenceInfo ( Term clause ) { } }

implementation: PositionalTermTraverser positionalTraverser = new PositionalTermTraverserImpl ( ) ; PositionAndOccurrenceVisitor positionAndOccurrenceVisitor = new PositionAndOccurrenceVisitor ( interner , symbolTable , positionalTraverser ) ; positionalTraverser . setContextChangeVisitor ( positionAndOccurrenceVisitor ) ; TermWalker walker = new TermWalker ( new DepthFirstBacktrackingSearch < Term , Term > ( ) , positionalTraverser , positionAndOccurrenceVisitor ) ; walker . walk ( clause ) ;


signature:
public class InstructionCompiler { /** * Pretty prints a compiled predicate .
 * @ param predicate The compiled predicate to pretty print . */
private void displayCompiledPredicate ( Term predicate ) { } }

implementation:
// Pretty print the clause .
StringBuffer result = new StringBuffer ( ) ; PositionalTermVisitor displayVisitor = new WAMCompiledPredicatePrintingVisitor ( interner , symbolTable , result ) ; TermWalkers . positionalWalker ( displayVisitor ) . walk ( predicate ) ; /* log . fine ( result . toString ( ) ) ; */


signature:
public class InstructionCompiler { /** * Pretty prints a compiled query .
 * @ param query The compiled query to pretty print . */
private void displayCompiledQuery ( Term query ) { } }

implementation:
// Pretty print the clause .
StringBuffer result = new StringBuffer ( ) ; PositionalTermVisitor displayVisitor = new WAMCompiledQueryPrintingVisitor ( interner , symbolTable , result ) ; TermWalkers . positionalWalker ( displayVisitor ) . walk ( query ) ; /* log . fine ( result . toString ( ) ) ; */


signature:
public class ByteBufferUtils { /** * Writes the specified integer value as an ASCII string into the specified byte buffer . If the integer value is
 * shorted than the specified length , the number will be padded with leading zeros , so that it fills the required
 * length . If there is insufficient space in the buffer to write the value into , then the buffer size is increased
 * using the supplied byte buffer pool .
 * @ param buffer The byte buffer to write to .
 * @ param value The value to write .
 * @ param length The length to pad the number to with leading zeros .
 * @ return The byte buffer with the value written to it . This may be a different buffer to the one passed in if the
 * buffer had to be copied in order to increase its size . */
public static ByteBuffer putPaddedInt32AsString ( ByteBuffer buffer , int value , int length ) { } }

implementation:
// Ensure there is sufficient space in the buffer to hold the result .
int charsRequired = BitHackUtils . getCharacterCountInt32 ( value ) ; length = ( charsRequired < length ) ? length : charsRequired ; // Take an explicit index into the buffer to start writing to , as the numbers will be written backwards .
int index = buffer . position ( ) + length - 1 ; // Record the start position , to remember if a minus sign was written or not , so that it does not get
// overwritten by the zero padding .
int start = buffer . position ( ) ; // Advance the buffer position manually , as the characters will be written to specific indexes backwards .
buffer . position ( buffer . position ( ) + length ) ; // Take care of the minus sign for negative numbers .
if ( value < 0 ) { buffer . put ( MINUS_ASCII ) ; start ++ ; // Stop padding code overwriting minus sign .
} else { value = - value ; } // Write the digits least significant to most significant into the buffer . As the number was converted to be
// negative the remainders will be negative too .
do { int remainder = value % 10 ; value = value / 10 ; buffer . put ( index -- , ( ( byte ) ( ZERO_ASCII - remainder ) ) ) ; } while ( value != 0 ) ; // Write out the padding zeros .
while ( index >= start ) { buffer . put ( index -- , ZERO_ASCII ) ; } return buffer ;


signature:
public class ByteBufferUtils { /** * Returns the contents of a buffer as a string , converting ASCII characters in the buffer , into unicode string
 * characters .
 * @ param buffer The buffer .
 * @ param length The length of the string to get from the buffer .
 * @ return The buffer as a string . */
public static String asString ( ByteBuffer buffer , int length ) { } }

implementation: char [ ] chars = new char [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { chars [ i ] = ( char ) buffer . get ( i ) ; } return String . valueOf ( chars ) ;


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

implementation:
// Find the enumeration node for this enumeration value .
EnumerationNode node = null ; // Check if the attribute class has been finalized yet .
if ( attributeClass . finalized ) { // Fetch the string value from the attribute class array of finalized values .
node = attributeClass . lookupValue [ value ] ; } else { // The attribute class has not been finalized yet .
// Fetch the string value from the attribute class list of unfinalized values .
node = attributeClass . lookupValueList . get ( value ) ; } // Extract the id from it .
long existingId = node . id ; // Do nothing if the new id matches the existing one .
if ( id == existingId ) { return ; } // Check if the type is finalized .
if ( attributeClass . finalized ) { // Raise an illegal argument exception if the id is not known .
EnumeratedStringAttribute newValue = attributeClass . getAttributeFromId ( id ) ; // Otherwise , change the value of this attribute to that of the new id .
this . value = newValue . value ; } else { // The type is un - finalized .
// Check if another instance of the type already has the id and raise an exception if so .
EnumerationNode existingNode = attributeClass . idMap . get ( id ) ; if ( existingNode != null ) { throw new IllegalArgumentException ( "The id value, " + id + ", cannot be set because another instance of this type with that " + "id already exists." ) ; } // Assign it to this instance if the type is unfinalized . Also removing the old id mapping from the id
// map and replacing it with the new one .
node . id = id ; attributeClass . idMap . remove ( existingId ) ; attributeClass . idMap . put ( id , node ) ; }


signature:
public class EnumeratedStringAttribute { /** * Gets the string value of a string attribute .
 * @ return The underlying string value of this attribute . */
public String getStringValue ( ) { } }

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


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

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


signature:
public class TermParser { /** * Parses the next sentence from the current token source .
 * @ return The fully parsed syntax tree for the next sentence .
 * @ throws SourceCodeException If the source being parsed does not match the grammar . */
public Sentence < Term > parse ( ) throws SourceCodeException { } }

implementation: try { return new SentenceImpl < Term > ( parser . termSentence ( ) ) ; } catch ( SourceCodeException e ) { throw new IllegalStateException ( e ) ; }


signature:
public class LojixTermReader { /** * Reads a Lojix term and invoked appropriate methods on the content handler to describe its structure and contents
 * to it .
 * @ param term The Lojix term to read . */
private void read ( Term term ) { } }

implementation: if ( term . isNumber ( ) ) { NumericType numericType = ( NumericType ) term ; if ( numericType . isInteger ( ) ) { IntLiteral jplInteger = ( IntLiteral ) term ; getContentHandler ( ) . startIntegerTerm ( jplInteger . longValue ( ) ) ; } else if ( numericType . isFloat ( ) ) { FloatLiteral jplFloat = ( FloatLiteral ) term ; getContentHandler ( ) . startFloatTerm ( jplFloat . doubleValue ( ) ) ; } } else if ( term . isVar ( ) ) { Variable var = ( Variable ) term ; getContentHandler ( ) . startVariable ( interner . getVariableName ( var . getName ( ) ) ) ; } else if ( term . isAtom ( ) ) { Functor atom = ( Functor ) term ; getContentHandler ( ) . startAtom ( interner . getFunctorName ( atom . getName ( ) ) ) ; } else if ( term . isCompound ( ) ) { Functor functor = ( Functor ) term ; getContentHandler ( ) . startCompound ( ) ; getContentHandler ( ) . startAtom ( interner . getFunctorName ( functor . getName ( ) ) ) ; for ( com . thesett . aima . logic . fol . Term child : functor . getArguments ( ) ) { read ( child ) ; } getContentHandler ( ) . endCompound ( ) ; } else { throw new IllegalStateException ( "Unrecognized Lojix term: " + term ) ; }


signature: public class AbstractMicrodataDocument { public final MicrodataItem getItem ( String type ) { } }

implementation: List < MicrodataItem > items = getItems ( type ) ; if ( items . isEmpty ( ) ) { throw new MicrodataItemNotFoundException ( newUrl ( type ) ) ; } return items . get ( 0 ) ;


signature:
public class ReflectionUtils { /** * Checks if the named class exists and is loadable .
 * @ param className The class to check for .
 * @ return < tt > true < / tt > if the named class exists and is loadable . */
public static boolean classExistsAndIsLoadable ( String className ) { } }

implementation:
try { Class . forName ( className ) ; return true ; } catch ( ClassNotFoundException e ) { // Exception noted and ignored .
e = null ; return false ; }


signature:
public class ReflectionUtils { /** * Checks if the named class exists and is loadable and is a sub - type of the specified class .
 * @ param parent The class to check that the named class is a sub - type of .
 * @ param className The class to check for .
 * @ return < tt > true < / tt > if the named class exists and is loadable and is a sub - type of the specified class . */
public static boolean isSubTypeOf ( Class parent , String className ) { } }

implementation:
try { Class cls = Class . forName ( className ) ; return parent . isAssignableFrom ( cls ) ; } catch ( ClassNotFoundException e ) { // Exception noted and ignored .
e = null ; return false ; }


signature:
public class ReflectionUtils { /** * Checks that the named child class is the same type or a sub - type of the named parent class .
 * @ param parent The parent class name .
 * @ param child The child class name .
 * @ return < tt > true < / tt > if the named child class is the same type or a sub - type of the named parent class , < tt >
 * false < / tt > otherwise . */
public static boolean isSubTypeOf ( String parent , String child ) { } }

implementation:
try { return isSubTypeOf ( Class . forName ( parent ) , Class . forName ( child ) ) ; } catch ( ClassNotFoundException e ) { // Exception noted so can be ignored .
e = null ; return false ; }


signature:
public class ReflectionUtils { /** * Checks that the child class is the same type or a sub - type of the parent class .
 * @ param parentClass The parent class .
 * @ param childClass The child class .
 * @ return < tt > true < / tt > if the child class is the same type or a sub - type of the parent class , < tt > false < / tt >
 * otherwise . */
public static boolean isSubTypeOf ( Class parentClass , Class childClass ) { } }

implementation:
try { // Check that the child class can be cast as a sub - type of the parent .
childClass . asSubclass ( parentClass ) ; return true ; } catch ( ClassCastException e ) { // Exception noted so can be ignored .
e = null ; return false ; }


signature:
public class ReflectionUtils { /** * Gets the Class object for a named class .
 * @ param className The class to get the Class object for .
 * @ return The Class object for the named class . */
public static Class < ? > forName ( String className ) { } }

implementation: try { return Class . forName ( className ) ; } catch ( ClassNotFoundException e ) { throw new ReflectionUtilsException ( "ClassNotFoundException whilst finding class: " + className + "." , e ) ; }


signature:
public class ReflectionUtils { /** * Creates an instance of a Class , instantiated through its no - args constructor .
 * @ param cls The Class to instantiate .
 * @ param < T > The Class type .
 * @ return An instance of the class . */
public static < T > T newInstance ( Class < T > cls ) { } }

implementation: try { return cls . newInstance ( ) ; } catch ( InstantiationException e ) { throw new ReflectionUtilsException ( "InstantiationException whilst instantiating class." , e ) ; } catch ( IllegalAccessException e ) { throw new ReflectionUtilsException ( "IllegalAccessException whilst instantiating class." , e ) ; }


signature:
public class ReflectionUtils { /** * Calls a constuctor with the specified arguments .
 * @ param constructor The constructor .
 * @ param args The arguments .
 * @ param < T > The Class type .
 * @ return An instance of the class that the constructor is for . */
public static < T > T newInstance ( Constructor < T > constructor , Object [ ] args ) { } }

implementation: try { return constructor . newInstance ( args ) ; } catch ( InstantiationException e ) { throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( e ) ; }


signature:
public class ReflectionUtils { /** * Calls a named method on an object with a specified set of parameters , any Java access modifier are overridden .
 * @ param o The object to call .
 * @ param method The method name to call .
 * @ param params The parameters to pass .
 * @ param paramClasses The argument types .
 * @ return The return value from the method call . */
public static Object callMethodOverridingIllegalAccess ( Object o , String method , Object [ ] params , Class [ ] paramClasses ) { } }

implementation:
// Get the objects class .
Class cls = o . getClass ( ) ; // Get the classes of the parameters .
/* Class [ ] paramClasses = new Class [ params . length ] ;
 for ( int i = 0 ; i < params . length ; i + + )
 paramClasses [ i ] = params [ i ] . getClass ( ) ; */
try { // Try to find the matching method on the class .
Method m = cls . getDeclaredMethod ( method , paramClasses ) ; // Make it accessible .
m . setAccessible ( true ) ; // Invoke it with the parameters .
return m . invoke ( o , params ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( e ) ; }


signature:
public class ReflectionUtils { /** * Calls a named method on an object with a specified set of parameters .
 * @ param o The object to call .
 * @ param method The method name to call .
 * @ param params The parameters to pass .
 * @ return The return value from the method call . */
public static Object callMethod ( Object o , String method , Object [ ] params ) { } }

implementation:
// Get the objects class .
Class cls = o . getClass ( ) ; // Get the classes of the parameters .
Class [ ] paramClasses = new Class [ params . length ] ; for ( int i = 0 ; i < params . length ; i ++ ) { paramClasses [ i ] = params [ i ] . getClass ( ) ; } try { // Try to find the matching method on the class .
Method m = cls . getMethod ( method , paramClasses ) ; // Invoke it with the parameters .
return m . invoke ( o , params ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( e ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( e ) ; }


signature:
public class ReflectionUtils { /** * Calls a named static method on a class with a specified set of parameters .
 * @ param method The method name to call .
 * @ param params The parameters to pass .
 * @ return The return value from the method call . */
public static Object callStaticMethod ( Method method , Object [ ] params ) { } }

implementation: try { return method . invoke ( null , params ) ; } catch ( IllegalAccessException e ) { throw new IllegalStateException ( e ) ; } catch ( InvocationTargetException e ) { throw new IllegalStateException ( e ) ; }


signature:
public class ReflectionUtils { /** * Gets the constructor of a class that takes the specified set of arguments if any matches . If no matching
 * constructor is found then a runtime exception is raised .
 * @ param cls The class to get a constructor from .
 * @ param args The arguments to match .
 * @ param < T > The class type .
 * @ return The constructor . */
public static < T > Constructor < T > getConstructor ( Class < T > cls , Class [ ] args ) { } }

implementation: try { return cls . getConstructor ( args ) ; } catch ( NoSuchMethodException e ) { throw new IllegalStateException ( e ) ; }


signature:
public class ReflectionUtils { /** * Finds the argument types of all setter methods on a bean for a given property name . For a method to be a setter
 * method it must have a void return type , be public and accept only a single argument . Its name must be ' set '
 * followed by the property name .
 * @ param obClass The class to find all setter methods matching a given property for .
 * @ param propertyName The property name to find all matching setter methods for .
 * @ return An array of the types ( as classes ) of all the possible types that the setter method can be called with . */
public static Set < Class > findMatchingSetters ( Class obClass , String propertyName ) { } }

implementation:
/* log . fine ( " private Set < Class > findMatchingSetters ( Object ob , String propertyName ) : called " ) ; */
Set < Class > types = new HashSet < Class > ( ) ; // Convert the first letter of the property name to upper case to match against the upper case version of
// it that will be in the setter method name . For example the property test will have a setter method called
// setTest .
String upperPropertyName = Character . toUpperCase ( propertyName . charAt ( 0 ) ) + propertyName . substring ( 1 ) ; // Scan through all the objects methods .
Method [ ] methods = obClass . getMethods ( ) ; for ( Method nextMethod : methods ) { // Get the next method .
/* log . fine ( " nextMethod = " + nextMethod . getName ( ) ) ; */
// Check if a method has the correct name , accessibility and the correct number of arguments to be a setter
// method for the property .
String methodName = nextMethod . getName ( ) ; if ( methodName . equals ( "set" + upperPropertyName ) && Modifier . isPublic ( nextMethod . getModifiers ( ) ) && ( nextMethod . getParameterTypes ( ) . length == 1 ) ) { /* log . fine ( methodName + " is a valid setter method for the property " + propertyName +
 " with argument of type " + nextMethod . getParameterTypes ( ) [ 0 ] ) ; */
// Add its argument type to the array of setter types .
types . add ( nextMethod . getParameterTypes ( ) [ 0 ] ) ; } } return types ;


signature:
public class TextTableGridRenderer { /** * Renders the table . */
public void renderTable ( ) { } }

implementation:
for ( int i = 0 ; i < tableModel . getRowCount ( ) ; i ++ ) { int colOffset = 0 ; for ( int j = 0 ; j < tableModel . getColumnCount ( ) ; j ++ ) { // Print the contents of the table cell .
String valueToPrint = tableModel . get ( j , i ) ; valueToPrint = ( valueToPrint == null ) ? "" : valueToPrint ; gridModel . insert ( valueToPrint , colOffset , i ) ; // Pad spaces up to the column width if the contents are shorted .
Integer maxColumnSize = tableModel . getMaxColumnSize ( j ) ; int spaces = maxColumnSize - valueToPrint . length ( ) ; while ( spaces > 0 ) { gridModel . insert ( " " , colOffset + valueToPrint . length ( ) + spaces -- - 1 , i ) ; } // Shift to the next column .
colOffset += maxColumnSize ; } }


signature: public class SeleniumForm { private URL getAction ( ) { } }

implementation: String action = element . getAttribute ( "action" ) ; if ( action . isEmpty ( ) ) { action = driver . getCurrentUrl ( ) ; } return newUrlOrNull ( action ) ;


signature:
public class Queues { /** * Wraps a java . util . concurrent . BlockingQueue as a { @ link com . thesett . common . util . concurrent . BlockingQueue }
 * implementation .
 * @ param queue The blocking queue to wrap .
 * @ param < E > The type of queue element .
 * @ return The queue as a { @ link com . thesett . common . util . concurrent . BlockingQueue } implementation . */
public static < E > BlockingQueue < E > getBlockingQueue ( java . util . concurrent . BlockingQueue < E > queue ) { } }

implementation: return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , false , false , false ) ;


signature:
public class Queues { /** * Wraps a java . util . concurrent . BlockingQueue as a { @ link com . thesett . common . util . concurrent . BlockingQueue }
 * implementation .
 * @ param queue The blocking queue to wrap .
 * @ param < E > The type of queue element .
 * @ return The queue as a { @ link com . thesett . common . util . concurrent . BlockingQueue } implementation . */
public static < E > SizeableBlockingQueue < E > getSizeableBlockingQueue ( java . util . concurrent . BlockingQueue < E > queue ) { } }


signature:
public class Queues { /** * Wraps queue as a sizeable , atomically counted queue , as per the { @ link # getSizeableQueue } and
 * { @ link # getAtomicCountedQueue } methods .
 * @ param queue The queue to provide atomic counting and sizing of .
 * @ param < E > The type of queue element .
 * @ return An atomicically counted , sizeable queue . */
public static < E extends Sizeable > SizeableQueue < E > getAtomicCountedSizeableQueue ( java . util . Queue < E > queue ) { } }

implementation: return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , false , true , true ) ;


signature:
public class Queues { /** * Provides a transactional queue , that delays all queue manipulation operations until the transaction is committed ,
 * or erases them if it is rolled back .
 * @ param queue The queue to make transactional .
 * @ param < E > The type of queue element .
 * @ return A transactional queue . */
public static < E > Queue < E > getTransactionalQueue ( java . util . Queue < E > queue ) { } }

implementation: return new WrapperQueue < E > ( queue , new LinkedList < E > ( ) , true , false , false ) ;


signature:
public class Queues { /** * Provides a transactional requeue , that delays all queue manipulation operations until the transaction is
 * committed , or erases them if it is rolled back . As this is a requeue , the requeue buffer may be examined directly
 * and the queue fully supports browsing with iterators .
 * @ param queue The queue to use as the underlying queue implementation for the requeue .
 * @ param requeue The collection to use for the requeue buffer .
 * @ param < E > The type of queue element .
 * @ return A transactional requeue . */
public static < E > Queue < E > getTransactionalReQueue ( java . util . Queue < E > queue , Collection < E > requeue ) { } }

implementation: return new WrapperQueue < E > ( queue , requeue , true , false , false ) ;


signature:
public class Queues { /** * Wraps queue as a sizeable , transactional requeue , as per the { @ link # getSizeableQueue } and
 * { @ link # getTransactionalReQueue } methods .
 * @ param queue The queue to provide sizing and transactional operations on .
 * @ param requeue The requeue buffer implementation to use .
 * @ param < E > The type of queue element .
 * @ return An atomicically counted , sizeable queue . */
public static < E extends Sizeable > SizeableQueue < E > getSizeableTransactionalReQueue ( java . util . Queue < E > queue , Collection < E > requeue ) { } }

implementation: return new WrapperQueue < E > ( queue , requeue , true , true , false ) ;


signature:
public class Queues { /** * Wraps queue as a sizeable , atomically counted queue , transactional requeue , as per the { @ link # getSizeableQueue } ,
 * { @ link # getAtomicCountedQueue } , and { @ link # getTransactionalReQueue } methods .
 * @ param queue The queue to provide atomic counting , sizing and transactional operations on .
 * @ param requeue The requeue buffer implementation to use .
 * @ param < E > The type of queue element .
 * @ return An atomicically counted , sizeable queue . */
public static < E extends Sizeable > Queue < E > getAtomicCountedSizeableTransactionalReQueue ( java . util . Queue < E > queue , Collection < E > requeue ) { } }

implementation: return new WrapperQueue < E > ( queue , requeue , true , true , true ) ;


signature:
public class TypeHelper { /** * Gets the type of a specified object .
 * @ param o The object to get the type of .
 * @ return The type of the object . */
public static Type getTypeFromObject ( Object o ) { } }

implementation:
// Check if the object is null , in which case its type cannot be derived .
if ( o == null ) { return new UnknownType ( ) ; } // Check if the object is an attribute a and get its type that way if possible .
if ( o instanceof Attribute ) { return ( ( Attribute ) o ) . getType ( ) ; } // Return an approproate Type for the java primitive , wrapper or class type of the argument .
return new JavaType ( o ) ;


signature:
public class BaseQueueSearch { /** * Resets the search , clearing out the queue and setting it to contain just the start state node . */
public void reset ( ) { } }

implementation:
// Clear out the start states .
startStates . clear ( ) ; enqueuedOnce = false ; // Reset the queue to a fresh empty queue .
queue = createQueue ( ) ; // Clear the goal predicate .
goalPredicate = null ; // Reset the maximum steps limit
maxSteps = 0 ; // Reset the number of steps taken
searchSteps = 0 ; // Reset the repeated state filter if there is one .
if ( repeatedStateFilter != null ) { repeatedStateFilter . reset ( ) ; } // Reset the search alogorithm if it requires resettting .
searchAlgorithm . reset ( ) ;


signature:
public class BaseQueueSearch { /** * This logic enqueues all the start states , calling the { @ link # createSearchNode } method that concrete sub - classes
 * implement to specify the search node type . If there is a repeated state filter set up then this is attached to
 * the search nodes . This is called at the start of the search method to set up the queue into a state which is
 * ready for the search algorithm .
 * @ param startStates The set of start states to being the search at .
 * @ return The queue of search nodes for each of the start states .
 * @ throws IllegalStateException if no start states have been set for the search . */
public Queue < SearchNode < O , T > > enqueueStartStates ( Collection < T > startStates ) { } }

implementation:
// Check that there are some start states
if ( ! startStates . isEmpty ( ) ) { // Only enqueue the start states if they have not already been enqueued .
if ( ! enqueuedOnce ) { // Enqueue all the start states
for ( T nextStartState : startStates ) { // If the goal predicate has not been defined , try to set up the default from the initial search
// states .
if ( goalPredicate == null ) { goalPredicate = nextStartState . getDefaultGoalPredicate ( ) ; } // Make search nodes out of the start states using the abstract search node creation method ,
// subclasses override this to create different kinds of search node .
SearchNode newStartNode = createSearchNode ( nextStartState ) ; // Check if a repeated state filter has been applied and attach it to the start node if so .
if ( repeatedStateFilter != null ) { // Attach it to the start node .
newStartNode . setRepeatedStateFilter ( repeatedStateFilter ) ; } // Insert the new start search node onto the queue .
queue . offer ( newStartNode ) ; } } } else { // There are no start states so raise an exception because the search cannot be run without a start state .
throw new IllegalStateException ( "Cannot start the search because there are no start states defined. " + "Queue searches require some start states." , null ) ; } // Check that a goal predicate is set up .
if ( goalPredicate == null ) { throw new IllegalStateException ( "Cannot start the search because there is no goal predicate." , null ) ; } // Set the enqueuedOnce flag to indicate that the start states have already been enqueued .
enqueuedOnce = true ; return queue ;


signature:
public class BaseQueueSearch { /** * Implementation of the general queue search . The basic algorithm is simple : take the next element from the queue
 * and goal test it . If it is a goal then return it and stop the search . If it is not a goal then expand its
 * successor states and enqueue them and then repeat the procedure .
 * @ return The first { @ link SearchNode } corresponding to a goal state that is found or null if none can be found
 * after exhaustive searching . A return value of null should really mean that exhaustive searching has been
 * completed rather than some premature termination condition being reached . See the comment below about the
 * SearchNotExhaustiveException .
 * @ throws SearchNotExhaustiveException If the search stops before finding a solution or exhausting the search
 * space . Different search algorithms may fail for different reasons but in
 * particular it it is worth noting that if the maximum number of steps is
 * reached without exhausting the search space this will cause an exception to
 * be thrown rather than for this method to return null . */
public SearchNode < O , T > findGoalPath ( ) throws SearchNotExhaustiveException { } }

implementation:
// Delegate the search to the pluggable search algorithm .
return searchAlgorithm . search ( this , startStates , maxSteps , searchSteps ) ;


signature:
public class BaseQueueSearch { /** * Perform the search . This can be called multiple times to get successive results where more than one goal can be
 * found , if the algorithm supports this . In this case it should return null once no more goals can be found .
 * @ return The first state corresponding to a goal state that is found or null if none can be found after exhaustive
 * searching . A return value of null should really mean that exhaustive searching has been completed rather
 * than some premature termination condition being reached . See the comment below about the
 * SearchNotExhaustiveException .
 * @ throws SearchNotExhaustiveException If the search stops before finding a solution or exhausting the search
 * space . Different search algorithms may fail for different reasons but in
 * particular it it is worth noting that if the maximum number of steps is
 * reached without exhausting the search space this will cause an exception to
 * be thrown rather than for this method to return null . */
public T search ( ) throws SearchNotExhaustiveException { } }

implementation: SearchNode < O , T > path = findGoalPath ( ) ; if ( path != null ) { return path . getState ( ) ; } else { return null ; }


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

implementation:
Functor isOp = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; // Evaluate the second argument as a fully instantiated numeric value .
Term expressionValue = BuiltInUtils . evaluateAsNumeric ( isOp . getArgument ( 1 ) ) ; // This is used to record variables bound during the unification , so that they may be undone if the resolution
// state is backtracked over .
List < Variable > boundVariables = new LinkedList < Variable > ( ) ; // Unify against the LHS .
boolean matched = state . getUnifier ( ) . unifyInternal ( isOp . getArgument ( 0 ) , expressionValue , boundVariables , boundVariables ) ; for ( Variable binding : boundVariables ) { state . getVariableBindings ( ) . offer ( binding ) ; } return matched ;


signature:
public class IntRangeType { /** * Creates a new int range type with the specified name , if it does not already exist .
 * @ param name The name of the int 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 int range type .
 * @ throws IllegalArgumentException If min is not less than or equal to max , or the named type already exists . */
public static Type createInstance ( String name , int min , int max ) { } }

implementation:
// 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 ( INT_RANGE_TYPES ) { // Add the newly created type to the map of all types .
IntRangeType newType = new IntRangeType ( 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 .
IntRangeType oldType = INT_RANGE_TYPES . get ( name ) ; if ( ( oldType != null ) && ! oldType . equals ( newType ) ) { throw new IllegalArgumentException ( "The type '" + name + "' already exists and cannot be redefined." ) ; } else if ( ( oldType != null ) && oldType . equals ( newType ) ) { return oldType ; } else { INT_RANGE_TYPES . put ( name , newType ) ; return newType ; } }


signature:
public class IntRangeType { /** * { @ inheritDoc }
 * < p / > Beware that as this operation creates a fully expanded set of the integer range in memory , large ranges may
 * use a lot of memory . Consider using the { @ link # getAllPossibleValuesIterator ( ) } method instead , as it lazily
 * creates the values on demand . */
public Set < Integer > getAllPossibleValuesSet ( ) throws InfiniteValuesException { } }

implementation: Set < Integer > results = new HashSet < Integer > ( ) ; for ( int i = minValue ; i <= maxValue ; i ++ ) { results . add ( i ) ; } return results ;


signature:
public class Exponential { /** * Evaluates the arithmetic operator on its two numeric arguments .
 * @ param firstNumber The first argument .
 * @ param secondNumber The second argument .
 * @ return The result of performing the arithmetic operator on its arguments . */
protected NumericType evaluate ( NumericType firstNumber , NumericType secondNumber ) { } }

implementation:
// If either of the arguments is a real number , then use real number arithmetic , otherwise use integer arithmetic .
if ( firstNumber . isInteger ( ) && secondNumber . isInteger ( ) ) { int n1 = firstNumber . intValue ( ) ; int n2 = secondNumber . intValue ( ) ; int result = 1 ; for ( int i = 0 ; i < n2 ; i ++ ) { result *= n1 ; } return new IntLiteral ( result ) ; } else { return new DoubleLiteral ( Math . pow ( firstNumber . doubleValue ( ) , secondNumber . doubleValue ( ) ) ) ; }


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

implementation:
// Flatten the head goal on the disjunction operator to produce a series of choice points .
Functor goalTerm = state . getGoalStack ( ) . poll ( ) . getFunctor ( ) ; disjuncts = TermUtils . flattenTerm ( goalTerm , Functor . class , state . getInterner ( ) . internFunctorName ( ";" , 2 ) ) ; return true ;


signature:
public class Disjunction { /** * { @ inheritDoc } */
public void createContinuationStates ( ResolutionState state ) { } }

implementation: for ( Functor disjunct : disjuncts ) { BuiltInFunctor newGoal = state . getBuiltInTransform ( ) . apply ( disjunct ) ; newGoal . setParentChoicePointState ( state ) ; state . createContinuationStatesForGoal ( newGoal ) ; }


signature:
public class SchemaDefinitionImpl { /** * ( non - Javadoc )
 * @ see
 * com . groupon . novie . SchemaConfig # areLinked ( com . groupon . novie . internal . engine
 * . internal . SqlTable , com . groupon . novie . internal . engine . internal . SqlTable ) */
@ Override public boolean areLinked ( SqlTable table1 , SqlTable table2 ) { } }

implementation: return predecessorRelation . get ( table1 . getTableName ( ) ) . containsKey ( table2 . getTableName ( ) ) ;


signature:
public class SchemaDefinitionImpl { /** * ( non - Javadoc )
 * @ see com . groupon . novie . SchemaConfig # getDimensionByName ( java . lang . String ,
 * java . lang . String ) */
@ Override public DimensionTable getDimensionByName ( String dimensionName , String tzNameAlias ) { } }

implementation:
DimensionTable dimensionTable ; if ( StringUtils . isBlank ( tzNameAlias ) || ( StringUtils . isNotBlank ( tzNameAlias ) && tzNameAlias . equals ( getDefaultTimezone ( ) ) ) ) { dimensionTable = dimensions . get ( dimensionName . toUpperCase ( ) ) ; } else { if ( ! isTimeZoneSupported ( tzNameAlias ) ) { LOG . error ( tzNameAlias + " TZ is not supported, do not consider it." ) ; dimensionTable = dimensions . get ( dimensionName . toUpperCase ( ) ) ; } else { String tzName = tzNamesAliases . get ( tzNameAlias ) ; dimensionTable = alternateDimensions . get ( Pair . of ( dimensionName . toUpperCase ( ) , tzName ) ) ; if ( dimensionTable == null ) { // No alternateTable for this dimension / tz pair
dimensionTable = dimensions . get ( dimensionName . toUpperCase ( ) ) ; } } } if ( dimensionTable == null ) { throw new IllegalArgumentException ( "Invalid SqlTable for the dimension: " + dimensionName ) ; } return dimensionTable ;


signature:
public class SchemaDefinitionImpl { /** * ( non - Javadoc )
 * @ see com . groupon . novie . SchemaConfig # getMeasuresColumn ( ) */
@ Override public List < AbstractSqlColumn > getMeasuresColumn ( ) { } }

implementation: return Collections . unmodifiableList ( Lists . newArrayList ( factTable . getMeasuresColumn ( ) . values ( ) ) ) ;


signature:
public class SchemaDefinitionImpl { /** * { @ inheritDoc SchemaDefinition }
 * { @ link SchemaDefinition # getMeasuresByName ( String ) } */
@ Override public Optional < AbstractSqlColumn > getMeasuresByName ( String informationName ) { } }

implementation: for ( AbstractSqlColumn column : factTable . getMeasuresColumn ( ) . values ( ) ) { if ( column . getBusinessName ( ) . equalsIgnoreCase ( informationName ) ) { return Optional . of ( column ) ; } } return Optional . absent ( ) ;


signature:
public class SchemaDefinitionImpl { /** * ( non - Javadoc )
 * @ see
 * com . groupon . novie . SchemaConfig # getInformationColumn ( com . groupon . novie
 * . internal . engine . internal . DimensionTable , java . lang . String ) */
@ Override public AbstractSqlColumn getInformationColumn ( DimensionTable dimension , String informationName ) { } }

implementation: final AbstractSqlColumn sqlTableColumn = dimension . getSqlTableColumnByInformationName ( informationName ) ; if ( sqlTableColumn == null ) { throw new IllegalArgumentException ( "Invalid sqlTableColumn for the informationName: " + informationName ) ; } return sqlTableColumn ;


signature:
public class SchemaDefinitionImpl { /** * ( non - Javadoc )
 * @ see com . groupon . novie . SchemaConfig # isValidDimension ( java . lang . String ,
 * java . lang . String ) */
@ Override public boolean isValidDimension ( String dimensionName , String informationName ) { } }

implementation: if ( StringUtils . isNotBlank ( dimensionName ) ) { DimensionTable dim = dimensions . get ( dimensionName . toUpperCase ( ) ) ; if ( dim == null ) { return false ; } if ( StringUtils . isBlank ( informationName ) ) { return true ; } if ( dim . getSqlTableColumnByInformationName ( informationName . toUpperCase ( ) ) != null ) { return true ; } } return false ;


signature:
public class SchemaDefinitionImpl { /** * ( non - Javadoc )
 * @ see com . groupon . novie . SchemaDefinition # isMandatoryDimension ( java . lang . String ) */
@ Override public boolean isMandatoryDimension ( String dimensionName ) { } }

implementation: if ( isValidDimension ( dimensionName , null ) ) { return mandatoryDimensionNames . contains ( dimensionName . toUpperCase ( Locale . ENGLISH ) ) ; } return false ;


signature:
public class SchemaDefinitionImpl { /** * ( non - Javadoc )
 * @ see com . groupon . novie . SchemaConfig # getInformationType ( java . lang . String ,
 * java . lang . String ) */
@ Override public ColumnDataType getInformationType ( String dimensionName , String informationName ) { } }

implementation: if ( StringUtils . isNotBlank ( dimensionName ) ) { DimensionTable dim = dimensions . get ( dimensionName . toUpperCase ( ) ) ; if ( dim == null ) { throw new IllegalArgumentException ( "Unknown dimension named " + dimensionName + "." ) ; } if ( StringUtils . isBlank ( informationName ) ) { return dim . getDefaultSearchColumn ( ) . getColumnType ( ) ; } AbstractSqlColumn information = dim . getSqlTableColumnByInformationName ( informationName ) ; if ( information == null ) { throw new IllegalArgumentException ( "Unknown information named " + informationName + " for dimension " + dimensionName + "." ) ; } return information . getColumnType ( ) ; } throw new IllegalArgumentException ( "Dimension name can't be null or blank" ) ;


signature:
public class SchemaDefinitionImpl { /** * Add a new supported tz . Add one aliase with the same name
 * @ param tzName */
public void addSupportedTZ ( String tzName ) { } }

implementation: if ( ! StringUtils . isBlank ( tzName ) && ! tzNamesAliases . containsKey ( tzName . trim ( ) ) ) { tzNamesAliases . put ( tzName . trim ( ) , tzName . trim ( ) ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "Endpoint " + this . getEndPointName ( ) + " - add support of TZ: " + tzName ) ; } }


signature:
public class SchemaDefinitionImpl { /** * Timezone is case sensitive */
public void addTZAlternateDimension ( String orignalDimensionName , DimensionTable alternateDimension , String tzName ) { } }

implementation: addSupportedTZ ( tzName ) ; if ( tzNamesAliases . containsValue ( tzName ) ) { sqlTables . put ( alternateDimension . getTableName ( ) , alternateDimension ) ; alternateDimensions . put ( Pair . of ( orignalDimensionName . toUpperCase ( ) , tzName ) , alternateDimension ) ; } else { LOG . error ( "Unsuported timezone: " + tzName ) ; }


signature:
public class SchemaDefinitionImpl { /** * Add a dimension as mandatory .
 * Mandatory dimension names are stored in upper case .
 * @ param table The dimension table
 * @ param mandatory Add if true , remove otherwise */
public void addDimension ( DimensionTable table , boolean mandatory ) { } }

implementation: sqlTables . put ( table . getTableName ( ) , table ) ; dimensions . put ( table . getDimensionName ( ) . toUpperCase ( ) , table ) ; if ( mandatory ) { mandatoryDimensionNames . add ( table . getDimensionName ( ) . toUpperCase ( Locale . ENGLISH ) ) ; }


signature:
public class SchemaDefinitionImpl { /** * Build the configuration links ( ie Foreigns key ) . Checks the validity of
 * the configuration .
 * @ throws Exception */
public Collection < Error > buildAndValidateConfig ( ) { } }

implementation:
Collection < Error > returnValue = new ArrayList < Error > ( ) ; // Check default TZ
if ( defaultTimezone == null ) { returnValue . add ( new Error ( "No default Timezone configured" ) ) ; } for ( Pair < Pair < String , String > , Pair < String , String > > fkRelationship : fkRelationshipSet ) { Optional < PhysicalSqlColumn > left = getColumnByPair ( fkRelationship . getLeft ( ) ) ; Optional < PhysicalSqlColumn > right = getColumnByPair ( fkRelationship . getRight ( ) ) ; if ( ! left . isPresent ( ) ) { returnValue . add ( new Error ( "Column " + fkRelationship . getLeft ( ) . getRight ( ) + " in table " + fkRelationship . getLeft ( ) . getLeft ( ) + " doesn't exist." ) ) ; } else if ( ! right . isPresent ( ) ) { returnValue . add ( new Error ( "Column " + fkRelationship . getRight ( ) . getRight ( ) + " in table " + fkRelationship . getRight ( ) . getLeft ( ) + " doesn't exist." ) ) ; } else { buildSqlForeignKey ( left . get ( ) , right . get ( ) ) ; } } // Check Alternate Tables
for ( Entry < Pair < String , String > , DimensionTable > entry : alternateDimensions . entrySet ( ) ) { DimensionTable dim = dimensions . get ( entry . getKey ( ) . getLeft ( ) ) ; if ( dim == null ) { returnValue . add ( new Error ( "Original dimension " + entry . getKey ( ) . getLeft ( ) + " does not exist." ) ) ; } else { if ( ! dim . isEquivalent ( entry . getValue ( ) , returnValue ) ) { returnValue . add ( new Error ( "Dimension " + entry . getValue ( ) . getDimensionName ( ) + " is not equivalent to " + dim . getDimensionName ( ) + "." ) ) ; } } } return returnValue ;


signature:
public class SchemaDefinitionImpl { /** * { @ inheritDoc SchemaDefinition }
 * { @ link SchemaDefinition # isValidMeasure ( String ) } */
@ Override public boolean isValidMeasure ( String name ) { } }

implementation: for ( AbstractSqlColumn column : factTable . getMeasuresColumn ( ) . values ( ) ) { if ( column . getBusinessName ( ) . equals ( name ) ) { return true ; } } return false ;


signature:
public class TermUtils { /** * Calculates the set of free variables in a term .
 * @ param query The term to calculate the free non - anonymous variable set from .
 * @ return A set of variables that are free and non - anonymous in the term . */
public static Set < Variable > findFreeVariables ( Term query ) { } }

implementation: QueueBasedSearchMethod < Term , Term > freeVarSearch = new DepthFirstSearch < Term , Term > ( ) ; freeVarSearch . reset ( ) ; freeVarSearch . addStartState ( query ) ; freeVarSearch . setGoalPredicate ( new FreeVariablePredicate ( ) ) ; return ( Set < Variable > ) ( Set ) Searches . setOf ( freeVarSearch ) ;


signature:
public class TermUtils { /** * Calculates the set of free and non - anonymous variables in a term . This is the set of variables that a user query
 * usually wants to be made aware of .
 * @ param query The term to calculate the free non - anonymous variable set from .
 * @ return A set of variables that are free and non - anonymous in the term . */
public static Set < Variable > findFreeNonAnonymousVariables ( Term query ) { } }

implementation: QueueBasedSearchMethod < Term , Term > freeVarSearch = new DepthFirstSearch < Term , Term > ( ) ; freeVarSearch . reset ( ) ; freeVarSearch . addStartState ( query ) ; freeVarSearch . setGoalPredicate ( new FreeNonAnonymousVariablePredicate ( ) ) ; return ( Set < Variable > ) ( Set ) Searches . setOf ( freeVarSearch ) ;


signature:
public class TermUtils { /** * Flattens a sequence of terms as a symbol seperated argument list . Terms that have been parsed as a bracketed
 * expressions will not be flattened . All of the terms in the list must sub sub - classes of a specified super class .
 * This is usefull , for example , when parsing a sequence of functors in a clause body , in order to check that all of
 * the body members really are functors and not just terms .
 * < p / > For example , ' a , b , c ' is broken into the list { a , b , c } on the symbol ' , ' . The example , ' a , ( b , c ) , d ' is
 * broken into the list { a , ( b , c ) , d } on the symbol ' , ' and so on .
 * @ param < T > The type of the class that all flattened terms must extend .
 * @ param term The term to flatten .
 * @ param superClass The root class that all flattened terms must extend .
 * @ param symbolToFlattenOn A symbol of fixity 2 to flatten on .
 * @ param interner The functor and variable interner for the namespace the term to flatten is in .
 * @ return A sequence of terms parsed as a term , then flattened back into a list seperated on commas .
 * @ throws SourceCodeException If any of the extracted terms encountered do not extend the superclass . */
public static < T extends Term > List < T > flattenTerm ( Term term , Class < T > superClass , String symbolToFlattenOn , VariableAndFunctorInterner interner ) throws SourceCodeException { } }

implementation:
List < T > terms = new LinkedList < T > ( ) ; // Used to hold the next term to examine as operators are flattened .
Term nextTerm = term ; // Used to indicate when there are no more operators to flatten .
boolean mayBeMoreCommas = true ; // Get the functor name of the symbol to flatten on .
int symbolName = interner . internFunctorName ( symbolToFlattenOn , 2 ) ; // Walk down the terms matching symbols and flattening them into a list of terms .
while ( mayBeMoreCommas ) { if ( ! nextTerm . isBracketed ( ) && ( nextTerm instanceof Functor ) && ( symbolName == ( ( ( Functor ) nextTerm ) . getName ( ) ) ) ) { Functor op = ( Functor ) nextTerm ; Term termToExtract = op . getArgument ( 0 ) ; if ( superClass . isInstance ( termToExtract ) ) { terms . add ( superClass . cast ( termToExtract ) ) ; nextTerm = op . getArgument ( 1 ) ; } else { throw new SourceCodeException ( "The term " + termToExtract + " is expected to extend " + superClass + " but does not." , null , null , null , termToExtract . getSourceCodePosition ( ) ) ; } } else { if ( superClass . isInstance ( nextTerm ) ) { terms . add ( superClass . cast ( nextTerm ) ) ; mayBeMoreCommas = false ; } else { throw new SourceCodeException ( "The term " + nextTerm + " is expected to extend " + superClass + " but does not." , null , null , null , nextTerm . getSourceCodePosition ( ) ) ; } } } return terms ;


signature:
public class TermUtils { /** * Flattens a sequence of terms as a symbol seperated argument list . Terms that have been parsed as a bracketed
 * expressions will not be flattened . All of the terms in the list must sub sub - classes of a specified super class .
 * This is usefull , for example , when parsing a sequence of functors in a clause body , in order to check that all of
 * the body members really are functors and not just terms .
 * < p / > For example , ' a , b , c ' is broken into the list { a , b , c } on the symbol ' , ' . The example , ' a , ( b , c ) , d ' is
 * broken into the list { a , ( b , c ) , d } on the symbol ' , ' and so on .
 * @ param < T > The type of the class that all flattened terms must extend .
 * @ param term The term to flatten .
 * @ param superClass The root class that all flattened terms must extend .
 * @ param internedName The interned name of the symbol to flatten on .
 * @ return A sequence of terms parsed as a term , then flattened back into a list seperated on commas . */
public static < T extends Term > List < T > flattenTerm ( Term term , Class < T > superClass , int internedName ) { } }

implementation:
List < T > terms = new LinkedList < T > ( ) ; // Used to hold the next term to examine as operators are flattened .
Term nextTerm = term ; // Used to indicate when there are no more operators to flatten .
boolean mayBeMore = true ; // Walk down the terms matching symbols and flattening them into a list of terms .
while ( mayBeMore ) { if ( ! nextTerm . isBracketed ( ) && ( nextTerm instanceof Functor ) && ( internedName == ( ( ( Functor ) nextTerm ) . getName ( ) ) ) ) { Functor op = ( Functor ) nextTerm ; Term termToExtract = op . getArgument ( 0 ) ; if ( superClass . isInstance ( termToExtract ) ) { terms . add ( superClass . cast ( termToExtract ) ) ; nextTerm = op . getArgument ( 1 ) ; } else { throw new IllegalStateException ( "The term " + termToExtract + " is expected to extend " + superClass + " but does not." ) ; } } else { if ( superClass . isInstance ( nextTerm ) ) { terms . add ( superClass . cast ( nextTerm ) ) ; mayBeMore = false ; } else { throw new IllegalStateException ( "The term " + nextTerm + " is expected to extend " + superClass + " but does not." ) ; } } } return terms ;


signature:
public class TermUtils { /** * Converts a term into a clause . The term must be a functor . If it is a functor corresponding to the ' : - ' symbol it
 * is a clause with a head and a body . If it is a functor corresponding to the ' ? - ' symbol it is a query clause with
 * no head but must have a body . If it is neither but is a functor it is interpreted as a program clause ' : - ' with
 * no body , that is , a fact .
 * @ param term The term to convert to a top - level clause .
 * @ param interner The functor and variable name interner for the namespace the term to convert is in .
 * @ return A clause for the term , or < tt > null < / tt > if it cannot be converted .
 * @ throws SourceCodeException If the term to convert to a clause does not form a valid clause . */
public static Clause convertToClause ( Term term , VariableAndFunctorInterner interner ) throws SourceCodeException { } }

implementation:
// Check if the top level term is a query , an implication or neither and reduce the term into a clause
// accordingly .
if ( term instanceof OpSymbol ) { OpSymbol symbol = ( OpSymbol ) term ; if ( ":-" . equals ( symbol . getTextName ( ) ) ) { List < Functor > flattenedArgs = flattenTerm ( symbol . getArgument ( 1 ) , Functor . class , "," , interner ) ; return new Clause < Functor > ( ( Functor ) symbol . getArgument ( 0 ) , flattenedArgs . toArray ( new Functor [ flattenedArgs . size ( ) ] ) ) ; } else if ( "?-" . equals ( symbol . getTextName ( ) ) ) { List < Functor > flattenedArgs = flattenTerm ( symbol . getArgument ( 0 ) , Functor . class , "," , interner ) ; return new Clause < Functor > ( null , flattenedArgs . toArray ( new Functor [ flattenedArgs . size ( ) ] ) ) ; } } if ( term instanceof Functor ) { return new Clause < Functor > ( ( Functor ) term , null ) ; } else { throw new SourceCodeException ( "Only functors can for a clause body, not " + term + "." , null , null , null , term . getSourceCodePosition ( ) ) ; }


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

implementation: float h1 = ( ( HeuristicSearchNode ) object1 ) . getH ( ) ; float h2 = ( ( HeuristicSearchNode ) object2 ) . getH ( ) ; return ( h1 > h2 ) ? 1 : ( ( h1 < h2 ) ? - 1 : 0 ) ;


signature:
public class FileUtils { /** * Reads a text file as a string .
 * @ param filename The name of the file .
 * @ return The contents of the file . */
public static String readFileAsString ( String filename ) { } }

implementation: BufferedInputStream is = null ; try { is = new BufferedInputStream ( new FileInputStream ( filename ) ) ; } catch ( FileNotFoundException e ) { throw new IllegalStateException ( e ) ; } return readStreamAsString ( is ) ;


signature:
public class FileUtils { /** * Reads a text file as a string .
 * @ param file The file .
 * @ return The contents of the file . */
public static String readFileAsString ( File file ) { } }

implementation: BufferedInputStream is = null ; try { is = new BufferedInputStream ( new FileInputStream ( file ) ) ; } catch ( FileNotFoundException e ) { throw new IllegalStateException ( e ) ; } return readStreamAsString ( is ) ;


signature:
public class FileUtils { /** * Writes an object , using its ' toString ' method , to the named file . The object may optionally be appended to the
 * file , or may overwrite it .
 * @ param outputFileName The name of the file to write the output to .
 * @ param toWrite The object to write to the file .
 * @ param append < tt > true < / tt > to append to the file , < tt > false < / tt > to overwrite . */
public static void writeObjectToFile ( String outputFileName , Object toWrite , boolean append ) { } }

implementation:
// Open the output file .
Writer resultWriter ; try { resultWriter = new FileWriter ( outputFileName , append ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Unable to open the output file '" + outputFileName + "' for writing." , e ) ; } // Write the object into the output file .
try { resultWriter . write ( toWrite . toString ( ) ) ; resultWriter . flush ( ) ; resultWriter . close ( ) ; } catch ( IOException e ) { throw new IllegalStateException ( "There was an error whilst writing to the output file '" + outputFileName + "'." , e ) ; }


signature:
public class FileUtils { /** * Reads the contents of a reader , one line at a time until the end of stream is encountered , and returns all
 * together as a string .
 * @ param is The reader .
 * @ return The contents of the reader . */
private static String readStreamAsString ( BufferedInputStream is ) { } }

implementation: try { byte [ ] data = new byte [ 4096 ] ; StringBuffer inBuffer = new StringBuffer ( ) ; int read ; while ( ( read = is . read ( data ) ) != - 1 ) { String s = new String ( data , 0 , read ) ; inBuffer . append ( s ) ; } return inBuffer . toString ( ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; }


signature:
public class SizeableLinkedList { /** * Appends the specified element to the end of this list ( optional operation ) .
 * < p / > Lists that support this operation may place limitations on what elements may be added to this list . In
 * particular , some lists will refuse to add null elements , and others will impose restrictions on the type of
 * elements that may be added . List classes should clearly specify in their documentation any restrictions on what
 * elements may be added .
 * @ param o element to be appended to this list .
 * @ return < tt > true < / tt > ( as per the general contract of the < tt > Collection . add < / tt > method ) .
 * @ throws UnsupportedOperationException if the < tt > add < / tt > method is not supported by this list .
 * @ throws ClassCastException if the class of the specified element prevents it from being added to this
 * list .
 * @ throws NullPointerException if the specified element is null and this list does not support null
 * elements .
 * @ throws IllegalArgumentException if some aspect of this element prevents it from being added to this list . */
public boolean add ( T o ) { } }

implementation: boolean result = super . add ( o ) ; sizeOf += ( result ) ? o . sizeof ( ) : 0 ; return result ;


signature:
public class SizeableLinkedList { /** * Removes the first occurrence in this list of the specified element ( optional operation ) . If this list does not
 * contain the element , it is unchanged . More formally , removes the element with the lowest index i such that < tt >
 * ( o = = null ? get ( i ) = = null : o . equals ( get ( i ) ) ) < / tt > ( if such an element exists ) .
 * @ param o element to be removed from this list , if present .
 * @ return < tt > true < / tt > if this list contained the specified element .
 * @ throws ClassCastException if the type of the specified element is incompatible with this list
 * ( optional ) .
 * @ throws NullPointerException if the specified element is null and this list does not support null
 * elements ( optional ) .
 * @ throws UnsupportedOperationException if the < tt > remove < / tt > method is not supported by this list . */
public boolean remove ( Object o ) { } }

implementation: boolean result = super . remove ( o ) ; sizeOf -= ( ( o instanceof Sizeable ) && result ) ? ( ( Sizeable ) o ) . sizeof ( ) : 0 ; return result ;